three.js 794 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '58dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. String.prototype.trim = String.prototype.trim || function () {
  16. return this.replace( /^\s+|\s+$/g, '' );
  17. };
  18. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  19. THREE.extend = function ( obj, source ) {
  20. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  21. if ( Object.keys ) {
  22. var keys = Object.keys( source );
  23. for (var i = 0, il = keys.length; i < il; i++) {
  24. var prop = keys[i];
  25. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  26. }
  27. } else {
  28. var safeHasOwnProperty = {}.hasOwnProperty;
  29. for ( var prop in source ) {
  30. if ( safeHasOwnProperty.call( source, prop ) ) {
  31. obj[prop] = source[prop];
  32. }
  33. }
  34. }
  35. return obj;
  36. };
  37. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  38. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  39. // requestAnimationFrame polyfill by Erik Möller
  40. // fixes from Paul Irish and Tino Zijdel
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  45. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( window.requestAnimationFrame === undefined ) {
  49. window.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  57. }() );
  58. // GL STATE CONSTANTS
  59. THREE.CullFaceNone = 0;
  60. THREE.CullFaceBack = 1;
  61. THREE.CullFaceFront = 2;
  62. THREE.CullFaceFrontBack = 3;
  63. THREE.FrontFaceDirectionCW = 0;
  64. THREE.FrontFaceDirectionCCW = 1;
  65. // SHADOWING TYPES
  66. THREE.BasicShadowMap = 0;
  67. THREE.PCFShadowMap = 1;
  68. THREE.PCFSoftShadowMap = 2;
  69. // MATERIAL CONSTANTS
  70. // side
  71. THREE.FrontSide = 0;
  72. THREE.BackSide = 1;
  73. THREE.DoubleSide = 2;
  74. // shading
  75. THREE.NoShading = 0;
  76. THREE.FlatShading = 1;
  77. THREE.SmoothShading = 2;
  78. // colors
  79. THREE.NoColors = 0;
  80. THREE.FaceColors = 1;
  81. THREE.VertexColors = 2;
  82. // blending modes
  83. THREE.NoBlending = 0;
  84. THREE.NormalBlending = 1;
  85. THREE.AdditiveBlending = 2;
  86. THREE.SubtractiveBlending = 3;
  87. THREE.MultiplyBlending = 4;
  88. THREE.CustomBlending = 5;
  89. // custom blending equations
  90. // (numbers start from 100 not to clash with other
  91. // mappings to OpenGL constants defined in Texture.js)
  92. THREE.AddEquation = 100;
  93. THREE.SubtractEquation = 101;
  94. THREE.ReverseSubtractEquation = 102;
  95. // custom blending destination factors
  96. THREE.ZeroFactor = 200;
  97. THREE.OneFactor = 201;
  98. THREE.SrcColorFactor = 202;
  99. THREE.OneMinusSrcColorFactor = 203;
  100. THREE.SrcAlphaFactor = 204;
  101. THREE.OneMinusSrcAlphaFactor = 205;
  102. THREE.DstAlphaFactor = 206;
  103. THREE.OneMinusDstAlphaFactor = 207;
  104. // custom blending source factors
  105. //THREE.ZeroFactor = 200;
  106. //THREE.OneFactor = 201;
  107. //THREE.SrcAlphaFactor = 204;
  108. //THREE.OneMinusSrcAlphaFactor = 205;
  109. //THREE.DstAlphaFactor = 206;
  110. //THREE.OneMinusDstAlphaFactor = 207;
  111. THREE.DstColorFactor = 208;
  112. THREE.OneMinusDstColorFactor = 209;
  113. THREE.SrcAlphaSaturateFactor = 210;
  114. // TEXTURE CONSTANTS
  115. THREE.MultiplyOperation = 0;
  116. THREE.MixOperation = 1;
  117. THREE.AddOperation = 2;
  118. // Mapping modes
  119. THREE.UVMapping = function () {};
  120. THREE.CubeReflectionMapping = function () {};
  121. THREE.CubeRefractionMapping = function () {};
  122. THREE.SphericalReflectionMapping = function () {};
  123. THREE.SphericalRefractionMapping = function () {};
  124. // Wrapping modes
  125. THREE.RepeatWrapping = 1000;
  126. THREE.ClampToEdgeWrapping = 1001;
  127. THREE.MirroredRepeatWrapping = 1002;
  128. // Filters
  129. THREE.NearestFilter = 1003;
  130. THREE.NearestMipMapNearestFilter = 1004;
  131. THREE.NearestMipMapLinearFilter = 1005;
  132. THREE.LinearFilter = 1006;
  133. THREE.LinearMipMapNearestFilter = 1007;
  134. THREE.LinearMipMapLinearFilter = 1008;
  135. // Data types
  136. THREE.UnsignedByteType = 1009;
  137. THREE.ByteType = 1010;
  138. THREE.ShortType = 1011;
  139. THREE.UnsignedShortType = 1012;
  140. THREE.IntType = 1013;
  141. THREE.UnsignedIntType = 1014;
  142. THREE.FloatType = 1015;
  143. // Pixel types
  144. //THREE.UnsignedByteType = 1009;
  145. THREE.UnsignedShort4444Type = 1016;
  146. THREE.UnsignedShort5551Type = 1017;
  147. THREE.UnsignedShort565Type = 1018;
  148. // Pixel formats
  149. THREE.AlphaFormat = 1019;
  150. THREE.RGBFormat = 1020;
  151. THREE.RGBAFormat = 1021;
  152. THREE.LuminanceFormat = 1022;
  153. THREE.LuminanceAlphaFormat = 1023;
  154. // Compressed texture formats
  155. THREE.RGB_S3TC_DXT1_Format = 2001;
  156. THREE.RGBA_S3TC_DXT1_Format = 2002;
  157. THREE.RGBA_S3TC_DXT3_Format = 2003;
  158. THREE.RGBA_S3TC_DXT5_Format = 2004;
  159. /*
  160. // Potential future PVRTC compressed texture formats
  161. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  162. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  163. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  164. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  165. */
  166. /**
  167. * @author mrdoob / http://mrdoob.com/
  168. */
  169. THREE.Color = function ( value ) {
  170. if ( value !== undefined ) this.set( value );
  171. return this;
  172. };
  173. THREE.Color.prototype = {
  174. constructor: THREE.Color,
  175. r: 1, g: 1, b: 1,
  176. set: function ( value ) {
  177. switch ( typeof value ) {
  178. case "number":
  179. this.setHex( value );
  180. break;
  181. case "string":
  182. this.setStyle( value );
  183. break;
  184. }
  185. },
  186. setHex: function ( hex ) {
  187. hex = Math.floor( hex );
  188. this.r = ( hex >> 16 & 255 ) / 255;
  189. this.g = ( hex >> 8 & 255 ) / 255;
  190. this.b = ( hex & 255 ) / 255;
  191. return this;
  192. },
  193. setRGB: function ( r, g, b ) {
  194. this.r = r;
  195. this.g = g;
  196. this.b = b;
  197. return this;
  198. },
  199. setHSL: function ( h, s, l ) {
  200. // h,s,l ranges are in 0.0 - 1.0
  201. if ( s === 0 ) {
  202. this.r = this.g = this.b = l;
  203. } else {
  204. var hue2rgb = function ( p, q, t ) {
  205. if ( t < 0 ) t += 1;
  206. if ( t > 1 ) t -= 1;
  207. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  208. if ( t < 1 / 2 ) return q;
  209. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  210. return p;
  211. };
  212. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  213. var q = ( 2 * l ) - p;
  214. this.r = hue2rgb( q, p, h + 1 / 3 );
  215. this.g = hue2rgb( q, p, h );
  216. this.b = hue2rgb( q, p, h - 1 / 3 );
  217. }
  218. return this;
  219. },
  220. setStyle: function ( style ) {
  221. // rgb(255,0,0)
  222. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  223. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  224. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  225. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  226. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  227. return this;
  228. }
  229. // rgb(100%,0%,0%)
  230. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  231. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  232. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  233. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  234. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  235. return this;
  236. }
  237. // #ff0000
  238. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ], 16 ) );
  241. return this;
  242. }
  243. // #f00
  244. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  245. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  246. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  247. return this;
  248. }
  249. // red
  250. if ( /^(\w+)$/i.test( style ) ) {
  251. this.setHex( THREE.ColorKeywords[ style ] );
  252. return this;
  253. }
  254. },
  255. copy: function ( color ) {
  256. this.r = color.r;
  257. this.g = color.g;
  258. this.b = color.b;
  259. return this;
  260. },
  261. copyGammaToLinear: function ( color ) {
  262. this.r = color.r * color.r;
  263. this.g = color.g * color.g;
  264. this.b = color.b * color.b;
  265. return this;
  266. },
  267. copyLinearToGamma: function ( color ) {
  268. this.r = Math.sqrt( color.r );
  269. this.g = Math.sqrt( color.g );
  270. this.b = Math.sqrt( color.b );
  271. return this;
  272. },
  273. convertGammaToLinear: function () {
  274. var r = this.r, g = this.g, b = this.b;
  275. this.r = r * r;
  276. this.g = g * g;
  277. this.b = b * b;
  278. return this;
  279. },
  280. convertLinearToGamma: function () {
  281. this.r = Math.sqrt( this.r );
  282. this.g = Math.sqrt( this.g );
  283. this.b = Math.sqrt( this.b );
  284. return this;
  285. },
  286. getHex: function () {
  287. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  288. },
  289. getHexString: function () {
  290. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  291. },
  292. getHSL: function () {
  293. var hsl = { h: 0, s: 0, l: 0 };
  294. return function () {
  295. // h,s,l ranges are in 0.0 - 1.0
  296. var r = this.r, g = this.g, b = this.b;
  297. var max = Math.max( r, g, b );
  298. var min = Math.min( r, g, b );
  299. var hue, saturation;
  300. var lightness = ( min + max ) / 2.0;
  301. if ( min === max ) {
  302. hue = 0;
  303. saturation = 0;
  304. } else {
  305. var delta = max - min;
  306. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  307. switch ( max ) {
  308. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  309. case g: hue = ( b - r ) / delta + 2; break;
  310. case b: hue = ( r - g ) / delta + 4; break;
  311. }
  312. hue /= 6;
  313. }
  314. hsl.h = hue;
  315. hsl.s = saturation;
  316. hsl.l = lightness;
  317. return hsl;
  318. };
  319. }(),
  320. getStyle: function () {
  321. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  322. },
  323. offsetHSL: function ( h, s, l ) {
  324. var hsl = this.getHSL();
  325. hsl.h += h; hsl.s += s; hsl.l += l;
  326. this.setHSL( hsl.h, hsl.s, hsl.l );
  327. return this;
  328. },
  329. add: function ( color ) {
  330. this.r += color.r;
  331. this.g += color.g;
  332. this.b += color.b;
  333. return this;
  334. },
  335. addColors: function ( color1, color2 ) {
  336. this.r = color1.r + color2.r;
  337. this.g = color1.g + color2.g;
  338. this.b = color1.b + color2.b;
  339. return this;
  340. },
  341. addScalar: function ( s ) {
  342. this.r += s;
  343. this.g += s;
  344. this.b += s;
  345. return this;
  346. },
  347. multiply: function ( color ) {
  348. this.r *= color.r;
  349. this.g *= color.g;
  350. this.b *= color.b;
  351. return this;
  352. },
  353. multiplyScalar: function ( s ) {
  354. this.r *= s;
  355. this.g *= s;
  356. this.b *= s;
  357. return this;
  358. },
  359. lerp: function ( color, alpha ) {
  360. this.r += ( color.r - this.r ) * alpha;
  361. this.g += ( color.g - this.g ) * alpha;
  362. this.b += ( color.b - this.b ) * alpha;
  363. return this;
  364. },
  365. equals: function ( c ) {
  366. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  367. },
  368. clone: function () {
  369. return new THREE.Color().setRGB( this.r, this.g, this.b );
  370. }
  371. };
  372. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  373. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  374. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  375. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  376. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  377. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  378. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  379. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  380. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  381. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  382. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  383. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  384. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  385. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  386. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  387. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  388. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  389. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  390. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  391. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  392. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  393. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  394. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  395. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  396. /**
  397. * @author mikael emtinger / http://gomo.se/
  398. * @author alteredq / http://alteredqualia.com/
  399. * @author WestLangley / http://github.com/WestLangley
  400. * @author bhouston / http://exocortex.com
  401. */
  402. THREE.Quaternion = function( x, y, z, w ) {
  403. this.x = x || 0;
  404. this.y = y || 0;
  405. this.z = z || 0;
  406. this.w = ( w !== undefined ) ? w : 1;
  407. };
  408. THREE.Quaternion.prototype = {
  409. constructor: THREE.Quaternion,
  410. set: function ( x, y, z, w ) {
  411. this.x = x;
  412. this.y = y;
  413. this.z = z;
  414. this.w = w;
  415. return this;
  416. },
  417. copy: function ( q ) {
  418. this.x = q.x;
  419. this.y = q.y;
  420. this.z = q.z;
  421. this.w = q.w;
  422. return this;
  423. },
  424. setFromEuler: function ( v, order ) {
  425. // http://www.mathworks.com/matlabcentral/fileexchange/
  426. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  427. // content/SpinCalc.m
  428. var c1 = Math.cos( v.x / 2 );
  429. var c2 = Math.cos( v.y / 2 );
  430. var c3 = Math.cos( v.z / 2 );
  431. var s1 = Math.sin( v.x / 2 );
  432. var s2 = Math.sin( v.y / 2 );
  433. var s3 = Math.sin( v.z / 2 );
  434. if ( order === undefined || order === 'XYZ' ) {
  435. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  436. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  437. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  438. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  439. } else if ( order === 'YXZ' ) {
  440. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  441. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  442. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  443. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  444. } else if ( order === 'ZXY' ) {
  445. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  446. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  447. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  448. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  449. } else if ( order === 'ZYX' ) {
  450. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  451. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  452. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  453. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  454. } else if ( order === 'YZX' ) {
  455. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  456. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  457. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  458. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  459. } else if ( order === 'XZY' ) {
  460. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  461. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  462. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  463. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  464. }
  465. return this;
  466. },
  467. setFromAxisAngle: function ( axis, angle ) {
  468. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  469. // axis have to be normalized
  470. var halfAngle = angle / 2,
  471. s = Math.sin( halfAngle );
  472. this.x = axis.x * s;
  473. this.y = axis.y * s;
  474. this.z = axis.z * s;
  475. this.w = Math.cos( halfAngle );
  476. return this;
  477. },
  478. setFromRotationMatrix: function ( m ) {
  479. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  481. var te = m.elements,
  482. m11 = te[0], m12 = te[4], m13 = te[8],
  483. m21 = te[1], m22 = te[5], m23 = te[9],
  484. m31 = te[2], m32 = te[6], m33 = te[10],
  485. trace = m11 + m22 + m33,
  486. s;
  487. if ( trace > 0 ) {
  488. s = 0.5 / Math.sqrt( trace + 1.0 );
  489. this.w = 0.25 / s;
  490. this.x = ( m32 - m23 ) * s;
  491. this.y = ( m13 - m31 ) * s;
  492. this.z = ( m21 - m12 ) * s;
  493. } else if ( m11 > m22 && m11 > m33 ) {
  494. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  495. this.w = (m32 - m23 ) / s;
  496. this.x = 0.25 * s;
  497. this.y = (m12 + m21 ) / s;
  498. this.z = (m13 + m31 ) / s;
  499. } else if ( m22 > m33 ) {
  500. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  501. this.w = (m13 - m31 ) / s;
  502. this.x = (m12 + m21 ) / s;
  503. this.y = 0.25 * s;
  504. this.z = (m23 + m32 ) / s;
  505. } else {
  506. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  507. this.w = ( m21 - m12 ) / s;
  508. this.x = ( m13 + m31 ) / s;
  509. this.y = ( m23 + m32 ) / s;
  510. this.z = 0.25 * s;
  511. }
  512. return this;
  513. },
  514. inverse: function () {
  515. this.conjugate().normalize();
  516. return this;
  517. },
  518. conjugate: function () {
  519. this.x *= -1;
  520. this.y *= -1;
  521. this.z *= -1;
  522. return this;
  523. },
  524. lengthSq: function () {
  525. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  526. },
  527. length: function () {
  528. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  529. },
  530. normalize: function () {
  531. var l = this.length();
  532. if ( l === 0 ) {
  533. this.x = 0;
  534. this.y = 0;
  535. this.z = 0;
  536. this.w = 1;
  537. } else {
  538. l = 1 / l;
  539. this.x = this.x * l;
  540. this.y = this.y * l;
  541. this.z = this.z * l;
  542. this.w = this.w * l;
  543. }
  544. return this;
  545. },
  546. multiply: function ( q, p ) {
  547. if ( p !== undefined ) {
  548. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  549. return this.multiplyQuaternions( q, p );
  550. }
  551. return this.multiplyQuaternions( this, q );
  552. },
  553. multiplyQuaternions: function ( a, b ) {
  554. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  555. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  556. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  557. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  558. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  559. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  560. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  561. return this;
  562. },
  563. multiplyVector3: function ( vector ) {
  564. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  565. return vector.applyQuaternion( this );
  566. },
  567. slerp: function ( qb, t ) {
  568. var x = this.x, y = this.y, z = this.z, w = this.w;
  569. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  570. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  571. if ( cosHalfTheta < 0 ) {
  572. this.w = -qb.w;
  573. this.x = -qb.x;
  574. this.y = -qb.y;
  575. this.z = -qb.z;
  576. cosHalfTheta = -cosHalfTheta;
  577. } else {
  578. this.copy( qb );
  579. }
  580. if ( cosHalfTheta >= 1.0 ) {
  581. this.w = w;
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. }
  587. var halfTheta = Math.acos( cosHalfTheta );
  588. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  589. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  590. this.w = 0.5 * ( w + this.w );
  591. this.x = 0.5 * ( x + this.x );
  592. this.y = 0.5 * ( y + this.y );
  593. this.z = 0.5 * ( z + this.z );
  594. return this;
  595. }
  596. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  597. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  598. this.w = ( w * ratioA + this.w * ratioB );
  599. this.x = ( x * ratioA + this.x * ratioB );
  600. this.y = ( y * ratioA + this.y * ratioB );
  601. this.z = ( z * ratioA + this.z * ratioB );
  602. return this;
  603. },
  604. equals: function ( v ) {
  605. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  606. },
  607. clone: function () {
  608. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  609. }
  610. };
  611. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  612. return qm.copy( qa ).slerp( qb, t );
  613. }
  614. /**
  615. * @author mrdoob / http://mrdoob.com/
  616. * @author philogb / http://blog.thejit.org/
  617. * @author egraether / http://egraether.com/
  618. * @author zz85 / http://www.lab4games.net/zz85/blog
  619. */
  620. THREE.Vector2 = function ( x, y ) {
  621. this.x = x || 0;
  622. this.y = y || 0;
  623. };
  624. THREE.Vector2.prototype = {
  625. constructor: THREE.Vector2,
  626. set: function ( x, y ) {
  627. this.x = x;
  628. this.y = y;
  629. return this;
  630. },
  631. setX: function ( x ) {
  632. this.x = x;
  633. return this;
  634. },
  635. setY: function ( y ) {
  636. this.y = y;
  637. return this;
  638. },
  639. setComponent: function ( index, value ) {
  640. switch ( index ) {
  641. case 0: this.x = value; break;
  642. case 1: this.y = value; break;
  643. default: throw new Error( "index is out of range: " + index );
  644. }
  645. },
  646. getComponent: function ( index ) {
  647. switch ( index ) {
  648. case 0: return this.x;
  649. case 1: return this.y;
  650. default: throw new Error( "index is out of range: " + index );
  651. }
  652. },
  653. copy: function ( v ) {
  654. this.x = v.x;
  655. this.y = v.y;
  656. return this;
  657. },
  658. add: function ( v, w ) {
  659. if ( w !== undefined ) {
  660. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  661. return this.addVectors( v, w );
  662. }
  663. this.x += v.x;
  664. this.y += v.y;
  665. return this;
  666. },
  667. addVectors: function ( a, b ) {
  668. this.x = a.x + b.x;
  669. this.y = a.y + b.y;
  670. return this;
  671. },
  672. addScalar: function ( s ) {
  673. this.x += s;
  674. this.y += s;
  675. return this;
  676. },
  677. sub: function ( v, w ) {
  678. if ( w !== undefined ) {
  679. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  680. return this.subVectors( v, w );
  681. }
  682. this.x -= v.x;
  683. this.y -= v.y;
  684. return this;
  685. },
  686. subVectors: function ( a, b ) {
  687. this.x = a.x - b.x;
  688. this.y = a.y - b.y;
  689. return this;
  690. },
  691. multiplyScalar: function ( s ) {
  692. this.x *= s;
  693. this.y *= s;
  694. return this;
  695. },
  696. divideScalar: function ( s ) {
  697. if ( s !== 0 ) {
  698. this.x /= s;
  699. this.y /= s;
  700. } else {
  701. this.set( 0, 0 );
  702. }
  703. return this;
  704. },
  705. min: function ( v ) {
  706. if ( this.x > v.x ) {
  707. this.x = v.x;
  708. }
  709. if ( this.y > v.y ) {
  710. this.y = v.y;
  711. }
  712. return this;
  713. },
  714. max: function ( v ) {
  715. if ( this.x < v.x ) {
  716. this.x = v.x;
  717. }
  718. if ( this.y < v.y ) {
  719. this.y = v.y;
  720. }
  721. return this;
  722. },
  723. clamp: function ( min, max ) {
  724. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  725. if ( this.x < min.x ) {
  726. this.x = min.x;
  727. } else if ( this.x > max.x ) {
  728. this.x = max.x;
  729. }
  730. if ( this.y < min.y ) {
  731. this.y = min.y;
  732. } else if ( this.y > max.y ) {
  733. this.y = max.y;
  734. }
  735. return this;
  736. },
  737. negate: function() {
  738. return this.multiplyScalar( - 1 );
  739. },
  740. dot: function ( v ) {
  741. return this.x * v.x + this.y * v.y;
  742. },
  743. lengthSq: function () {
  744. return this.x * this.x + this.y * this.y;
  745. },
  746. length: function () {
  747. return Math.sqrt( this.x * this.x + this.y * this.y );
  748. },
  749. normalize: function () {
  750. return this.divideScalar( this.length() );
  751. },
  752. distanceTo: function ( v ) {
  753. return Math.sqrt( this.distanceToSquared( v ) );
  754. },
  755. distanceToSquared: function ( v ) {
  756. var dx = this.x - v.x, dy = this.y - v.y;
  757. return dx * dx + dy * dy;
  758. },
  759. setLength: function ( l ) {
  760. var oldLength = this.length();
  761. if ( oldLength !== 0 && l !== oldLength ) {
  762. this.multiplyScalar( l / oldLength );
  763. }
  764. return this;
  765. },
  766. lerp: function ( v, alpha ) {
  767. this.x += ( v.x - this.x ) * alpha;
  768. this.y += ( v.y - this.y ) * alpha;
  769. return this;
  770. },
  771. equals: function( v ) {
  772. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  773. },
  774. fromArray: function ( array ) {
  775. this.x = array[ 0 ];
  776. this.y = array[ 1 ];
  777. return this;
  778. },
  779. toArray: function () {
  780. return [ this.x, this.y ];
  781. },
  782. clone: function () {
  783. return new THREE.Vector2( this.x, this.y );
  784. }
  785. };
  786. /**
  787. * @author mrdoob / http://mrdoob.com/
  788. * @author *kile / http://kile.stravaganza.org/
  789. * @author philogb / http://blog.thejit.org/
  790. * @author mikael emtinger / http://gomo.se/
  791. * @author egraether / http://egraether.com/
  792. * @author WestLangley / http://github.com/WestLangley
  793. */
  794. THREE.Vector3 = function ( x, y, z ) {
  795. this.x = x || 0;
  796. this.y = y || 0;
  797. this.z = z || 0;
  798. };
  799. THREE.Vector3.prototype = {
  800. constructor: THREE.Vector3,
  801. set: function ( x, y, z ) {
  802. this.x = x;
  803. this.y = y;
  804. this.z = z;
  805. return this;
  806. },
  807. setX: function ( x ) {
  808. this.x = x;
  809. return this;
  810. },
  811. setY: function ( y ) {
  812. this.y = y;
  813. return this;
  814. },
  815. setZ: function ( z ) {
  816. this.z = z;
  817. return this;
  818. },
  819. setComponent: function ( index, value ) {
  820. switch ( index ) {
  821. case 0: this.x = value; break;
  822. case 1: this.y = value; break;
  823. case 2: this.z = value; break;
  824. default: throw new Error( "index is out of range: " + index );
  825. }
  826. },
  827. getComponent: function ( index ) {
  828. switch ( index ) {
  829. case 0: return this.x;
  830. case 1: return this.y;
  831. case 2: return this.z;
  832. default: throw new Error( "index is out of range: " + index );
  833. }
  834. },
  835. copy: function ( v ) {
  836. this.x = v.x;
  837. this.y = v.y;
  838. this.z = v.z;
  839. return this;
  840. },
  841. add: function ( v, w ) {
  842. if ( w !== undefined ) {
  843. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  844. return this.addVectors( v, w );
  845. }
  846. this.x += v.x;
  847. this.y += v.y;
  848. this.z += v.z;
  849. return this;
  850. },
  851. addScalar: function ( s ) {
  852. this.x += s;
  853. this.y += s;
  854. this.z += s;
  855. return this;
  856. },
  857. addVectors: function ( a, b ) {
  858. this.x = a.x + b.x;
  859. this.y = a.y + b.y;
  860. this.z = a.z + b.z;
  861. return this;
  862. },
  863. sub: function ( v, w ) {
  864. if ( w !== undefined ) {
  865. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  866. return this.subVectors( v, w );
  867. }
  868. this.x -= v.x;
  869. this.y -= v.y;
  870. this.z -= v.z;
  871. return this;
  872. },
  873. subVectors: 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. multiply: function ( v, w ) {
  880. if ( w !== undefined ) {
  881. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  882. return this.multiplyVectors( v, w );
  883. }
  884. this.x *= v.x;
  885. this.y *= v.y;
  886. this.z *= v.z;
  887. return this;
  888. },
  889. multiplyScalar: function ( s ) {
  890. this.x *= s;
  891. this.y *= s;
  892. this.z *= s;
  893. return this;
  894. },
  895. multiplyVectors: function ( a, b ) {
  896. this.x = a.x * b.x;
  897. this.y = a.y * b.y;
  898. this.z = a.z * b.z;
  899. return this;
  900. },
  901. applyMatrix3: function ( m ) {
  902. var x = this.x;
  903. var y = this.y;
  904. var z = this.z;
  905. var e = m.elements;
  906. this.x = e[0] * x + e[3] * y + e[6] * z;
  907. this.y = e[1] * x + e[4] * y + e[7] * z;
  908. this.z = e[2] * x + e[5] * y + e[8] * z;
  909. return this;
  910. },
  911. applyMatrix4: function ( m ) {
  912. // input: THREE.Matrix4 affine matrix
  913. var x = this.x, y = this.y, z = this.z;
  914. var e = m.elements;
  915. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  916. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  917. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  918. return this;
  919. },
  920. applyProjection: function ( m ) {
  921. // input: THREE.Matrix4 projection matrix
  922. var x = this.x, y = this.y, z = this.z;
  923. var e = m.elements;
  924. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  925. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  926. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  927. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  928. return this;
  929. },
  930. applyQuaternion: function ( q ) {
  931. var x = this.x;
  932. var y = this.y;
  933. var z = this.z;
  934. var qx = q.x;
  935. var qy = q.y;
  936. var qz = q.z;
  937. var qw = q.w;
  938. // calculate quat * vector
  939. var ix = qw * x + qy * z - qz * y;
  940. var iy = qw * y + qz * x - qx * z;
  941. var iz = qw * z + qx * y - qy * x;
  942. var iw = -qx * x - qy * y - qz * z;
  943. // calculate result * inverse quat
  944. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  945. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  946. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  947. return this;
  948. },
  949. transformDirection: function ( m ) {
  950. // input: THREE.Matrix4 affine matrix
  951. // vector interpreted as a direction
  952. var x = this.x, y = this.y, z = this.z;
  953. var e = m.elements;
  954. this.x = e[0] * x + e[4] * y + e[8] * z;
  955. this.y = e[1] * x + e[5] * y + e[9] * z;
  956. this.z = e[2] * x + e[6] * y + e[10] * z;
  957. this.normalize();
  958. return this;
  959. },
  960. divide: function ( v ) {
  961. this.x /= v.x;
  962. this.y /= v.y;
  963. this.z /= v.z;
  964. return this;
  965. },
  966. divideScalar: function ( s ) {
  967. if ( s !== 0 ) {
  968. this.x /= s;
  969. this.y /= s;
  970. this.z /= s;
  971. } else {
  972. this.x = 0;
  973. this.y = 0;
  974. this.z = 0;
  975. }
  976. return this;
  977. },
  978. min: function ( v ) {
  979. if ( this.x > v.x ) {
  980. this.x = v.x;
  981. }
  982. if ( this.y > v.y ) {
  983. this.y = v.y;
  984. }
  985. if ( this.z > v.z ) {
  986. this.z = v.z;
  987. }
  988. return this;
  989. },
  990. max: function ( v ) {
  991. if ( this.x < v.x ) {
  992. this.x = v.x;
  993. }
  994. if ( this.y < v.y ) {
  995. this.y = v.y;
  996. }
  997. if ( this.z < v.z ) {
  998. this.z = v.z;
  999. }
  1000. return this;
  1001. },
  1002. clamp: function ( min, max ) {
  1003. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1004. if ( this.x < min.x ) {
  1005. this.x = min.x;
  1006. } else if ( this.x > max.x ) {
  1007. this.x = max.x;
  1008. }
  1009. if ( this.y < min.y ) {
  1010. this.y = min.y;
  1011. } else if ( this.y > max.y ) {
  1012. this.y = max.y;
  1013. }
  1014. if ( this.z < min.z ) {
  1015. this.z = min.z;
  1016. } else if ( this.z > max.z ) {
  1017. this.z = max.z;
  1018. }
  1019. return this;
  1020. },
  1021. negate: function () {
  1022. return this.multiplyScalar( - 1 );
  1023. },
  1024. dot: function ( v ) {
  1025. return this.x * v.x + this.y * v.y + this.z * v.z;
  1026. },
  1027. lengthSq: function () {
  1028. return this.x * this.x + this.y * this.y + this.z * this.z;
  1029. },
  1030. length: function () {
  1031. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1032. },
  1033. lengthManhattan: function () {
  1034. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1035. },
  1036. normalize: function () {
  1037. return this.divideScalar( this.length() );
  1038. },
  1039. setLength: function ( l ) {
  1040. var oldLength = this.length();
  1041. if ( oldLength !== 0 && l !== oldLength ) {
  1042. this.multiplyScalar( l / oldLength );
  1043. }
  1044. return this;
  1045. },
  1046. lerp: function ( v, alpha ) {
  1047. this.x += ( v.x - this.x ) * alpha;
  1048. this.y += ( v.y - this.y ) * alpha;
  1049. this.z += ( v.z - this.z ) * alpha;
  1050. return this;
  1051. },
  1052. cross: function ( v, w ) {
  1053. if ( w !== undefined ) {
  1054. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1055. return this.crossVectors( v, w );
  1056. }
  1057. var x = this.x, y = this.y, z = this.z;
  1058. this.x = y * v.z - z * v.y;
  1059. this.y = z * v.x - x * v.z;
  1060. this.z = x * v.y - y * v.x;
  1061. return this;
  1062. },
  1063. crossVectors: function ( a, b ) {
  1064. this.x = a.y * b.z - a.z * b.y;
  1065. this.y = a.z * b.x - a.x * b.z;
  1066. this.z = a.x * b.y - a.y * b.x;
  1067. return this;
  1068. },
  1069. angleTo: function ( v ) {
  1070. var theta = this.dot( v ) / ( this.length() * v.length() );
  1071. // clamp, to handle numerical problems
  1072. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1073. },
  1074. distanceTo: function ( v ) {
  1075. return Math.sqrt( this.distanceToSquared( v ) );
  1076. },
  1077. distanceToSquared: function ( v ) {
  1078. var dx = this.x - v.x;
  1079. var dy = this.y - v.y;
  1080. var dz = this.z - v.z;
  1081. return dx * dx + dy * dy + dz * dz;
  1082. },
  1083. setEulerFromRotationMatrix: function ( m, order ) {
  1084. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1085. // clamp, to handle numerical problems
  1086. function clamp( x ) {
  1087. return Math.min( Math.max( x, -1 ), 1 );
  1088. }
  1089. var te = m.elements;
  1090. var m11 = te[0], m12 = te[4], m13 = te[8];
  1091. var m21 = te[1], m22 = te[5], m23 = te[9];
  1092. var m31 = te[2], m32 = te[6], m33 = te[10];
  1093. if ( order === undefined || order === 'XYZ' ) {
  1094. this.y = Math.asin( clamp( m13 ) );
  1095. if ( Math.abs( m13 ) < 0.99999 ) {
  1096. this.x = Math.atan2( - m23, m33 );
  1097. this.z = Math.atan2( - m12, m11 );
  1098. } else {
  1099. this.x = Math.atan2( m32, m22 );
  1100. this.z = 0;
  1101. }
  1102. } else if ( order === 'YXZ' ) {
  1103. this.x = Math.asin( - clamp( m23 ) );
  1104. if ( Math.abs( m23 ) < 0.99999 ) {
  1105. this.y = Math.atan2( m13, m33 );
  1106. this.z = Math.atan2( m21, m22 );
  1107. } else {
  1108. this.y = Math.atan2( - m31, m11 );
  1109. this.z = 0;
  1110. }
  1111. } else if ( order === 'ZXY' ) {
  1112. this.x = Math.asin( clamp( m32 ) );
  1113. if ( Math.abs( m32 ) < 0.99999 ) {
  1114. this.y = Math.atan2( - m31, m33 );
  1115. this.z = Math.atan2( - m12, m22 );
  1116. } else {
  1117. this.y = 0;
  1118. this.z = Math.atan2( m21, m11 );
  1119. }
  1120. } else if ( order === 'ZYX' ) {
  1121. this.y = Math.asin( - clamp( m31 ) );
  1122. if ( Math.abs( m31 ) < 0.99999 ) {
  1123. this.x = Math.atan2( m32, m33 );
  1124. this.z = Math.atan2( m21, m11 );
  1125. } else {
  1126. this.x = 0;
  1127. this.z = Math.atan2( - m12, m22 );
  1128. }
  1129. } else if ( order === 'YZX' ) {
  1130. this.z = Math.asin( clamp( m21 ) );
  1131. if ( Math.abs( m21 ) < 0.99999 ) {
  1132. this.x = Math.atan2( - m23, m22 );
  1133. this.y = Math.atan2( - m31, m11 );
  1134. } else {
  1135. this.x = 0;
  1136. this.y = Math.atan2( m13, m33 );
  1137. }
  1138. } else if ( order === 'XZY' ) {
  1139. this.z = Math.asin( - clamp( m12 ) );
  1140. if ( Math.abs( m12 ) < 0.99999 ) {
  1141. this.x = Math.atan2( m32, m22 );
  1142. this.y = Math.atan2( m13, m11 );
  1143. } else {
  1144. this.x = Math.atan2( - m23, m33 );
  1145. this.y = 0;
  1146. }
  1147. }
  1148. return this;
  1149. },
  1150. setEulerFromQuaternion: function ( q, order ) {
  1151. // q is assumed to be normalized
  1152. // clamp, to handle numerical problems
  1153. function clamp( x ) {
  1154. return Math.min( Math.max( x, -1 ), 1 );
  1155. }
  1156. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1157. var sqx = q.x * q.x;
  1158. var sqy = q.y * q.y;
  1159. var sqz = q.z * q.z;
  1160. var sqw = q.w * q.w;
  1161. if ( order === undefined || order === 'XYZ' ) {
  1162. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1163. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1164. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1165. } else if ( order === 'YXZ' ) {
  1166. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1167. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1168. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1169. } else if ( order === 'ZXY' ) {
  1170. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1171. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1172. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1173. } else if ( order === 'ZYX' ) {
  1174. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1175. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1176. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1177. } else if ( order === 'YZX' ) {
  1178. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1179. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1180. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1181. } else if ( order === 'XZY' ) {
  1182. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1183. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1184. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1185. }
  1186. return this;
  1187. },
  1188. getPositionFromMatrix: function ( m ) {
  1189. this.x = m.elements[12];
  1190. this.y = m.elements[13];
  1191. this.z = m.elements[14];
  1192. return this;
  1193. },
  1194. getScaleFromMatrix: function ( m ) {
  1195. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1196. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1197. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1198. this.x = sx;
  1199. this.y = sy;
  1200. this.z = sz;
  1201. return this;
  1202. },
  1203. getColumnFromMatrix: function ( index, matrix ) {
  1204. var offset = index * 4;
  1205. var me = matrix.elements;
  1206. this.x = me[ offset ];
  1207. this.y = me[ offset + 1 ];
  1208. this.z = me[ offset + 2 ];
  1209. return this;
  1210. },
  1211. equals: function ( v ) {
  1212. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1213. },
  1214. fromArray: function ( array ) {
  1215. this.x = array[ 0 ];
  1216. this.y = array[ 1 ];
  1217. this.z = array[ 2 ];
  1218. return this;
  1219. },
  1220. toArray: function () {
  1221. return [ this.x, this.y, this.z ];
  1222. },
  1223. clone: function () {
  1224. return new THREE.Vector3( this.x, this.y, this.z );
  1225. }
  1226. };
  1227. THREE.extend( THREE.Vector3.prototype, {
  1228. applyEuler: function () {
  1229. var q1 = new THREE.Quaternion();
  1230. return function ( v, eulerOrder ) {
  1231. var quaternion = q1.setFromEuler( v, eulerOrder );
  1232. this.applyQuaternion( quaternion );
  1233. return this;
  1234. };
  1235. }(),
  1236. applyAxisAngle: function () {
  1237. var q1 = new THREE.Quaternion();
  1238. return function ( axis, angle ) {
  1239. var quaternion = q1.setFromAxisAngle( axis, angle );
  1240. this.applyQuaternion( quaternion );
  1241. return this;
  1242. };
  1243. }(),
  1244. projectOnVector: function () {
  1245. var v1 = new THREE.Vector3();
  1246. return function ( vector ) {
  1247. v1.copy( vector ).normalize();
  1248. var d = this.dot( v1 );
  1249. return this.copy( v1 ).multiplyScalar( d );
  1250. };
  1251. }(),
  1252. projectOnPlane: function () {
  1253. var v1 = new THREE.Vector3();
  1254. return function ( planeNormal ) {
  1255. v1.copy( this ).projectOnVector( planeNormal );
  1256. return this.sub( v1 );
  1257. }
  1258. }(),
  1259. reflect: function () {
  1260. var v1 = new THREE.Vector3();
  1261. return function ( vector ) {
  1262. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1263. return this.subVectors( v1, this );
  1264. }
  1265. }()
  1266. } );
  1267. /**
  1268. * @author supereggbert / http://www.paulbrunt.co.uk/
  1269. * @author philogb / http://blog.thejit.org/
  1270. * @author mikael emtinger / http://gomo.se/
  1271. * @author egraether / http://egraether.com/
  1272. * @author WestLangley / http://github.com/WestLangley
  1273. */
  1274. THREE.Vector4 = function ( x, y, z, w ) {
  1275. this.x = x || 0;
  1276. this.y = y || 0;
  1277. this.z = z || 0;
  1278. this.w = ( w !== undefined ) ? w : 1;
  1279. };
  1280. THREE.Vector4.prototype = {
  1281. constructor: THREE.Vector4,
  1282. set: function ( x, y, z, w ) {
  1283. this.x = x;
  1284. this.y = y;
  1285. this.z = z;
  1286. this.w = w;
  1287. return this;
  1288. },
  1289. setX: function ( x ) {
  1290. this.x = x;
  1291. return this;
  1292. },
  1293. setY: function ( y ) {
  1294. this.y = y;
  1295. return this;
  1296. },
  1297. setZ: function ( z ) {
  1298. this.z = z;
  1299. return this;
  1300. },
  1301. setW: function ( w ) {
  1302. this.w = w;
  1303. return this;
  1304. },
  1305. setComponent: function ( index, value ) {
  1306. switch ( index ) {
  1307. case 0: this.x = value; break;
  1308. case 1: this.y = value; break;
  1309. case 2: this.z = value; break;
  1310. case 3: this.w = value; break;
  1311. default: throw new Error( "index is out of range: " + index );
  1312. }
  1313. },
  1314. getComponent: function ( index ) {
  1315. switch ( index ) {
  1316. case 0: return this.x;
  1317. case 1: return this.y;
  1318. case 2: return this.z;
  1319. case 3: return this.w;
  1320. default: throw new Error( "index is out of range: " + index );
  1321. }
  1322. },
  1323. copy: function ( v ) {
  1324. this.x = v.x;
  1325. this.y = v.y;
  1326. this.z = v.z;
  1327. this.w = ( v.w !== undefined ) ? v.w : 1;
  1328. return this;
  1329. },
  1330. add: function ( v, w ) {
  1331. if ( w !== undefined ) {
  1332. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1333. return this.addVectors( v, w );
  1334. }
  1335. this.x += v.x;
  1336. this.y += v.y;
  1337. this.z += v.z;
  1338. this.w += v.w;
  1339. return this;
  1340. },
  1341. addScalar: function ( s ) {
  1342. this.x += s;
  1343. this.y += s;
  1344. this.z += s;
  1345. this.w += s;
  1346. return this;
  1347. },
  1348. addVectors: function ( a, b ) {
  1349. this.x = a.x + b.x;
  1350. this.y = a.y + b.y;
  1351. this.z = a.z + b.z;
  1352. this.w = a.w + b.w;
  1353. return this;
  1354. },
  1355. sub: function ( v, w ) {
  1356. if ( w !== undefined ) {
  1357. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1358. return this.subVectors( v, w );
  1359. }
  1360. this.x -= v.x;
  1361. this.y -= v.y;
  1362. this.z -= v.z;
  1363. this.w -= v.w;
  1364. return this;
  1365. },
  1366. subVectors: function ( a, b ) {
  1367. this.x = a.x - b.x;
  1368. this.y = a.y - b.y;
  1369. this.z = a.z - b.z;
  1370. this.w = a.w - b.w;
  1371. return this;
  1372. },
  1373. multiplyScalar: function ( s ) {
  1374. this.x *= s;
  1375. this.y *= s;
  1376. this.z *= s;
  1377. this.w *= s;
  1378. return this;
  1379. },
  1380. applyMatrix4: function ( m ) {
  1381. var x = this.x;
  1382. var y = this.y;
  1383. var z = this.z;
  1384. var w = this.w;
  1385. var e = m.elements;
  1386. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1387. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1388. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1389. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1390. return this;
  1391. },
  1392. divideScalar: function ( s ) {
  1393. if ( s !== 0 ) {
  1394. this.x /= s;
  1395. this.y /= s;
  1396. this.z /= s;
  1397. this.w /= s;
  1398. } else {
  1399. this.x = 0;
  1400. this.y = 0;
  1401. this.z = 0;
  1402. this.w = 1;
  1403. }
  1404. return this;
  1405. },
  1406. setAxisAngleFromQuaternion: function ( q ) {
  1407. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1408. // q is assumed to be normalized
  1409. this.w = 2 * Math.acos( q.w );
  1410. var s = Math.sqrt( 1 - q.w * q.w );
  1411. if ( s < 0.0001 ) {
  1412. this.x = 1;
  1413. this.y = 0;
  1414. this.z = 0;
  1415. } else {
  1416. this.x = q.x / s;
  1417. this.y = q.y / s;
  1418. this.z = q.z / s;
  1419. }
  1420. return this;
  1421. },
  1422. setAxisAngleFromRotationMatrix: function ( m ) {
  1423. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1424. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1425. var angle, x, y, z, // variables for result
  1426. epsilon = 0.01, // margin to allow for rounding errors
  1427. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1428. te = m.elements,
  1429. m11 = te[0], m12 = te[4], m13 = te[8],
  1430. m21 = te[1], m22 = te[5], m23 = te[9],
  1431. m31 = te[2], m32 = te[6], m33 = te[10];
  1432. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1433. && ( Math.abs( m13 - m31 ) < epsilon )
  1434. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1435. // singularity found
  1436. // first check for identity matrix which must have +1 for all terms
  1437. // in leading diagonal and zero in other terms
  1438. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1439. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1440. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1441. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1442. // this singularity is identity matrix so angle = 0
  1443. this.set( 1, 0, 0, 0 );
  1444. return this; // zero angle, arbitrary axis
  1445. }
  1446. // otherwise this singularity is angle = 180
  1447. angle = Math.PI;
  1448. var xx = ( m11 + 1 ) / 2;
  1449. var yy = ( m22 + 1 ) / 2;
  1450. var zz = ( m33 + 1 ) / 2;
  1451. var xy = ( m12 + m21 ) / 4;
  1452. var xz = ( m13 + m31 ) / 4;
  1453. var yz = ( m23 + m32 ) / 4;
  1454. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1455. if ( xx < epsilon ) {
  1456. x = 0;
  1457. y = 0.707106781;
  1458. z = 0.707106781;
  1459. } else {
  1460. x = Math.sqrt( xx );
  1461. y = xy / x;
  1462. z = xz / x;
  1463. }
  1464. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1465. if ( yy < epsilon ) {
  1466. x = 0.707106781;
  1467. y = 0;
  1468. z = 0.707106781;
  1469. } else {
  1470. y = Math.sqrt( yy );
  1471. x = xy / y;
  1472. z = yz / y;
  1473. }
  1474. } else { // m33 is the largest diagonal term so base result on this
  1475. if ( zz < epsilon ) {
  1476. x = 0.707106781;
  1477. y = 0.707106781;
  1478. z = 0;
  1479. } else {
  1480. z = Math.sqrt( zz );
  1481. x = xz / z;
  1482. y = yz / z;
  1483. }
  1484. }
  1485. this.set( x, y, z, angle );
  1486. return this; // return 180 deg rotation
  1487. }
  1488. // as we have reached here there are no singularities so we can handle normally
  1489. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1490. + ( m13 - m31 ) * ( m13 - m31 )
  1491. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1492. if ( Math.abs( s ) < 0.001 ) s = 1;
  1493. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1494. // caught by singularity test above, but I've left it in just in case
  1495. this.x = ( m32 - m23 ) / s;
  1496. this.y = ( m13 - m31 ) / s;
  1497. this.z = ( m21 - m12 ) / s;
  1498. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1499. return this;
  1500. },
  1501. min: function ( v ) {
  1502. if ( this.x > v.x ) {
  1503. this.x = v.x;
  1504. }
  1505. if ( this.y > v.y ) {
  1506. this.y = v.y;
  1507. }
  1508. if ( this.z > v.z ) {
  1509. this.z = v.z;
  1510. }
  1511. if ( this.w > v.w ) {
  1512. this.w = v.w;
  1513. }
  1514. return this;
  1515. },
  1516. max: function ( v ) {
  1517. if ( this.x < v.x ) {
  1518. this.x = v.x;
  1519. }
  1520. if ( this.y < v.y ) {
  1521. this.y = v.y;
  1522. }
  1523. if ( this.z < v.z ) {
  1524. this.z = v.z;
  1525. }
  1526. if ( this.w < v.w ) {
  1527. this.w = v.w;
  1528. }
  1529. return this;
  1530. },
  1531. clamp: function ( min, max ) {
  1532. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1533. if ( this.x < min.x ) {
  1534. this.x = min.x;
  1535. } else if ( this.x > max.x ) {
  1536. this.x = max.x;
  1537. }
  1538. if ( this.y < min.y ) {
  1539. this.y = min.y;
  1540. } else if ( this.y > max.y ) {
  1541. this.y = max.y;
  1542. }
  1543. if ( this.z < min.z ) {
  1544. this.z = min.z;
  1545. } else if ( this.z > max.z ) {
  1546. this.z = max.z;
  1547. }
  1548. if ( this.w < min.w ) {
  1549. this.w = min.w;
  1550. } else if ( this.w > max.w ) {
  1551. this.w = max.w;
  1552. }
  1553. return this;
  1554. },
  1555. negate: function() {
  1556. return this.multiplyScalar( -1 );
  1557. },
  1558. dot: function ( v ) {
  1559. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1560. },
  1561. lengthSq: function () {
  1562. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1563. },
  1564. length: function () {
  1565. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1566. },
  1567. lengthManhattan: function () {
  1568. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1569. },
  1570. normalize: function () {
  1571. return this.divideScalar( this.length() );
  1572. },
  1573. setLength: function ( l ) {
  1574. var oldLength = this.length();
  1575. if ( oldLength !== 0 && l !== oldLength ) {
  1576. this.multiplyScalar( l / oldLength );
  1577. }
  1578. return this;
  1579. },
  1580. lerp: function ( v, alpha ) {
  1581. this.x += ( v.x - this.x ) * alpha;
  1582. this.y += ( v.y - this.y ) * alpha;
  1583. this.z += ( v.z - this.z ) * alpha;
  1584. this.w += ( v.w - this.w ) * alpha;
  1585. return this;
  1586. },
  1587. equals: function ( v ) {
  1588. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1589. },
  1590. fromArray: function ( array ) {
  1591. this.x = array[ 0 ];
  1592. this.y = array[ 1 ];
  1593. this.z = array[ 2 ];
  1594. this.w = array[ 3 ];
  1595. return this;
  1596. },
  1597. toArray: function () {
  1598. return [ this.x, this.y, this.z, this.w ];
  1599. },
  1600. clone: function () {
  1601. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1602. }
  1603. };
  1604. /**
  1605. * @author bhouston / http://exocortex.com
  1606. */
  1607. THREE.Line3 = function ( start, end ) {
  1608. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1609. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1610. };
  1611. THREE.Line3.prototype = {
  1612. constructor: THREE.Line3,
  1613. set: function ( start, end ) {
  1614. this.start.copy( start );
  1615. this.end.copy( end );
  1616. return this;
  1617. },
  1618. copy: function ( line ) {
  1619. this.start.copy( line.start );
  1620. this.end.copy( line.end );
  1621. return this;
  1622. },
  1623. center: function ( optionalTarget ) {
  1624. var result = optionalTarget || new THREE.Vector3();
  1625. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1626. },
  1627. delta: function ( optionalTarget ) {
  1628. var result = optionalTarget || new THREE.Vector3();
  1629. return result.subVectors( this.end, this.start );
  1630. },
  1631. distanceSq: function () {
  1632. return this.start.distanceToSquared( this.end );
  1633. },
  1634. distance: function () {
  1635. return this.start.distanceTo( this.end );
  1636. },
  1637. at: function ( t, optionalTarget ) {
  1638. var result = optionalTarget || new THREE.Vector3();
  1639. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1640. },
  1641. closestPointToPointParameter: function() {
  1642. var startP = new THREE.Vector3();
  1643. var startEnd = new THREE.Vector3();
  1644. return function ( point, clampToLine ) {
  1645. startP.subVectors( point, this.start );
  1646. startEnd.subVectors( this.end, this.start );
  1647. var startEnd2 = startEnd.dot( startEnd );
  1648. var startEnd_startP = startEnd.dot( startP );
  1649. var t = startEnd_startP / startEnd2;
  1650. if ( clampToLine ) {
  1651. t = THREE.Math.clamp( t, 0, 1 );
  1652. }
  1653. return t;
  1654. };
  1655. }(),
  1656. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1657. var t = this.closestPointToPointParameter( point, clampToLine );
  1658. var result = optionalTarget || new THREE.Vector3();
  1659. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1660. },
  1661. applyMatrix4: function ( matrix ) {
  1662. this.start.applyMatrix4( matrix );
  1663. this.end.applyMatrix4( matrix );
  1664. return this;
  1665. },
  1666. equals: function ( line ) {
  1667. return line.start.equals( this.start ) && line.end.equals( this.end );
  1668. },
  1669. clone: function () {
  1670. return new THREE.Line3().copy( this );
  1671. }
  1672. };
  1673. /**
  1674. * @author bhouston / http://exocortex.com
  1675. */
  1676. THREE.Box2 = function ( min, max ) {
  1677. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1678. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1679. };
  1680. THREE.Box2.prototype = {
  1681. constructor: THREE.Box2,
  1682. set: function ( min, max ) {
  1683. this.min.copy( min );
  1684. this.max.copy( max );
  1685. return this;
  1686. },
  1687. setFromPoints: function ( points ) {
  1688. if ( points.length > 0 ) {
  1689. var point = points[ 0 ];
  1690. this.min.copy( point );
  1691. this.max.copy( point );
  1692. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1693. point = points[ i ];
  1694. if ( point.x < this.min.x ) {
  1695. this.min.x = point.x;
  1696. } else if ( point.x > this.max.x ) {
  1697. this.max.x = point.x;
  1698. }
  1699. if ( point.y < this.min.y ) {
  1700. this.min.y = point.y;
  1701. } else if ( point.y > this.max.y ) {
  1702. this.max.y = point.y;
  1703. }
  1704. }
  1705. } else {
  1706. this.makeEmpty();
  1707. }
  1708. return this;
  1709. },
  1710. setFromCenterAndSize: function () {
  1711. var v1 = new THREE.Vector2();
  1712. return function ( center, size ) {
  1713. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1714. this.min.copy( center ).sub( halfSize );
  1715. this.max.copy( center ).add( halfSize );
  1716. return this;
  1717. };
  1718. }(),
  1719. copy: function ( box ) {
  1720. this.min.copy( box.min );
  1721. this.max.copy( box.max );
  1722. return this;
  1723. },
  1724. makeEmpty: function () {
  1725. this.min.x = this.min.y = Infinity;
  1726. this.max.x = this.max.y = -Infinity;
  1727. return this;
  1728. },
  1729. empty: function () {
  1730. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1731. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1732. },
  1733. center: function ( optionalTarget ) {
  1734. var result = optionalTarget || new THREE.Vector2();
  1735. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1736. },
  1737. size: function ( optionalTarget ) {
  1738. var result = optionalTarget || new THREE.Vector2();
  1739. return result.subVectors( this.max, this.min );
  1740. },
  1741. expandByPoint: function ( point ) {
  1742. this.min.min( point );
  1743. this.max.max( point );
  1744. return this;
  1745. },
  1746. expandByVector: function ( vector ) {
  1747. this.min.sub( vector );
  1748. this.max.add( vector );
  1749. return this;
  1750. },
  1751. expandByScalar: function ( scalar ) {
  1752. this.min.addScalar( -scalar );
  1753. this.max.addScalar( scalar );
  1754. return this;
  1755. },
  1756. containsPoint: function ( point ) {
  1757. if ( point.x < this.min.x || point.x > this.max.x ||
  1758. point.y < this.min.y || point.y > this.max.y ) {
  1759. return false;
  1760. }
  1761. return true;
  1762. },
  1763. containsBox: function ( box ) {
  1764. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1765. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1766. return true;
  1767. }
  1768. return false;
  1769. },
  1770. getParameter: function ( point ) {
  1771. // This can potentially have a divide by zero if the box
  1772. // has a size dimension of 0.
  1773. return new THREE.Vector2(
  1774. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1775. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1776. );
  1777. },
  1778. isIntersectionBox: function ( box ) {
  1779. // using 6 splitting planes to rule out intersections.
  1780. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1781. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1782. return false;
  1783. }
  1784. return true;
  1785. },
  1786. clampPoint: function ( point, optionalTarget ) {
  1787. var result = optionalTarget || new THREE.Vector2();
  1788. return result.copy( point ).clamp( this.min, this.max );
  1789. },
  1790. distanceToPoint: function () {
  1791. var v1 = new THREE.Vector2();
  1792. return function ( point ) {
  1793. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1794. return clampedPoint.sub( point ).length();
  1795. };
  1796. }(),
  1797. intersect: function ( box ) {
  1798. this.min.max( box.min );
  1799. this.max.min( box.max );
  1800. return this;
  1801. },
  1802. union: function ( box ) {
  1803. this.min.min( box.min );
  1804. this.max.max( box.max );
  1805. return this;
  1806. },
  1807. translate: function ( offset ) {
  1808. this.min.add( offset );
  1809. this.max.add( offset );
  1810. return this;
  1811. },
  1812. equals: function ( box ) {
  1813. return box.min.equals( this.min ) && box.max.equals( this.max );
  1814. },
  1815. clone: function () {
  1816. return new THREE.Box2().copy( this );
  1817. }
  1818. };
  1819. /**
  1820. * @author bhouston / http://exocortex.com
  1821. */
  1822. THREE.Box3 = function ( min, max ) {
  1823. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1824. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1825. };
  1826. THREE.Box3.prototype = {
  1827. constructor: THREE.Box3,
  1828. set: function ( min, max ) {
  1829. this.min.copy( min );
  1830. this.max.copy( max );
  1831. return this;
  1832. },
  1833. setFromPoints: function ( points ) {
  1834. if ( points.length > 0 ) {
  1835. var point = points[ 0 ];
  1836. this.min.copy( point );
  1837. this.max.copy( point );
  1838. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1839. point = points[ i ];
  1840. if ( point.x < this.min.x ) {
  1841. this.min.x = point.x;
  1842. } else if ( point.x > this.max.x ) {
  1843. this.max.x = point.x;
  1844. }
  1845. if ( point.y < this.min.y ) {
  1846. this.min.y = point.y;
  1847. } else if ( point.y > this.max.y ) {
  1848. this.max.y = point.y;
  1849. }
  1850. if ( point.z < this.min.z ) {
  1851. this.min.z = point.z;
  1852. } else if ( point.z > this.max.z ) {
  1853. this.max.z = point.z;
  1854. }
  1855. }
  1856. } else {
  1857. this.makeEmpty();
  1858. }
  1859. return this;
  1860. },
  1861. setFromCenterAndSize: function() {
  1862. var v1 = new THREE.Vector3();
  1863. return function ( center, size ) {
  1864. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1865. this.min.copy( center ).sub( halfSize );
  1866. this.max.copy( center ).add( halfSize );
  1867. return this;
  1868. };
  1869. }(),
  1870. copy: function ( box ) {
  1871. this.min.copy( box.min );
  1872. this.max.copy( box.max );
  1873. return this;
  1874. },
  1875. makeEmpty: function () {
  1876. this.min.x = this.min.y = this.min.z = Infinity;
  1877. this.max.x = this.max.y = this.max.z = -Infinity;
  1878. return this;
  1879. },
  1880. empty: function () {
  1881. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1882. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1883. },
  1884. center: function ( optionalTarget ) {
  1885. var result = optionalTarget || new THREE.Vector3();
  1886. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1887. },
  1888. size: function ( optionalTarget ) {
  1889. var result = optionalTarget || new THREE.Vector3();
  1890. return result.subVectors( this.max, this.min );
  1891. },
  1892. expandByPoint: function ( point ) {
  1893. this.min.min( point );
  1894. this.max.max( point );
  1895. return this;
  1896. },
  1897. expandByVector: function ( vector ) {
  1898. this.min.sub( vector );
  1899. this.max.add( vector );
  1900. return this;
  1901. },
  1902. expandByScalar: function ( scalar ) {
  1903. this.min.addScalar( -scalar );
  1904. this.max.addScalar( scalar );
  1905. return this;
  1906. },
  1907. containsPoint: function ( point ) {
  1908. if ( point.x < this.min.x || point.x > this.max.x ||
  1909. point.y < this.min.y || point.y > this.max.y ||
  1910. point.z < this.min.z || point.z > this.max.z ) {
  1911. return false;
  1912. }
  1913. return true;
  1914. },
  1915. containsBox: function ( box ) {
  1916. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1917. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1918. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1919. return true;
  1920. }
  1921. return false;
  1922. },
  1923. getParameter: function ( point ) {
  1924. // This can potentially have a divide by zero if the box
  1925. // has a size dimension of 0.
  1926. return new THREE.Vector3(
  1927. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1928. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1929. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1930. );
  1931. },
  1932. isIntersectionBox: function ( box ) {
  1933. // using 6 splitting planes to rule out intersections.
  1934. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1935. box.max.y < this.min.y || box.min.y > this.max.y ||
  1936. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1937. return false;
  1938. }
  1939. return true;
  1940. },
  1941. clampPoint: function ( point, optionalTarget ) {
  1942. var result = optionalTarget || new THREE.Vector3();
  1943. return result.copy( point ).clamp( this.min, this.max );
  1944. },
  1945. distanceToPoint: function() {
  1946. var v1 = new THREE.Vector3();
  1947. return function ( point ) {
  1948. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1949. return clampedPoint.sub( point ).length();
  1950. };
  1951. }(),
  1952. getBoundingSphere: function() {
  1953. var v1 = new THREE.Vector3();
  1954. return function ( optionalTarget ) {
  1955. var result = optionalTarget || new THREE.Sphere();
  1956. result.center = this.center();
  1957. result.radius = this.size( v1 ).length() * 0.5;
  1958. return result;
  1959. };
  1960. }(),
  1961. intersect: function ( box ) {
  1962. this.min.max( box.min );
  1963. this.max.min( box.max );
  1964. return this;
  1965. },
  1966. union: function ( box ) {
  1967. this.min.min( box.min );
  1968. this.max.max( box.max );
  1969. return this;
  1970. },
  1971. applyMatrix4: function() {
  1972. var points = [
  1973. new THREE.Vector3(),
  1974. new THREE.Vector3(),
  1975. new THREE.Vector3(),
  1976. new THREE.Vector3(),
  1977. new THREE.Vector3(),
  1978. new THREE.Vector3(),
  1979. new THREE.Vector3(),
  1980. new THREE.Vector3()
  1981. ];
  1982. return function ( matrix ) {
  1983. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1984. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1985. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1986. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1987. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1988. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1989. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1990. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1991. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1992. this.makeEmpty();
  1993. this.setFromPoints( points );
  1994. return this;
  1995. };
  1996. }(),
  1997. translate: function ( offset ) {
  1998. this.min.add( offset );
  1999. this.max.add( offset );
  2000. return this;
  2001. },
  2002. equals: function ( box ) {
  2003. return box.min.equals( this.min ) && box.max.equals( this.max );
  2004. },
  2005. clone: function () {
  2006. return new THREE.Box3().copy( this );
  2007. }
  2008. };
  2009. /**
  2010. * @author alteredq / http://alteredqualia.com/
  2011. * @author WestLangley / http://github.com/WestLangley
  2012. * @author bhouston / http://exocortex.com
  2013. */
  2014. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2015. this.elements = new Float32Array(9);
  2016. this.set(
  2017. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2018. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2019. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2020. );
  2021. };
  2022. THREE.Matrix3.prototype = {
  2023. constructor: THREE.Matrix3,
  2024. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2025. var te = this.elements;
  2026. te[0] = n11; te[3] = n12; te[6] = n13;
  2027. te[1] = n21; te[4] = n22; te[7] = n23;
  2028. te[2] = n31; te[5] = n32; te[8] = n33;
  2029. return this;
  2030. },
  2031. identity: function () {
  2032. this.set(
  2033. 1, 0, 0,
  2034. 0, 1, 0,
  2035. 0, 0, 1
  2036. );
  2037. return this;
  2038. },
  2039. copy: function ( m ) {
  2040. var me = m.elements;
  2041. this.set(
  2042. me[0], me[3], me[6],
  2043. me[1], me[4], me[7],
  2044. me[2], me[5], me[8]
  2045. );
  2046. return this;
  2047. },
  2048. multiplyVector3: function ( vector ) {
  2049. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2050. return vector.applyMatrix3( this );
  2051. },
  2052. multiplyVector3Array: function() {
  2053. var v1 = new THREE.Vector3();
  2054. return function ( a ) {
  2055. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2056. v1.x = a[ i ];
  2057. v1.y = a[ i + 1 ];
  2058. v1.z = a[ i + 2 ];
  2059. v1.applyMatrix3(this);
  2060. a[ i ] = v1.x;
  2061. a[ i + 1 ] = v1.y;
  2062. a[ i + 2 ] = v1.z;
  2063. }
  2064. return a;
  2065. };
  2066. }(),
  2067. multiplyScalar: function ( s ) {
  2068. var te = this.elements;
  2069. te[0] *= s; te[3] *= s; te[6] *= s;
  2070. te[1] *= s; te[4] *= s; te[7] *= s;
  2071. te[2] *= s; te[5] *= s; te[8] *= s;
  2072. return this;
  2073. },
  2074. determinant: function () {
  2075. var te = this.elements;
  2076. var a = te[0], b = te[1], c = te[2],
  2077. d = te[3], e = te[4], f = te[5],
  2078. g = te[6], h = te[7], i = te[8];
  2079. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2080. },
  2081. getInverse: function ( matrix, throwOnInvertible ) {
  2082. // input: THREE.Matrix4
  2083. // ( based on http://code.google.com/p/webgl-mjs/ )
  2084. var me = matrix.elements;
  2085. var te = this.elements;
  2086. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2087. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2088. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2089. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2090. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2091. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2092. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2093. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2094. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2095. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2096. // no inverse
  2097. if ( det === 0 ) {
  2098. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2099. if ( throwOnInvertible || false ) {
  2100. throw new Error( msg );
  2101. } else {
  2102. console.warn( msg );
  2103. }
  2104. this.identity();
  2105. return this;
  2106. }
  2107. this.multiplyScalar( 1.0 / det );
  2108. return this;
  2109. },
  2110. transpose: function () {
  2111. var tmp, m = this.elements;
  2112. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2113. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2114. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2115. return this;
  2116. },
  2117. getNormalMatrix: function ( m ) {
  2118. // input: THREE.Matrix4
  2119. this.getInverse( m ).transpose();
  2120. return this;
  2121. },
  2122. transposeIntoArray: function ( r ) {
  2123. var m = this.elements;
  2124. r[ 0 ] = m[ 0 ];
  2125. r[ 1 ] = m[ 3 ];
  2126. r[ 2 ] = m[ 6 ];
  2127. r[ 3 ] = m[ 1 ];
  2128. r[ 4 ] = m[ 4 ];
  2129. r[ 5 ] = m[ 7 ];
  2130. r[ 6 ] = m[ 2 ];
  2131. r[ 7 ] = m[ 5 ];
  2132. r[ 8 ] = m[ 8 ];
  2133. return this;
  2134. },
  2135. clone: function () {
  2136. var te = this.elements;
  2137. return new THREE.Matrix3(
  2138. te[0], te[3], te[6],
  2139. te[1], te[4], te[7],
  2140. te[2], te[5], te[8]
  2141. );
  2142. }
  2143. };
  2144. /**
  2145. * @author mrdoob / http://mrdoob.com/
  2146. * @author supereggbert / http://www.paulbrunt.co.uk/
  2147. * @author philogb / http://blog.thejit.org/
  2148. * @author jordi_ros / http://plattsoft.com
  2149. * @author D1plo1d / http://github.com/D1plo1d
  2150. * @author alteredq / http://alteredqualia.com/
  2151. * @author mikael emtinger / http://gomo.se/
  2152. * @author timknip / http://www.floorplanner.com/
  2153. * @author bhouston / http://exocortex.com
  2154. * @author WestLangley / http://github.com/WestLangley
  2155. */
  2156. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2157. var te = this.elements = new Float32Array( 16 );
  2158. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2159. // we should not support semi specification of Matrix4, it is just weird.
  2160. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2161. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2162. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2163. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2164. };
  2165. THREE.Matrix4.prototype = {
  2166. constructor: THREE.Matrix4,
  2167. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2168. var te = this.elements;
  2169. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2170. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2171. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2172. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2173. return this;
  2174. },
  2175. identity: function () {
  2176. this.set(
  2177. 1, 0, 0, 0,
  2178. 0, 1, 0, 0,
  2179. 0, 0, 1, 0,
  2180. 0, 0, 0, 1
  2181. );
  2182. return this;
  2183. },
  2184. copy: function ( m ) {
  2185. var me = m.elements;
  2186. this.set(
  2187. me[0], me[4], me[8], me[12],
  2188. me[1], me[5], me[9], me[13],
  2189. me[2], me[6], me[10], me[14],
  2190. me[3], me[7], me[11], me[15]
  2191. );
  2192. return this;
  2193. },
  2194. copyPosition: function ( m ) {
  2195. var te = this.elements;
  2196. var me = m.elements;
  2197. te[12] = me[12];
  2198. te[13] = me[13];
  2199. te[14] = me[14];
  2200. return this;
  2201. },
  2202. copyRotation: function () {
  2203. var v1 = new THREE.Vector3();
  2204. return function ( m ) {
  2205. var te = this.elements;
  2206. var me = m.elements;
  2207. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2208. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2209. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2210. te[0] = me[0] * scaleX;
  2211. te[1] = me[1] * scaleX;
  2212. te[2] = me[2] * scaleX;
  2213. te[4] = me[4] * scaleY;
  2214. te[5] = me[5] * scaleY;
  2215. te[6] = me[6] * scaleY;
  2216. te[8] = me[8] * scaleZ;
  2217. te[9] = me[9] * scaleZ;
  2218. te[10] = me[10] * scaleZ;
  2219. return this;
  2220. };
  2221. }(),
  2222. setRotationFromEuler: function ( v, order ) {
  2223. var te = this.elements;
  2224. var x = v.x, y = v.y, z = v.z;
  2225. var a = Math.cos( x ), b = Math.sin( x );
  2226. var c = Math.cos( y ), d = Math.sin( y );
  2227. var e = Math.cos( z ), f = Math.sin( z );
  2228. if ( order === undefined || order === 'XYZ' ) {
  2229. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2230. te[0] = c * e;
  2231. te[4] = - c * f;
  2232. te[8] = d;
  2233. te[1] = af + be * d;
  2234. te[5] = ae - bf * d;
  2235. te[9] = - b * c;
  2236. te[2] = bf - ae * d;
  2237. te[6] = be + af * d;
  2238. te[10] = a * c;
  2239. } else if ( order === 'YXZ' ) {
  2240. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2241. te[0] = ce + df * b;
  2242. te[4] = de * b - cf;
  2243. te[8] = a * d;
  2244. te[1] = a * f;
  2245. te[5] = a * e;
  2246. te[9] = - b;
  2247. te[2] = cf * b - de;
  2248. te[6] = df + ce * b;
  2249. te[10] = a * c;
  2250. } else if ( order === 'ZXY' ) {
  2251. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2252. te[0] = ce - df * b;
  2253. te[4] = - a * f;
  2254. te[8] = de + cf * b;
  2255. te[1] = cf + de * b;
  2256. te[5] = a * e;
  2257. te[9] = df - ce * b;
  2258. te[2] = - a * d;
  2259. te[6] = b;
  2260. te[10] = a * c;
  2261. } else if ( order === 'ZYX' ) {
  2262. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2263. te[0] = c * e;
  2264. te[4] = be * d - af;
  2265. te[8] = ae * d + bf;
  2266. te[1] = c * f;
  2267. te[5] = bf * d + ae;
  2268. te[9] = af * d - be;
  2269. te[2] = - d;
  2270. te[6] = b * c;
  2271. te[10] = a * c;
  2272. } else if ( order === 'YZX' ) {
  2273. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2274. te[0] = c * e;
  2275. te[4] = bd - ac * f;
  2276. te[8] = bc * f + ad;
  2277. te[1] = f;
  2278. te[5] = a * e;
  2279. te[9] = - b * e;
  2280. te[2] = - d * e;
  2281. te[6] = ad * f + bc;
  2282. te[10] = ac - bd * f;
  2283. } else if ( order === 'XZY' ) {
  2284. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2285. te[0] = c * e;
  2286. te[4] = - f;
  2287. te[8] = d * e;
  2288. te[1] = ac * f + bd;
  2289. te[5] = a * e;
  2290. te[9] = ad * f - bc;
  2291. te[2] = bc * f - ad;
  2292. te[6] = b * e;
  2293. te[10] = bd * f + ac;
  2294. }
  2295. return this;
  2296. },
  2297. setRotationFromQuaternion: function ( q ) {
  2298. var te = this.elements;
  2299. var x = q.x, y = q.y, z = q.z, w = q.w;
  2300. var x2 = x + x, y2 = y + y, z2 = z + z;
  2301. var xx = x * x2, xy = x * y2, xz = x * z2;
  2302. var yy = y * y2, yz = y * z2, zz = z * z2;
  2303. var wx = w * x2, wy = w * y2, wz = w * z2;
  2304. te[0] = 1 - ( yy + zz );
  2305. te[4] = xy - wz;
  2306. te[8] = xz + wy;
  2307. te[1] = xy + wz;
  2308. te[5] = 1 - ( xx + zz );
  2309. te[9] = yz - wx;
  2310. te[2] = xz - wy;
  2311. te[6] = yz + wx;
  2312. te[10] = 1 - ( xx + yy );
  2313. return this;
  2314. },
  2315. lookAt: function() {
  2316. var x = new THREE.Vector3();
  2317. var y = new THREE.Vector3();
  2318. var z = new THREE.Vector3();
  2319. return function ( eye, target, up ) {
  2320. var te = this.elements;
  2321. z.subVectors( eye, target ).normalize();
  2322. if ( z.length() === 0 ) {
  2323. z.z = 1;
  2324. }
  2325. x.crossVectors( up, z ).normalize();
  2326. if ( x.length() === 0 ) {
  2327. z.x += 0.0001;
  2328. x.crossVectors( up, z ).normalize();
  2329. }
  2330. y.crossVectors( z, x );
  2331. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2332. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2333. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2334. return this;
  2335. };
  2336. }(),
  2337. multiply: function ( m, n ) {
  2338. if ( n !== undefined ) {
  2339. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2340. return this.multiplyMatrices( m, n );
  2341. }
  2342. return this.multiplyMatrices( this, m );
  2343. },
  2344. multiplyMatrices: function ( a, b ) {
  2345. var ae = a.elements;
  2346. var be = b.elements;
  2347. var te = this.elements;
  2348. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2349. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2350. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2351. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2352. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2353. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2354. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2355. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2356. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2357. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2358. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2359. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2360. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2361. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2362. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2363. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2364. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2365. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2366. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2367. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2368. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2369. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2370. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2371. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2372. return this;
  2373. },
  2374. multiplyToArray: function ( a, b, r ) {
  2375. var te = this.elements;
  2376. this.multiplyMatrices( a, b );
  2377. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2378. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2379. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2380. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2381. return this;
  2382. },
  2383. multiplyScalar: function ( s ) {
  2384. var te = this.elements;
  2385. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2386. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2387. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2388. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2389. return this;
  2390. },
  2391. multiplyVector3: function ( vector ) {
  2392. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2393. return vector.applyProjection( this );
  2394. },
  2395. multiplyVector4: function ( vector ) {
  2396. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2397. return vector.applyMatrix4( this );
  2398. },
  2399. multiplyVector3Array: function() {
  2400. var v1 = new THREE.Vector3();
  2401. return function ( a ) {
  2402. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2403. v1.x = a[ i ];
  2404. v1.y = a[ i + 1 ];
  2405. v1.z = a[ i + 2 ];
  2406. v1.applyProjection( this );
  2407. a[ i ] = v1.x;
  2408. a[ i + 1 ] = v1.y;
  2409. a[ i + 2 ] = v1.z;
  2410. }
  2411. return a;
  2412. };
  2413. }(),
  2414. rotateAxis: function ( v ) {
  2415. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2416. v.transformDirection( this );
  2417. },
  2418. crossVector: function ( vector ) {
  2419. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2420. return vector.applyMatrix4( this );
  2421. },
  2422. determinant: function () {
  2423. var te = this.elements;
  2424. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2425. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2426. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2427. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2428. //TODO: make this more efficient
  2429. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2430. return (
  2431. n41 * (
  2432. +n14 * n23 * n32
  2433. -n13 * n24 * n32
  2434. -n14 * n22 * n33
  2435. +n12 * n24 * n33
  2436. +n13 * n22 * n34
  2437. -n12 * n23 * n34
  2438. ) +
  2439. n42 * (
  2440. +n11 * n23 * n34
  2441. -n11 * n24 * n33
  2442. +n14 * n21 * n33
  2443. -n13 * n21 * n34
  2444. +n13 * n24 * n31
  2445. -n14 * n23 * n31
  2446. ) +
  2447. n43 * (
  2448. +n11 * n24 * n32
  2449. -n11 * n22 * n34
  2450. -n14 * n21 * n32
  2451. +n12 * n21 * n34
  2452. +n14 * n22 * n31
  2453. -n12 * n24 * n31
  2454. ) +
  2455. n44 * (
  2456. -n13 * n22 * n31
  2457. -n11 * n23 * n32
  2458. +n11 * n22 * n33
  2459. +n13 * n21 * n32
  2460. -n12 * n21 * n33
  2461. +n12 * n23 * n31
  2462. )
  2463. );
  2464. },
  2465. transpose: function () {
  2466. var te = this.elements;
  2467. var tmp;
  2468. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2469. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2470. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2471. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2472. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2473. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2474. return this;
  2475. },
  2476. flattenToArray: function ( flat ) {
  2477. var te = this.elements;
  2478. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2479. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2480. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2481. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2482. return flat;
  2483. },
  2484. flattenToArrayOffset: function( flat, offset ) {
  2485. var te = this.elements;
  2486. flat[ offset ] = te[0];
  2487. flat[ offset + 1 ] = te[1];
  2488. flat[ offset + 2 ] = te[2];
  2489. flat[ offset + 3 ] = te[3];
  2490. flat[ offset + 4 ] = te[4];
  2491. flat[ offset + 5 ] = te[5];
  2492. flat[ offset + 6 ] = te[6];
  2493. flat[ offset + 7 ] = te[7];
  2494. flat[ offset + 8 ] = te[8];
  2495. flat[ offset + 9 ] = te[9];
  2496. flat[ offset + 10 ] = te[10];
  2497. flat[ offset + 11 ] = te[11];
  2498. flat[ offset + 12 ] = te[12];
  2499. flat[ offset + 13 ] = te[13];
  2500. flat[ offset + 14 ] = te[14];
  2501. flat[ offset + 15 ] = te[15];
  2502. return flat;
  2503. },
  2504. getPosition: function() {
  2505. var v1 = new THREE.Vector3();
  2506. return function () {
  2507. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2508. var te = this.elements;
  2509. return v1.set( te[12], te[13], te[14] );
  2510. };
  2511. }(),
  2512. setPosition: function ( v ) {
  2513. var te = this.elements;
  2514. te[12] = v.x;
  2515. te[13] = v.y;
  2516. te[14] = v.z;
  2517. return this;
  2518. },
  2519. getInverse: function ( m, throwOnInvertible ) {
  2520. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2521. var te = this.elements;
  2522. var me = m.elements;
  2523. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2524. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2525. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2526. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2527. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2528. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2529. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2530. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2531. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2532. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2533. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2534. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2535. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2536. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2537. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2538. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2539. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2540. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2541. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2542. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2543. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2544. if ( det == 0 ) {
  2545. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2546. if ( throwOnInvertible || false ) {
  2547. throw new Error( msg );
  2548. } else {
  2549. console.warn( msg );
  2550. }
  2551. this.identity();
  2552. return this;
  2553. }
  2554. this.multiplyScalar( 1 / det );
  2555. return this;
  2556. },
  2557. extractPosition: function ( m ) {
  2558. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2559. return this.copyPosition( m );
  2560. },
  2561. extractRotation: function ( m ) {
  2562. console.warn( 'DEPRECATED: Matrix4\'s .extractRotation() has been renamed to .copyRotation().' );
  2563. return this.copyRotation( m );
  2564. },
  2565. translate: function ( v ) {
  2566. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2567. },
  2568. rotateX: function ( angle ) {
  2569. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2570. },
  2571. rotateY: function ( angle ) {
  2572. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2573. },
  2574. rotateZ: function ( angle ) {
  2575. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2576. },
  2577. rotateByAxis: function ( axis, angle ) {
  2578. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2579. },
  2580. scale: function ( v ) {
  2581. var te = this.elements;
  2582. var x = v.x, y = v.y, z = v.z;
  2583. te[0] *= x; te[4] *= y; te[8] *= z;
  2584. te[1] *= x; te[5] *= y; te[9] *= z;
  2585. te[2] *= x; te[6] *= y; te[10] *= z;
  2586. te[3] *= x; te[7] *= y; te[11] *= z;
  2587. return this;
  2588. },
  2589. getMaxScaleOnAxis: function () {
  2590. var te = this.elements;
  2591. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2592. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2593. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2594. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2595. },
  2596. makeTranslation: function ( x, y, z ) {
  2597. this.set(
  2598. 1, 0, 0, x,
  2599. 0, 1, 0, y,
  2600. 0, 0, 1, z,
  2601. 0, 0, 0, 1
  2602. );
  2603. return this;
  2604. },
  2605. makeRotationX: function ( theta ) {
  2606. var c = Math.cos( theta ), s = Math.sin( theta );
  2607. this.set(
  2608. 1, 0, 0, 0,
  2609. 0, c, -s, 0,
  2610. 0, s, c, 0,
  2611. 0, 0, 0, 1
  2612. );
  2613. return this;
  2614. },
  2615. makeRotationY: function ( theta ) {
  2616. var c = Math.cos( theta ), s = Math.sin( theta );
  2617. this.set(
  2618. c, 0, s, 0,
  2619. 0, 1, 0, 0,
  2620. -s, 0, c, 0,
  2621. 0, 0, 0, 1
  2622. );
  2623. return this;
  2624. },
  2625. makeRotationZ: function ( theta ) {
  2626. var c = Math.cos( theta ), s = Math.sin( theta );
  2627. this.set(
  2628. c, -s, 0, 0,
  2629. s, c, 0, 0,
  2630. 0, 0, 1, 0,
  2631. 0, 0, 0, 1
  2632. );
  2633. return this;
  2634. },
  2635. makeRotationAxis: function ( axis, angle ) {
  2636. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2637. var c = Math.cos( angle );
  2638. var s = Math.sin( angle );
  2639. var t = 1 - c;
  2640. var x = axis.x, y = axis.y, z = axis.z;
  2641. var tx = t * x, ty = t * y;
  2642. this.set(
  2643. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2644. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2645. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2646. 0, 0, 0, 1
  2647. );
  2648. return this;
  2649. },
  2650. makeScale: function ( x, y, z ) {
  2651. this.set(
  2652. x, 0, 0, 0,
  2653. 0, y, 0, 0,
  2654. 0, 0, z, 0,
  2655. 0, 0, 0, 1
  2656. );
  2657. return this;
  2658. },
  2659. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2660. var te = this.elements;
  2661. var x = 2 * near / ( right - left );
  2662. var y = 2 * near / ( top - bottom );
  2663. var a = ( right + left ) / ( right - left );
  2664. var b = ( top + bottom ) / ( top - bottom );
  2665. var c = - ( far + near ) / ( far - near );
  2666. var d = - 2 * far * near / ( far - near );
  2667. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2668. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2669. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2670. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2671. return this;
  2672. },
  2673. makePerspective: function ( fov, aspect, near, far ) {
  2674. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2675. var ymin = - ymax;
  2676. var xmin = ymin * aspect;
  2677. var xmax = ymax * aspect;
  2678. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2679. },
  2680. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2681. var te = this.elements;
  2682. var w = right - left;
  2683. var h = top - bottom;
  2684. var p = far - near;
  2685. var x = ( right + left ) / w;
  2686. var y = ( top + bottom ) / h;
  2687. var z = ( far + near ) / p;
  2688. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2689. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2690. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2691. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2692. return this;
  2693. },
  2694. clone: function () {
  2695. var te = this.elements;
  2696. return new THREE.Matrix4(
  2697. te[0], te[4], te[8], te[12],
  2698. te[1], te[5], te[9], te[13],
  2699. te[2], te[6], te[10], te[14],
  2700. te[3], te[7], te[11], te[15]
  2701. );
  2702. }
  2703. };
  2704. THREE.extend( THREE.Matrix4.prototype, {
  2705. compose: function() {
  2706. var mRotation = new THREE.Matrix4();
  2707. var mScale = new THREE.Matrix4();
  2708. return function ( position, quaternion, scale ) {
  2709. var te = this.elements;
  2710. mRotation.identity();
  2711. mRotation.setRotationFromQuaternion( quaternion );
  2712. mScale.makeScale( scale.x, scale.y, scale.z );
  2713. this.multiplyMatrices( mRotation, mScale );
  2714. te[12] = position.x;
  2715. te[13] = position.y;
  2716. te[14] = position.z;
  2717. return this;
  2718. };
  2719. }(),
  2720. decompose: function() {
  2721. var x = new THREE.Vector3();
  2722. var y = new THREE.Vector3();
  2723. var z = new THREE.Vector3();
  2724. var matrix = new THREE.Matrix4();
  2725. return function ( position, quaternion, scale ) {
  2726. var te = this.elements;
  2727. // grab the axis vectors
  2728. x.set( te[0], te[1], te[2] );
  2729. y.set( te[4], te[5], te[6] );
  2730. z.set( te[8], te[9], te[10] );
  2731. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2732. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2733. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2734. scale.x = x.length();
  2735. scale.y = y.length();
  2736. scale.z = z.length();
  2737. position.x = te[12];
  2738. position.y = te[13];
  2739. position.z = te[14];
  2740. // scale the rotation part
  2741. matrix.copy( this );
  2742. matrix.elements[0] /= scale.x;
  2743. matrix.elements[1] /= scale.x;
  2744. matrix.elements[2] /= scale.x;
  2745. matrix.elements[4] /= scale.y;
  2746. matrix.elements[5] /= scale.y;
  2747. matrix.elements[6] /= scale.y;
  2748. matrix.elements[8] /= scale.z;
  2749. matrix.elements[9] /= scale.z;
  2750. matrix.elements[10] /= scale.z;
  2751. quaternion.setFromRotationMatrix( matrix );
  2752. return [ position, quaternion, scale ];
  2753. };
  2754. }()
  2755. } );
  2756. /**
  2757. * @author bhouston / http://exocortex.com
  2758. */
  2759. THREE.Ray = function ( origin, direction ) {
  2760. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2761. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2762. };
  2763. THREE.Ray.prototype = {
  2764. constructor: THREE.Ray,
  2765. set: function ( origin, direction ) {
  2766. this.origin.copy( origin );
  2767. this.direction.copy( direction );
  2768. return this;
  2769. },
  2770. copy: function ( ray ) {
  2771. this.origin.copy( ray.origin );
  2772. this.direction.copy( ray.direction );
  2773. return this;
  2774. },
  2775. at: function( t, optionalTarget ) {
  2776. var result = optionalTarget || new THREE.Vector3();
  2777. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2778. },
  2779. recast: function() {
  2780. var v1 = new THREE.Vector3();
  2781. return function ( t ) {
  2782. this.origin.copy( this.at( t, v1 ) );
  2783. return this;
  2784. };
  2785. }(),
  2786. closestPointToPoint: function ( point, optionalTarget ) {
  2787. var result = optionalTarget || new THREE.Vector3();
  2788. result.subVectors( point, this.origin );
  2789. var directionDistance = result.dot( this.direction );
  2790. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2791. },
  2792. distanceToPoint: function() {
  2793. var v1 = new THREE.Vector3();
  2794. return function ( point ) {
  2795. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2796. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2797. return v1.distanceTo( point );
  2798. };
  2799. }(),
  2800. isIntersectionSphere: function( sphere ) {
  2801. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2802. },
  2803. isIntersectionPlane: function ( plane ) {
  2804. // check if the line and plane are non-perpendicular, if they
  2805. // eventually they will intersect.
  2806. var denominator = plane.normal.dot( this.direction );
  2807. if ( denominator != 0 ) {
  2808. return true;
  2809. }
  2810. // line is coplanar, return origin
  2811. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2812. return true;
  2813. }
  2814. return false;
  2815. },
  2816. distanceToPlane: function ( plane ) {
  2817. var denominator = plane.normal.dot( this.direction );
  2818. if ( denominator == 0 ) {
  2819. // line is coplanar, return origin
  2820. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2821. return 0;
  2822. }
  2823. // Unsure if this is the correct method to handle this case.
  2824. return undefined;
  2825. }
  2826. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2827. return t;
  2828. },
  2829. intersectPlane: function ( plane, optionalTarget ) {
  2830. var t = this.distanceToPlane( plane );
  2831. if ( t === undefined ) {
  2832. return undefined;
  2833. }
  2834. return this.at( t, optionalTarget );
  2835. },
  2836. applyMatrix4: function ( matrix4 ) {
  2837. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2838. this.origin.applyMatrix4( matrix4 );
  2839. this.direction.sub( this.origin );
  2840. return this;
  2841. },
  2842. equals: function ( ray ) {
  2843. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2844. },
  2845. clone: function () {
  2846. return new THREE.Ray().copy( this );
  2847. }
  2848. };
  2849. /**
  2850. * @author bhouston / http://exocortex.com
  2851. * @author mrdoob / http://mrdoob.com/
  2852. */
  2853. THREE.Sphere = function ( center, radius ) {
  2854. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2855. this.radius = ( radius !== undefined ) ? radius : 0;
  2856. };
  2857. THREE.Sphere.prototype = {
  2858. constructor: THREE.Sphere,
  2859. set: function ( center, radius ) {
  2860. this.center.copy( center );
  2861. this.radius = radius;
  2862. return this;
  2863. },
  2864. setFromCenterAndPoints: function ( center, points ) {
  2865. var maxRadiusSq = 0;
  2866. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2867. var radiusSq = center.distanceToSquared( points[ i ] );
  2868. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2869. }
  2870. this.center = center;
  2871. this.radius = Math.sqrt( maxRadiusSq );
  2872. return this;
  2873. },
  2874. copy: function ( sphere ) {
  2875. this.center.copy( sphere.center );
  2876. this.radius = sphere.radius;
  2877. return this;
  2878. },
  2879. empty: function () {
  2880. return ( this.radius <= 0 );
  2881. },
  2882. containsPoint: function ( point ) {
  2883. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2884. },
  2885. distanceToPoint: function ( point ) {
  2886. return ( point.distanceTo( this.center ) - this.radius );
  2887. },
  2888. intersectsSphere: function ( sphere ) {
  2889. var radiusSum = this.radius + sphere.radius;
  2890. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2891. },
  2892. clampPoint: function ( point, optionalTarget ) {
  2893. var deltaLengthSq = this.center.distanceToSquared( point );
  2894. var result = optionalTarget || new THREE.Vector3();
  2895. result.copy( point );
  2896. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2897. result.sub( this.center ).normalize();
  2898. result.multiplyScalar( this.radius ).add( this.center );
  2899. }
  2900. return result;
  2901. },
  2902. getBoundingBox: function ( optionalTarget ) {
  2903. var box = optionalTarget || new THREE.Box3();
  2904. box.set( this.center, this.center );
  2905. box.expandByScalar( this.radius );
  2906. return box;
  2907. },
  2908. applyMatrix4: function ( matrix ) {
  2909. this.center.applyMatrix4( matrix );
  2910. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2911. return this;
  2912. },
  2913. translate: function ( offset ) {
  2914. this.center.add( offset );
  2915. return this;
  2916. },
  2917. equals: function ( sphere ) {
  2918. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2919. },
  2920. clone: function () {
  2921. return new THREE.Sphere().copy( this );
  2922. }
  2923. };
  2924. /**
  2925. * @author mrdoob / http://mrdoob.com/
  2926. * @author alteredq / http://alteredqualia.com/
  2927. * @author bhouston / http://exocortex.com
  2928. */
  2929. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2930. this.planes = [
  2931. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2932. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2933. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2934. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2935. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2936. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2937. ];
  2938. };
  2939. THREE.Frustum.prototype = {
  2940. constructor: THREE.Frustum,
  2941. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2942. var planes = this.planes;
  2943. planes[0].copy( p0 );
  2944. planes[1].copy( p1 );
  2945. planes[2].copy( p2 );
  2946. planes[3].copy( p3 );
  2947. planes[4].copy( p4 );
  2948. planes[5].copy( p5 );
  2949. return this;
  2950. },
  2951. copy: function ( frustum ) {
  2952. var planes = this.planes;
  2953. for( var i = 0; i < 6; i ++ ) {
  2954. planes[i].copy( frustum.planes[i] );
  2955. }
  2956. return this;
  2957. },
  2958. setFromMatrix: function ( m ) {
  2959. var planes = this.planes;
  2960. var me = m.elements;
  2961. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2962. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2963. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2964. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2965. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2966. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2967. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2968. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2969. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2970. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2971. return this;
  2972. },
  2973. intersectsObject: function () {
  2974. var center = new THREE.Vector3();
  2975. return function ( object ) {
  2976. // this method is expanded inlined for performance reasons.
  2977. var matrix = object.matrixWorld;
  2978. var planes = this.planes;
  2979. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2980. center.getPositionFromMatrix( matrix );
  2981. for ( var i = 0; i < 6; i ++ ) {
  2982. var distance = planes[ i ].distanceToPoint( center );
  2983. if ( distance < negRadius ) {
  2984. return false;
  2985. }
  2986. }
  2987. return true;
  2988. };
  2989. }(),
  2990. intersectsSphere: function ( sphere ) {
  2991. var planes = this.planes;
  2992. var center = sphere.center;
  2993. var negRadius = -sphere.radius;
  2994. for ( var i = 0; i < 6; i ++ ) {
  2995. var distance = planes[ i ].distanceToPoint( center );
  2996. if ( distance < negRadius ) {
  2997. return false;
  2998. }
  2999. }
  3000. return true;
  3001. },
  3002. containsPoint: function ( point ) {
  3003. var planes = this.planes;
  3004. for ( var i = 0; i < 6; i ++ ) {
  3005. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3006. return false;
  3007. }
  3008. }
  3009. return true;
  3010. },
  3011. clone: function () {
  3012. return new THREE.Frustum().copy( this );
  3013. }
  3014. };
  3015. /**
  3016. * @author bhouston / http://exocortex.com
  3017. */
  3018. THREE.Plane = function ( normal, constant ) {
  3019. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3020. this.constant = ( constant !== undefined ) ? constant : 0;
  3021. };
  3022. THREE.Plane.prototype = {
  3023. constructor: THREE.Plane,
  3024. set: function ( normal, constant ) {
  3025. this.normal.copy( normal );
  3026. this.constant = constant;
  3027. return this;
  3028. },
  3029. setComponents: function ( x, y, z, w ) {
  3030. this.normal.set( x, y, z );
  3031. this.constant = w;
  3032. return this;
  3033. },
  3034. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3035. this.normal.copy( normal );
  3036. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3037. return this;
  3038. },
  3039. setFromCoplanarPoints: function() {
  3040. var v1 = new THREE.Vector3();
  3041. var v2 = new THREE.Vector3();
  3042. return function ( a, b, c ) {
  3043. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3044. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3045. this.setFromNormalAndCoplanarPoint( normal, a );
  3046. return this;
  3047. };
  3048. }(),
  3049. copy: function ( plane ) {
  3050. this.normal.copy( plane.normal );
  3051. this.constant = plane.constant;
  3052. return this;
  3053. },
  3054. normalize: function () {
  3055. // Note: will lead to a divide by zero if the plane is invalid.
  3056. var inverseNormalLength = 1.0 / this.normal.length();
  3057. this.normal.multiplyScalar( inverseNormalLength );
  3058. this.constant *= inverseNormalLength;
  3059. return this;
  3060. },
  3061. negate: function () {
  3062. this.constant *= -1;
  3063. this.normal.negate();
  3064. return this;
  3065. },
  3066. distanceToPoint: function ( point ) {
  3067. return this.normal.dot( point ) + this.constant;
  3068. },
  3069. distanceToSphere: function ( sphere ) {
  3070. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3071. },
  3072. projectPoint: function ( point, optionalTarget ) {
  3073. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3074. },
  3075. orthoPoint: function ( point, optionalTarget ) {
  3076. var perpendicularMagnitude = this.distanceToPoint( point );
  3077. var result = optionalTarget || new THREE.Vector3();
  3078. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3079. },
  3080. isIntersectionLine: function ( line ) {
  3081. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3082. var startSign = this.distanceToPoint( line.start );
  3083. var endSign = this.distanceToPoint( line.end );
  3084. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3085. },
  3086. intersectLine: function() {
  3087. var v1 = new THREE.Vector3();
  3088. return function ( line, optionalTarget ) {
  3089. var result = optionalTarget || new THREE.Vector3();
  3090. var direction = line.delta( v1 );
  3091. var denominator = this.normal.dot( direction );
  3092. if ( denominator == 0 ) {
  3093. // line is coplanar, return origin
  3094. if( this.distanceToPoint( line.start ) == 0 ) {
  3095. return result.copy( line.start );
  3096. }
  3097. // Unsure if this is the correct method to handle this case.
  3098. return undefined;
  3099. }
  3100. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3101. if( t < 0 || t > 1 ) {
  3102. return undefined;
  3103. }
  3104. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3105. };
  3106. }(),
  3107. coplanarPoint: function ( optionalTarget ) {
  3108. var result = optionalTarget || new THREE.Vector3();
  3109. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3110. },
  3111. applyMatrix4: function() {
  3112. var v1 = new THREE.Vector3();
  3113. var v2 = new THREE.Vector3();
  3114. return function ( matrix, optionalNormalMatrix ) {
  3115. // compute new normal based on theory here:
  3116. // http://www.songho.ca/opengl/gl_normaltransform.html
  3117. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3118. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3119. var newCoplanarPoint = this.coplanarPoint( v2 );
  3120. newCoplanarPoint.applyMatrix4( matrix );
  3121. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3122. return this;
  3123. };
  3124. }(),
  3125. translate: function ( offset ) {
  3126. this.constant = this.constant - offset.dot( this.normal );
  3127. return this;
  3128. },
  3129. equals: function ( plane ) {
  3130. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3131. },
  3132. clone: function () {
  3133. return new THREE.Plane().copy( this );
  3134. }
  3135. };
  3136. /**
  3137. * @author alteredq / http://alteredqualia.com/
  3138. */
  3139. THREE.Math = {
  3140. // Clamp value to range <a, b>
  3141. clamp: function ( x, a, b ) {
  3142. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3143. },
  3144. // Clamp value to range <a, inf)
  3145. clampBottom: function ( x, a ) {
  3146. return x < a ? a : x;
  3147. },
  3148. // Linear mapping from range <a1, a2> to range <b1, b2>
  3149. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3150. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3151. },
  3152. // http://en.wikipedia.org/wiki/Smoothstep
  3153. smoothstep: function ( x, min, max ) {
  3154. if ( x <= min ) return 0;
  3155. if ( x >= max ) return 1;
  3156. x = ( x - min )/( max - min );
  3157. return x*x*(3 - 2*x);
  3158. },
  3159. smootherstep: function ( x, min, max ) {
  3160. if ( x <= min ) return 0;
  3161. if ( x >= max ) return 1;
  3162. x = ( x - min )/( max - min );
  3163. return x*x*x*(x*(x*6 - 15) + 10);
  3164. },
  3165. // Random float from <0, 1> with 16 bits of randomness
  3166. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3167. random16: function () {
  3168. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3169. },
  3170. // Random integer from <low, high> interval
  3171. randInt: function ( low, high ) {
  3172. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3173. },
  3174. // Random float from <low, high> interval
  3175. randFloat: function ( low, high ) {
  3176. return low + Math.random() * ( high - low );
  3177. },
  3178. // Random float from <-range/2, range/2> interval
  3179. randFloatSpread: function ( range ) {
  3180. return range * ( 0.5 - Math.random() );
  3181. },
  3182. sign: function ( x ) {
  3183. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3184. },
  3185. degToRad: function() {
  3186. var degreeToRadiansFactor = Math.PI / 180;
  3187. return function ( degrees ) {
  3188. return degrees * degreeToRadiansFactor;
  3189. };
  3190. }(),
  3191. radToDeg: function() {
  3192. var radianToDegreesFactor = 180 / Math.PI;
  3193. return function ( radians ) {
  3194. return radians * radianToDegreesFactor;
  3195. };
  3196. }()
  3197. };
  3198. /**
  3199. * Spline from Tween.js, slightly optimized (and trashed)
  3200. * http://sole.github.com/tween.js/examples/05_spline.html
  3201. *
  3202. * @author mrdoob / http://mrdoob.com/
  3203. * @author alteredq / http://alteredqualia.com/
  3204. */
  3205. THREE.Spline = function ( points ) {
  3206. this.points = points;
  3207. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3208. point, intPoint, weight, w2, w3,
  3209. pa, pb, pc, pd;
  3210. this.initFromArray = function( a ) {
  3211. this.points = [];
  3212. for ( var i = 0; i < a.length; i++ ) {
  3213. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3214. }
  3215. };
  3216. this.getPoint = function ( k ) {
  3217. point = ( this.points.length - 1 ) * k;
  3218. intPoint = Math.floor( point );
  3219. weight = point - intPoint;
  3220. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3221. c[ 1 ] = intPoint;
  3222. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3223. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3224. pa = this.points[ c[ 0 ] ];
  3225. pb = this.points[ c[ 1 ] ];
  3226. pc = this.points[ c[ 2 ] ];
  3227. pd = this.points[ c[ 3 ] ];
  3228. w2 = weight * weight;
  3229. w3 = weight * w2;
  3230. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3231. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3232. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3233. return v3;
  3234. };
  3235. this.getControlPointsArray = function () {
  3236. var i, p, l = this.points.length,
  3237. coords = [];
  3238. for ( i = 0; i < l; i ++ ) {
  3239. p = this.points[ i ];
  3240. coords[ i ] = [ p.x, p.y, p.z ];
  3241. }
  3242. return coords;
  3243. };
  3244. // approximate length by summing linear segments
  3245. this.getLength = function ( nSubDivisions ) {
  3246. var i, index, nSamples, position,
  3247. point = 0, intPoint = 0, oldIntPoint = 0,
  3248. oldPosition = new THREE.Vector3(),
  3249. tmpVec = new THREE.Vector3(),
  3250. chunkLengths = [],
  3251. totalLength = 0;
  3252. // first point has 0 length
  3253. chunkLengths[ 0 ] = 0;
  3254. if ( !nSubDivisions ) nSubDivisions = 100;
  3255. nSamples = this.points.length * nSubDivisions;
  3256. oldPosition.copy( this.points[ 0 ] );
  3257. for ( i = 1; i < nSamples; i ++ ) {
  3258. index = i / nSamples;
  3259. position = this.getPoint( index );
  3260. tmpVec.copy( position );
  3261. totalLength += tmpVec.distanceTo( oldPosition );
  3262. oldPosition.copy( position );
  3263. point = ( this.points.length - 1 ) * index;
  3264. intPoint = Math.floor( point );
  3265. if ( intPoint != oldIntPoint ) {
  3266. chunkLengths[ intPoint ] = totalLength;
  3267. oldIntPoint = intPoint;
  3268. }
  3269. }
  3270. // last point ends with total length
  3271. chunkLengths[ chunkLengths.length ] = totalLength;
  3272. return { chunks: chunkLengths, total: totalLength };
  3273. };
  3274. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3275. var i, j,
  3276. index, indexCurrent, indexNext,
  3277. linearDistance, realDistance,
  3278. sampling, position,
  3279. newpoints = [],
  3280. tmpVec = new THREE.Vector3(),
  3281. sl = this.getLength();
  3282. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3283. for ( i = 1; i < this.points.length; i++ ) {
  3284. //tmpVec.copy( this.points[ i - 1 ] );
  3285. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3286. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3287. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3288. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3289. indexNext = i / ( this.points.length - 1 );
  3290. for ( j = 1; j < sampling - 1; j++ ) {
  3291. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3292. position = this.getPoint( index );
  3293. newpoints.push( tmpVec.copy( position ).clone() );
  3294. }
  3295. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3296. }
  3297. this.points = newpoints;
  3298. };
  3299. // Catmull-Rom
  3300. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3301. var v0 = ( p2 - p0 ) * 0.5,
  3302. v1 = ( p3 - p1 ) * 0.5;
  3303. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3304. };
  3305. };
  3306. /**
  3307. * @author bhouston / http://exocortex.com
  3308. * @author mrdoob / http://mrdoob.com/
  3309. */
  3310. THREE.Triangle = function ( a, b, c ) {
  3311. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3312. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3313. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3314. };
  3315. THREE.Triangle.normal = function() {
  3316. var v0 = new THREE.Vector3();
  3317. return function ( a, b, c, optionalTarget ) {
  3318. var result = optionalTarget || new THREE.Vector3();
  3319. result.subVectors( c, b );
  3320. v0.subVectors( a, b );
  3321. result.cross( v0 );
  3322. var resultLengthSq = result.lengthSq();
  3323. if( resultLengthSq > 0 ) {
  3324. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3325. }
  3326. return result.set( 0, 0, 0 );
  3327. };
  3328. }();
  3329. // static/instance method to calculate barycoordinates
  3330. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3331. THREE.Triangle.barycoordFromPoint = function() {
  3332. var v0 = new THREE.Vector3();
  3333. var v1 = new THREE.Vector3();
  3334. var v2 = new THREE.Vector3();
  3335. return function ( point, a, b, c, optionalTarget ) {
  3336. v0.subVectors( c, a );
  3337. v1.subVectors( b, a );
  3338. v2.subVectors( point, a );
  3339. var dot00 = v0.dot( v0 );
  3340. var dot01 = v0.dot( v1 );
  3341. var dot02 = v0.dot( v2 );
  3342. var dot11 = v1.dot( v1 );
  3343. var dot12 = v1.dot( v2 );
  3344. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3345. var result = optionalTarget || new THREE.Vector3();
  3346. // colinear or singular triangle
  3347. if( denom == 0 ) {
  3348. // arbitrary location outside of triangle?
  3349. // not sure if this is the best idea, maybe should be returning undefined
  3350. return result.set( -2, -1, -1 );
  3351. }
  3352. var invDenom = 1 / denom;
  3353. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3354. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3355. // barycoordinates must always sum to 1
  3356. return result.set( 1 - u - v, v, u );
  3357. };
  3358. }();
  3359. THREE.Triangle.containsPoint = function() {
  3360. var v1 = new THREE.Vector3();
  3361. return function ( point, a, b, c ) {
  3362. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3363. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3364. };
  3365. }();
  3366. THREE.Triangle.prototype = {
  3367. constructor: THREE.Triangle,
  3368. set: function ( a, b, c ) {
  3369. this.a.copy( a );
  3370. this.b.copy( b );
  3371. this.c.copy( c );
  3372. return this;
  3373. },
  3374. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3375. this.a.copy( points[i0] );
  3376. this.b.copy( points[i1] );
  3377. this.c.copy( points[i2] );
  3378. return this;
  3379. },
  3380. copy: function ( triangle ) {
  3381. this.a.copy( triangle.a );
  3382. this.b.copy( triangle.b );
  3383. this.c.copy( triangle.c );
  3384. return this;
  3385. },
  3386. area: function() {
  3387. var v0 = new THREE.Vector3();
  3388. var v1 = new THREE.Vector3();
  3389. return function () {
  3390. v0.subVectors( this.c, this.b );
  3391. v1.subVectors( this.a, this.b );
  3392. return v0.cross( v1 ).length() * 0.5;
  3393. };
  3394. }(),
  3395. midpoint: function ( optionalTarget ) {
  3396. var result = optionalTarget || new THREE.Vector3();
  3397. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3398. },
  3399. normal: function ( optionalTarget ) {
  3400. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3401. },
  3402. plane: function ( optionalTarget ) {
  3403. var result = optionalTarget || new THREE.Plane();
  3404. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3405. },
  3406. barycoordFromPoint: function ( point, optionalTarget ) {
  3407. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3408. },
  3409. containsPoint: function ( point ) {
  3410. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3411. },
  3412. equals: function ( triangle ) {
  3413. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3414. },
  3415. clone: function () {
  3416. return new THREE.Triangle().copy( this );
  3417. }
  3418. };
  3419. /**
  3420. * @author mrdoob / http://mrdoob.com/
  3421. */
  3422. THREE.Vertex = function ( v ) {
  3423. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3424. return v;
  3425. };
  3426. /**
  3427. * @author mrdoob / http://mrdoob.com/
  3428. */
  3429. THREE.UV = function ( u, v ) {
  3430. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3431. return new THREE.Vector2( u, v );
  3432. };
  3433. /**
  3434. * @author alteredq / http://alteredqualia.com/
  3435. */
  3436. THREE.Clock = function ( autoStart ) {
  3437. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3438. this.startTime = 0;
  3439. this.oldTime = 0;
  3440. this.elapsedTime = 0;
  3441. this.running = false;
  3442. };
  3443. THREE.extend( THREE.Clock.prototype, {
  3444. start: function () {
  3445. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3446. ? window.performance.now()
  3447. : Date.now();
  3448. this.oldTime = this.startTime;
  3449. this.running = true;
  3450. },
  3451. stop: function () {
  3452. this.getElapsedTime();
  3453. this.running = false;
  3454. },
  3455. getElapsedTime: function () {
  3456. this.getDelta();
  3457. return this.elapsedTime;
  3458. },
  3459. getDelta: function () {
  3460. var diff = 0;
  3461. if ( this.autoStart && ! this.running ) {
  3462. this.start();
  3463. }
  3464. if ( this.running ) {
  3465. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3466. ? window.performance.now()
  3467. : Date.now();
  3468. diff = 0.001 * ( newTime - this.oldTime );
  3469. this.oldTime = newTime;
  3470. this.elapsedTime += diff;
  3471. }
  3472. return diff;
  3473. }
  3474. } );
  3475. /**
  3476. * https://github.com/mrdoob/eventdispatcher.js/
  3477. */
  3478. THREE.EventDispatcher = function () {}
  3479. THREE.EventDispatcher.prototype = {
  3480. constructor: THREE.EventDispatcher,
  3481. addEventListener: function ( type, listener ) {
  3482. if ( this._listeners === undefined ) this._listeners = {};
  3483. var listeners = this._listeners;
  3484. if ( listeners[ type ] === undefined ) {
  3485. listeners[ type ] = [];
  3486. }
  3487. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3488. listeners[ type ].push( listener );
  3489. }
  3490. },
  3491. hasEventListener: function ( type, listener ) {
  3492. if ( this._listeners === undefined ) return false;
  3493. var listeners = this._listeners;
  3494. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3495. return true;
  3496. }
  3497. return false;
  3498. },
  3499. removeEventListener: function ( type, listener ) {
  3500. if ( this._listeners === undefined ) return;
  3501. var listeners = this._listeners;
  3502. var index = listeners[ type ].indexOf( listener );
  3503. if ( index !== - 1 ) {
  3504. listeners[ type ].splice( index, 1 );
  3505. }
  3506. },
  3507. dispatchEvent: function ( event ) {
  3508. if ( this._listeners === undefined ) return;
  3509. var listeners = this._listeners;
  3510. var listenerArray = listeners[ event.type ];
  3511. if ( listenerArray !== undefined ) {
  3512. event.target = this;
  3513. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3514. listenerArray[ i ].call( this, event );
  3515. }
  3516. }
  3517. }
  3518. };
  3519. /**
  3520. * @author mrdoob / http://mrdoob.com/
  3521. * @author bhouston / http://exocortex.com/
  3522. */
  3523. ( function ( THREE ) {
  3524. THREE.Raycaster = function ( origin, direction, near, far ) {
  3525. this.ray = new THREE.Ray( origin, direction );
  3526. // normalized ray.direction required for accurate distance calculations
  3527. if ( this.ray.direction.lengthSq() > 0 ) {
  3528. this.ray.direction.normalize();
  3529. }
  3530. this.near = near || 0;
  3531. this.far = far || Infinity;
  3532. };
  3533. var sphere = new THREE.Sphere();
  3534. var localRay = new THREE.Ray();
  3535. var facePlane = new THREE.Plane();
  3536. var intersectPoint = new THREE.Vector3();
  3537. var matrixPosition = new THREE.Vector3();
  3538. var inverseMatrix = new THREE.Matrix4();
  3539. var descSort = function ( a, b ) {
  3540. return a.distance - b.distance;
  3541. };
  3542. var intersectObject = function ( object, raycaster, intersects ) {
  3543. if ( object instanceof THREE.Particle ) {
  3544. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3545. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3546. if ( distance > object.scale.x ) {
  3547. return intersects;
  3548. }
  3549. intersects.push( {
  3550. distance: distance,
  3551. point: object.position,
  3552. face: null,
  3553. object: object
  3554. } );
  3555. } else if ( object instanceof THREE.LOD ) {
  3556. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3557. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3558. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3559. } else if ( object instanceof THREE.Mesh ) {
  3560. // Checking boundingSphere distance to ray
  3561. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3562. sphere.set(
  3563. matrixPosition,
  3564. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3565. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3566. return intersects;
  3567. }
  3568. // Checking faces
  3569. var geometry = object.geometry;
  3570. var vertices = geometry.vertices;
  3571. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3572. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3573. var side = object.material.side;
  3574. var a, b, c, d;
  3575. var precision = raycaster.precision;
  3576. object.matrixRotationWorld.copyRotation( object.matrixWorld );
  3577. inverseMatrix.getInverse( object.matrixWorld );
  3578. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3579. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3580. var face = geometry.faces[ f ];
  3581. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3582. if ( material === undefined ) continue;
  3583. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3584. var planeDistance = localRay.distanceToPlane( facePlane );
  3585. // bail if raycaster and plane are parallel
  3586. if ( Math.abs( planeDistance ) < precision ) continue;
  3587. // if negative distance, then plane is behind raycaster
  3588. if ( planeDistance < 0 ) continue;
  3589. // check if we hit the wrong side of a single sided face
  3590. side = material.side;
  3591. if ( side !== THREE.DoubleSide ) {
  3592. var planeSign = localRay.direction.dot( facePlane.normal );
  3593. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3594. }
  3595. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3596. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3597. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3598. if ( face instanceof THREE.Face3 ) {
  3599. a = vertices[ face.a ];
  3600. b = vertices[ face.b ];
  3601. c = vertices[ face.c ];
  3602. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3603. } else if ( face instanceof THREE.Face4 ) {
  3604. a = vertices[ face.a ];
  3605. b = vertices[ face.b ];
  3606. c = vertices[ face.c ];
  3607. d = vertices[ face.d ];
  3608. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3609. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3610. } else {
  3611. // This is added because if we call out of this if/else group when none of the cases
  3612. // match it will add a point to the intersection list erroneously.
  3613. throw Error( "face type not supported" );
  3614. }
  3615. intersects.push( {
  3616. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3617. point: raycaster.ray.at( planeDistance ),
  3618. face: face,
  3619. faceIndex: f,
  3620. object: object
  3621. } );
  3622. }
  3623. }
  3624. };
  3625. var intersectDescendants = function ( object, raycaster, intersects ) {
  3626. var descendants = object.getDescendants();
  3627. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3628. intersectObject( descendants[ i ], raycaster, intersects );
  3629. }
  3630. };
  3631. //
  3632. THREE.Raycaster.prototype.precision = 0.0001;
  3633. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3634. this.ray.set( origin, direction );
  3635. // normalized ray.direction required for accurate distance calculations
  3636. if ( this.ray.direction.length() > 0 ) {
  3637. this.ray.direction.normalize();
  3638. }
  3639. };
  3640. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3641. var intersects = [];
  3642. if ( recursive === true ) {
  3643. intersectDescendants( object, this, intersects );
  3644. }
  3645. intersectObject( object, this, intersects );
  3646. intersects.sort( descSort );
  3647. return intersects;
  3648. };
  3649. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3650. var intersects = [];
  3651. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3652. intersectObject( objects[ i ], this, intersects );
  3653. if ( recursive === true ) {
  3654. intersectDescendants( objects[ i ], this, intersects );
  3655. }
  3656. }
  3657. intersects.sort( descSort );
  3658. return intersects;
  3659. };
  3660. }( THREE ) );
  3661. /**
  3662. * @author mrdoob / http://mrdoob.com/
  3663. * @author mikael emtinger / http://gomo.se/
  3664. * @author alteredq / http://alteredqualia.com/
  3665. * @author WestLangley / http://github.com/WestLangley
  3666. */
  3667. THREE.Object3D = function () {
  3668. this.id = THREE.Object3DIdCount ++;
  3669. this.name = '';
  3670. this.parent = undefined;
  3671. this.children = [];
  3672. this.up = new THREE.Vector3( 0, 1, 0 );
  3673. this.position = new THREE.Vector3();
  3674. this.rotation = new THREE.Vector3();
  3675. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3676. this.scale = new THREE.Vector3( 1, 1, 1 );
  3677. this.renderDepth = null;
  3678. this.rotationAutoUpdate = true;
  3679. this.matrix = new THREE.Matrix4();
  3680. this.matrixWorld = new THREE.Matrix4();
  3681. this.matrixRotationWorld = new THREE.Matrix4();
  3682. this.matrixAutoUpdate = true;
  3683. this.matrixWorldNeedsUpdate = true;
  3684. this.quaternion = new THREE.Quaternion();
  3685. this.useQuaternion = false;
  3686. this.visible = true;
  3687. this.castShadow = false;
  3688. this.receiveShadow = false;
  3689. this.frustumCulled = true;
  3690. this.userData = {};
  3691. };
  3692. THREE.Object3D.prototype = {
  3693. constructor: THREE.Object3D,
  3694. applyMatrix: function () {
  3695. var m1 = new THREE.Matrix4();
  3696. return function ( matrix ) {
  3697. this.matrix.multiplyMatrices( matrix, this.matrix );
  3698. this.position.getPositionFromMatrix( this.matrix );
  3699. this.scale.getScaleFromMatrix( this.matrix );
  3700. m1.copyRotation( this.matrix );
  3701. if ( this.useQuaternion === true ) {
  3702. this.quaternion.setFromRotationMatrix( m1 );
  3703. } else {
  3704. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3705. }
  3706. }
  3707. }(),
  3708. rotateOnAxis: function() {
  3709. // rotate object on axis in object space
  3710. // axis is assumed to be normalized
  3711. var q1 = new THREE.Quaternion();
  3712. var q2 = new THREE.Quaternion();
  3713. return function ( axis, angle ) {
  3714. q1.setFromAxisAngle( axis, angle );
  3715. if ( this.useQuaternion === true ) {
  3716. this.quaternion.multiply( q1 );
  3717. } else {
  3718. q2.setFromEuler( this.rotation, this.eulerOrder );
  3719. q2.multiply( q1 );
  3720. this.rotation.setEulerFromQuaternion( q2, this.eulerOrder );
  3721. }
  3722. return this;
  3723. }
  3724. }(),
  3725. translateOnAxis: function () {
  3726. // translate object by distance along axis in object space
  3727. // axis is assumed to be normalized
  3728. var v1 = new THREE.Vector3();
  3729. return function ( axis, distance ) {
  3730. v1.copy( axis );
  3731. if ( this.useQuaternion === true ) {
  3732. v1.applyQuaternion( this.quaternion );
  3733. } else {
  3734. v1.applyEuler( this.rotation, this.eulerOrder );
  3735. }
  3736. this.position.add( v1.multiplyScalar( distance ) );
  3737. return this;
  3738. }
  3739. }(),
  3740. translate: function ( distance, axis ) {
  3741. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  3742. return this.translateOnAxis( axis, distance );
  3743. },
  3744. translateX: function () {
  3745. var v1 = new THREE.Vector3( 1, 0, 0 );
  3746. return function ( distance ) {
  3747. return this.translateOnAxis( v1, distance );
  3748. };
  3749. }(),
  3750. translateY: function () {
  3751. var v1 = new THREE.Vector3( 0, 1, 0 );
  3752. return function ( distance ) {
  3753. return this.translateOnAxis( v1, distance );
  3754. };
  3755. }(),
  3756. translateZ: function () {
  3757. var v1 = new THREE.Vector3( 0, 0, 1 );
  3758. return function ( distance ) {
  3759. return this.translateOnAxis( v1, distance );
  3760. };
  3761. }(),
  3762. localToWorld: function ( vector ) {
  3763. return vector.applyMatrix4( this.matrixWorld );
  3764. },
  3765. worldToLocal: function () {
  3766. var m1 = new THREE.Matrix4();
  3767. return function ( vector ) {
  3768. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3769. };
  3770. }(),
  3771. lookAt: function () {
  3772. // This routine does not support objects with rotated and/or translated parent(s)
  3773. var m1 = new THREE.Matrix4();
  3774. return function ( vector ) {
  3775. m1.lookAt( vector, this.position, this.up );
  3776. if ( this.useQuaternion === true ) {
  3777. this.quaternion.setFromRotationMatrix( m1 );
  3778. } else {
  3779. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3780. }
  3781. };
  3782. }(),
  3783. add: function ( object ) {
  3784. if ( object === this ) {
  3785. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3786. return;
  3787. }
  3788. if ( object instanceof THREE.Object3D ) {
  3789. if ( object.parent !== undefined ) {
  3790. object.parent.remove( object );
  3791. }
  3792. object.parent = this;
  3793. this.children.push( object );
  3794. // add to scene
  3795. var scene = this;
  3796. while ( scene.parent !== undefined ) {
  3797. scene = scene.parent;
  3798. }
  3799. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3800. scene.__addObject( object );
  3801. }
  3802. }
  3803. },
  3804. remove: function ( object ) {
  3805. var index = this.children.indexOf( object );
  3806. if ( index !== - 1 ) {
  3807. object.parent = undefined;
  3808. this.children.splice( index, 1 );
  3809. // remove from scene
  3810. var scene = this;
  3811. while ( scene.parent !== undefined ) {
  3812. scene = scene.parent;
  3813. }
  3814. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3815. scene.__removeObject( object );
  3816. }
  3817. }
  3818. },
  3819. traverse: function ( callback ) {
  3820. callback( this );
  3821. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3822. this.children[ i ].traverse( callback );
  3823. }
  3824. },
  3825. getObjectById: function ( id, recursive ) {
  3826. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3827. var child = this.children[ i ];
  3828. if ( child.id === id ) {
  3829. return child;
  3830. }
  3831. if ( recursive === true ) {
  3832. child = child.getObjectById( id, recursive );
  3833. if ( child !== undefined ) {
  3834. return child;
  3835. }
  3836. }
  3837. }
  3838. return undefined;
  3839. },
  3840. getObjectByName: function ( name, recursive ) {
  3841. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3842. var child = this.children[ i ];
  3843. if ( child.name === name ) {
  3844. return child;
  3845. }
  3846. if ( recursive === true ) {
  3847. child = child.getObjectByName( name, recursive );
  3848. if ( child !== undefined ) {
  3849. return child;
  3850. }
  3851. }
  3852. }
  3853. return undefined;
  3854. },
  3855. getChildByName: function ( name, recursive ) {
  3856. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  3857. return this.getObjectByName( name, recursive );
  3858. },
  3859. getDescendants: function ( array ) {
  3860. if ( array === undefined ) array = [];
  3861. Array.prototype.push.apply( array, this.children );
  3862. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3863. this.children[ i ].getDescendants( array );
  3864. }
  3865. return array;
  3866. },
  3867. updateMatrix: function () {
  3868. this.matrix.setPosition( this.position );
  3869. if ( this.useQuaternion === false ) {
  3870. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3871. } else {
  3872. this.matrix.setRotationFromQuaternion( this.quaternion );
  3873. }
  3874. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3875. this.matrix.scale( this.scale );
  3876. }
  3877. this.matrixWorldNeedsUpdate = true;
  3878. },
  3879. updateMatrixWorld: function ( force ) {
  3880. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3881. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3882. if ( this.parent === undefined ) {
  3883. this.matrixWorld.copy( this.matrix );
  3884. } else {
  3885. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3886. }
  3887. this.matrixWorldNeedsUpdate = false;
  3888. force = true;
  3889. }
  3890. // update children
  3891. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3892. this.children[ i ].updateMatrixWorld( force );
  3893. }
  3894. },
  3895. clone: function ( object ) {
  3896. if ( object === undefined ) object = new THREE.Object3D();
  3897. object.name = this.name;
  3898. object.up.copy( this.up );
  3899. object.position.copy( this.position );
  3900. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3901. object.eulerOrder = this.eulerOrder;
  3902. object.scale.copy( this.scale );
  3903. object.renderDepth = this.renderDepth;
  3904. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3905. object.matrix.copy( this.matrix );
  3906. object.matrixWorld.copy( this.matrixWorld );
  3907. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3908. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3909. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3910. object.quaternion.copy( this.quaternion );
  3911. object.useQuaternion = this.useQuaternion;
  3912. object.visible = this.visible;
  3913. object.castShadow = this.castShadow;
  3914. object.receiveShadow = this.receiveShadow;
  3915. object.frustumCulled = this.frustumCulled;
  3916. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  3917. for ( var i = 0; i < this.children.length; i ++ ) {
  3918. var child = this.children[ i ];
  3919. object.add( child.clone() );
  3920. }
  3921. return object;
  3922. }
  3923. };
  3924. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3925. THREE.Object3DIdCount = 0;
  3926. /**
  3927. * @author mrdoob / http://mrdoob.com/
  3928. * @author supereggbert / http://www.paulbrunt.co.uk/
  3929. * @author julianwa / https://github.com/julianwa
  3930. */
  3931. THREE.Projector = function () {
  3932. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3933. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3934. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3935. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3936. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3937. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3938. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3939. _vector3 = new THREE.Vector3(),
  3940. _vector4 = new THREE.Vector4(),
  3941. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3942. _boundingBox = new THREE.Box3(),
  3943. _points3 = new Array( 3 ),
  3944. _points4 = new Array( 4 ),
  3945. _viewMatrix = new THREE.Matrix4(),
  3946. _viewProjectionMatrix = new THREE.Matrix4(),
  3947. _modelMatrix,
  3948. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3949. _normalMatrix = new THREE.Matrix3(),
  3950. _normalViewMatrix = new THREE.Matrix3(),
  3951. _centroid = new THREE.Vector3(),
  3952. _frustum = new THREE.Frustum(),
  3953. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3954. _clippedVertex2PositionScreen = new THREE.Vector4();
  3955. this.projectVector = function ( vector, camera ) {
  3956. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3957. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3958. return vector.applyProjection( _viewProjectionMatrix );
  3959. };
  3960. this.unprojectVector = function ( vector, camera ) {
  3961. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3962. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3963. return vector.applyProjection( _viewProjectionMatrix );
  3964. };
  3965. this.pickingRay = function ( vector, camera ) {
  3966. // set two vectors with opposing z values
  3967. vector.z = -1.0;
  3968. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3969. this.unprojectVector( vector, camera );
  3970. this.unprojectVector( end, camera );
  3971. // find direction from vector to end
  3972. end.sub( vector ).normalize();
  3973. return new THREE.Raycaster( vector, end );
  3974. };
  3975. var projectGraph = function ( root, sortObjects ) {
  3976. _objectCount = 0;
  3977. _renderData.objects.length = 0;
  3978. _renderData.sprites.length = 0;
  3979. _renderData.lights.length = 0;
  3980. var projectObject = function ( parent ) {
  3981. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3982. var object = parent.children[ c ];
  3983. if ( object.visible === false ) continue;
  3984. if ( object instanceof THREE.Light ) {
  3985. _renderData.lights.push( object );
  3986. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3987. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3988. _object = getNextObjectInPool();
  3989. _object.object = object;
  3990. if ( object.renderDepth !== null ) {
  3991. _object.z = object.renderDepth;
  3992. } else {
  3993. _vector3.getPositionFromMatrix( object.matrixWorld );
  3994. _vector3.applyProjection( _viewProjectionMatrix );
  3995. _object.z = _vector3.z;
  3996. }
  3997. _renderData.objects.push( _object );
  3998. }
  3999. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4000. _object = getNextObjectInPool();
  4001. _object.object = object;
  4002. // TODO: Find an elegant and performant solution and remove this dupe code.
  4003. if ( object.renderDepth !== null ) {
  4004. _object.z = object.renderDepth;
  4005. } else {
  4006. _vector3.getPositionFromMatrix( object.matrixWorld );
  4007. _vector3.applyProjection( _viewProjectionMatrix );
  4008. _object.z = _vector3.z;
  4009. }
  4010. _renderData.sprites.push( _object );
  4011. } else {
  4012. _object = getNextObjectInPool();
  4013. _object.object = object;
  4014. if ( object.renderDepth !== null ) {
  4015. _object.z = object.renderDepth;
  4016. } else {
  4017. _vector3.getPositionFromMatrix( object.matrixWorld );
  4018. _vector3.applyProjection( _viewProjectionMatrix );
  4019. _object.z = _vector3.z;
  4020. }
  4021. _renderData.objects.push( _object );
  4022. }
  4023. projectObject( object );
  4024. }
  4025. };
  4026. projectObject( root );
  4027. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  4028. return _renderData;
  4029. };
  4030. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4031. var visible = false,
  4032. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4033. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4034. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4035. _face3Count = 0;
  4036. _face4Count = 0;
  4037. _lineCount = 0;
  4038. _particleCount = 0;
  4039. _renderData.elements.length = 0;
  4040. scene.updateMatrixWorld();
  4041. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4042. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4043. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4044. _normalViewMatrix.getInverse( _viewMatrix );
  4045. _normalViewMatrix.transpose();
  4046. _frustum.setFromMatrix( _viewProjectionMatrix );
  4047. _renderData = projectGraph( scene, sortObjects );
  4048. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4049. object = _renderData.objects[ o ].object;
  4050. _modelMatrix = object.matrixWorld;
  4051. _vertexCount = 0;
  4052. if ( object instanceof THREE.Mesh ) {
  4053. geometry = object.geometry;
  4054. vertices = geometry.vertices;
  4055. faces = geometry.faces;
  4056. faceVertexUvs = geometry.faceVertexUvs;
  4057. _normalMatrix.getInverse( _modelMatrix );
  4058. _normalMatrix.transpose();
  4059. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4060. objectMaterials = isFaceMaterial === true ? object.material : null;
  4061. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4062. _vertex = getNextVertexInPool();
  4063. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4064. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4065. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4066. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4067. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4068. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4069. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4070. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4071. }
  4072. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4073. face = faces[ f ];
  4074. var material = isFaceMaterial === true
  4075. ? objectMaterials.materials[ face.materialIndex ]
  4076. : object.material;
  4077. if ( material === undefined ) continue;
  4078. var side = material.side;
  4079. if ( face instanceof THREE.Face3 ) {
  4080. v1 = _vertexPool[ face.a ];
  4081. v2 = _vertexPool[ face.b ];
  4082. v3 = _vertexPool[ face.c ];
  4083. _points3[ 0 ] = v1.positionScreen;
  4084. _points3[ 1 ] = v2.positionScreen;
  4085. _points3[ 2 ] = v3.positionScreen;
  4086. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4087. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4088. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4089. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4090. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4091. _face = getNextFace3InPool();
  4092. _face.v1.copy( v1 );
  4093. _face.v2.copy( v2 );
  4094. _face.v3.copy( v3 );
  4095. } else {
  4096. continue;
  4097. }
  4098. } else {
  4099. continue;
  4100. }
  4101. } else if ( face instanceof THREE.Face4 ) {
  4102. v1 = _vertexPool[ face.a ];
  4103. v2 = _vertexPool[ face.b ];
  4104. v3 = _vertexPool[ face.c ];
  4105. v4 = _vertexPool[ face.d ];
  4106. _points4[ 0 ] = v1.positionScreen;
  4107. _points4[ 1 ] = v2.positionScreen;
  4108. _points4[ 2 ] = v3.positionScreen;
  4109. _points4[ 3 ] = v4.positionScreen;
  4110. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4111. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4112. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4113. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4114. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4115. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4116. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4117. _face = getNextFace4InPool();
  4118. _face.v1.copy( v1 );
  4119. _face.v2.copy( v2 );
  4120. _face.v3.copy( v3 );
  4121. _face.v4.copy( v4 );
  4122. } else {
  4123. continue;
  4124. }
  4125. } else {
  4126. continue;
  4127. }
  4128. }
  4129. _face.normalModel.copy( face.normal );
  4130. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4131. _face.normalModel.negate();
  4132. }
  4133. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4134. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4135. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4136. faceVertexNormals = face.vertexNormals;
  4137. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4138. var normalModel = _face.vertexNormalsModel[ n ];
  4139. normalModel.copy( faceVertexNormals[ n ] );
  4140. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4141. normalModel.negate();
  4142. }
  4143. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4144. var normalModelView = _face.vertexNormalsModelView[ n ];
  4145. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4146. }
  4147. _face.vertexNormalsLength = faceVertexNormals.length;
  4148. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4149. uvs = faceVertexUvs[ c ][ f ];
  4150. if ( uvs === undefined ) continue;
  4151. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4152. _face.uvs[ c ][ u ] = uvs[ u ];
  4153. }
  4154. }
  4155. _face.color = face.color;
  4156. _face.material = material;
  4157. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4158. _face.z = _centroid.z;
  4159. _renderData.elements.push( _face );
  4160. }
  4161. } else if ( object instanceof THREE.Line ) {
  4162. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4163. vertices = object.geometry.vertices;
  4164. v1 = getNextVertexInPool();
  4165. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4166. // Handle LineStrip and LinePieces
  4167. var step = object.type === THREE.LinePieces ? 2 : 1;
  4168. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4169. v1 = getNextVertexInPool();
  4170. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4171. if ( ( v + 1 ) % step > 0 ) continue;
  4172. v2 = _vertexPool[ _vertexCount - 2 ];
  4173. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4174. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4175. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4176. // Perform the perspective divide
  4177. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4178. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4179. _line = getNextLineInPool();
  4180. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4181. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4182. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4183. _line.material = object.material;
  4184. _renderData.elements.push( _line );
  4185. }
  4186. }
  4187. }
  4188. }
  4189. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4190. object = _renderData.sprites[ o ].object;
  4191. _modelMatrix = object.matrixWorld;
  4192. if ( object instanceof THREE.Particle ) {
  4193. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4194. _vector4.applyMatrix4( _viewProjectionMatrix );
  4195. _vector4.z /= _vector4.w;
  4196. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4197. _particle = getNextParticleInPool();
  4198. _particle.object = object;
  4199. _particle.x = _vector4.x / _vector4.w;
  4200. _particle.y = _vector4.y / _vector4.w;
  4201. _particle.z = _vector4.z;
  4202. _particle.rotation = object.rotation.z;
  4203. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4204. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4205. _particle.material = object.material;
  4206. _renderData.elements.push( _particle );
  4207. }
  4208. }
  4209. }
  4210. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4211. return _renderData;
  4212. };
  4213. // Pools
  4214. function getNextObjectInPool() {
  4215. if ( _objectCount === _objectPoolLength ) {
  4216. var object = new THREE.RenderableObject();
  4217. _objectPool.push( object );
  4218. _objectPoolLength ++;
  4219. _objectCount ++;
  4220. return object;
  4221. }
  4222. return _objectPool[ _objectCount ++ ];
  4223. }
  4224. function getNextVertexInPool() {
  4225. if ( _vertexCount === _vertexPoolLength ) {
  4226. var vertex = new THREE.RenderableVertex();
  4227. _vertexPool.push( vertex );
  4228. _vertexPoolLength ++;
  4229. _vertexCount ++;
  4230. return vertex;
  4231. }
  4232. return _vertexPool[ _vertexCount ++ ];
  4233. }
  4234. function getNextFace3InPool() {
  4235. if ( _face3Count === _face3PoolLength ) {
  4236. var face = new THREE.RenderableFace3();
  4237. _face3Pool.push( face );
  4238. _face3PoolLength ++;
  4239. _face3Count ++;
  4240. return face;
  4241. }
  4242. return _face3Pool[ _face3Count ++ ];
  4243. }
  4244. function getNextFace4InPool() {
  4245. if ( _face4Count === _face4PoolLength ) {
  4246. var face = new THREE.RenderableFace4();
  4247. _face4Pool.push( face );
  4248. _face4PoolLength ++;
  4249. _face4Count ++;
  4250. return face;
  4251. }
  4252. return _face4Pool[ _face4Count ++ ];
  4253. }
  4254. function getNextLineInPool() {
  4255. if ( _lineCount === _linePoolLength ) {
  4256. var line = new THREE.RenderableLine();
  4257. _linePool.push( line );
  4258. _linePoolLength ++;
  4259. _lineCount ++
  4260. return line;
  4261. }
  4262. return _linePool[ _lineCount ++ ];
  4263. }
  4264. function getNextParticleInPool() {
  4265. if ( _particleCount === _particlePoolLength ) {
  4266. var particle = new THREE.RenderableParticle();
  4267. _particlePool.push( particle );
  4268. _particlePoolLength ++;
  4269. _particleCount ++
  4270. return particle;
  4271. }
  4272. return _particlePool[ _particleCount ++ ];
  4273. }
  4274. //
  4275. function painterSort( a, b ) {
  4276. return b.z - a.z;
  4277. }
  4278. function clipLine( s1, s2 ) {
  4279. var alpha1 = 0, alpha2 = 1,
  4280. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4281. // Z = -1 and Z = +1, respectively.
  4282. bc1near = s1.z + s1.w,
  4283. bc2near = s2.z + s2.w,
  4284. bc1far = - s1.z + s1.w,
  4285. bc2far = - s2.z + s2.w;
  4286. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4287. // Both vertices lie entirely within all clip planes.
  4288. return true;
  4289. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4290. // Both vertices lie entirely outside one of the clip planes.
  4291. return false;
  4292. } else {
  4293. // The line segment spans at least one clip plane.
  4294. if ( bc1near < 0 ) {
  4295. // v1 lies outside the near plane, v2 inside
  4296. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4297. } else if ( bc2near < 0 ) {
  4298. // v2 lies outside the near plane, v1 inside
  4299. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4300. }
  4301. if ( bc1far < 0 ) {
  4302. // v1 lies outside the far plane, v2 inside
  4303. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4304. } else if ( bc2far < 0 ) {
  4305. // v2 lies outside the far plane, v2 inside
  4306. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4307. }
  4308. if ( alpha2 < alpha1 ) {
  4309. // The line segment spans two boundaries, but is outside both of them.
  4310. // (This can't happen when we're only clipping against just near/far but good
  4311. // to leave the check here for future usage if other clip planes are added.)
  4312. return false;
  4313. } else {
  4314. // Update the s1 and s2 vertices to match the clipped line segment.
  4315. s1.lerp( s2, alpha1 );
  4316. s2.lerp( s1, 1 - alpha2 );
  4317. return true;
  4318. }
  4319. }
  4320. }
  4321. };
  4322. /**
  4323. * @author mrdoob / http://mrdoob.com/
  4324. * @author alteredq / http://alteredqualia.com/
  4325. */
  4326. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4327. this.a = a;
  4328. this.b = b;
  4329. this.c = c;
  4330. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4331. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4332. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4333. this.vertexColors = color instanceof Array ? color : [];
  4334. this.vertexTangents = [];
  4335. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4336. this.centroid = new THREE.Vector3();
  4337. };
  4338. THREE.Face3.prototype = {
  4339. constructor: THREE.Face3,
  4340. clone: function () {
  4341. var face = new THREE.Face3( this.a, this.b, this.c );
  4342. face.normal.copy( this.normal );
  4343. face.color.copy( this.color );
  4344. face.centroid.copy( this.centroid );
  4345. face.materialIndex = this.materialIndex;
  4346. var i, il;
  4347. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4348. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4349. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4350. return face;
  4351. }
  4352. };
  4353. /**
  4354. * @author mrdoob / http://mrdoob.com/
  4355. * @author alteredq / http://alteredqualia.com/
  4356. */
  4357. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4358. this.a = a;
  4359. this.b = b;
  4360. this.c = c;
  4361. this.d = d;
  4362. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4363. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4364. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4365. this.vertexColors = color instanceof Array ? color : [];
  4366. this.vertexTangents = [];
  4367. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4368. this.centroid = new THREE.Vector3();
  4369. };
  4370. THREE.Face4.prototype = {
  4371. constructor: THREE.Face4,
  4372. clone: function () {
  4373. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4374. face.normal.copy( this.normal );
  4375. face.color.copy( this.color );
  4376. face.centroid.copy( this.centroid );
  4377. face.materialIndex = this.materialIndex;
  4378. var i, il;
  4379. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4380. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4381. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4382. return face;
  4383. }
  4384. };
  4385. /**
  4386. * @author mrdoob / http://mrdoob.com/
  4387. * @author kile / http://kile.stravaganza.org/
  4388. * @author alteredq / http://alteredqualia.com/
  4389. * @author mikael emtinger / http://gomo.se/
  4390. * @author zz85 / http://www.lab4games.net/zz85/blog
  4391. * @author bhouston / http://exocortex.com
  4392. */
  4393. THREE.Geometry = function () {
  4394. this.id = THREE.GeometryIdCount ++;
  4395. this.name = '';
  4396. this.vertices = [];
  4397. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4398. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4399. this.faces = [];
  4400. this.faceUvs = [[]];
  4401. this.faceVertexUvs = [[]];
  4402. this.morphTargets = [];
  4403. this.morphColors = [];
  4404. this.morphNormals = [];
  4405. this.skinWeights = [];
  4406. this.skinIndices = [];
  4407. this.lineDistances = [];
  4408. this.boundingBox = null;
  4409. this.boundingSphere = null;
  4410. this.hasTangents = false;
  4411. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4412. // update flags
  4413. this.verticesNeedUpdate = false;
  4414. this.elementsNeedUpdate = false;
  4415. this.uvsNeedUpdate = false;
  4416. this.normalsNeedUpdate = false;
  4417. this.tangentsNeedUpdate = false;
  4418. this.colorsNeedUpdate = false;
  4419. this.lineDistancesNeedUpdate = false;
  4420. this.buffersNeedUpdate = false;
  4421. };
  4422. THREE.Geometry.prototype = {
  4423. constructor: THREE.Geometry,
  4424. applyMatrix: function ( matrix ) {
  4425. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4426. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4427. var vertex = this.vertices[ i ];
  4428. vertex.applyMatrix4( matrix );
  4429. }
  4430. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4431. var face = this.faces[ i ];
  4432. face.normal.applyMatrix3( normalMatrix ).normalize();
  4433. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4434. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4435. }
  4436. face.centroid.applyMatrix4( matrix );
  4437. }
  4438. },
  4439. computeCentroids: function () {
  4440. var f, fl, face;
  4441. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4442. face = this.faces[ f ];
  4443. face.centroid.set( 0, 0, 0 );
  4444. if ( face instanceof THREE.Face3 ) {
  4445. face.centroid.add( this.vertices[ face.a ] );
  4446. face.centroid.add( this.vertices[ face.b ] );
  4447. face.centroid.add( this.vertices[ face.c ] );
  4448. face.centroid.divideScalar( 3 );
  4449. } else if ( face instanceof THREE.Face4 ) {
  4450. face.centroid.add( this.vertices[ face.a ] );
  4451. face.centroid.add( this.vertices[ face.b ] );
  4452. face.centroid.add( this.vertices[ face.c ] );
  4453. face.centroid.add( this.vertices[ face.d ] );
  4454. face.centroid.divideScalar( 4 );
  4455. }
  4456. }
  4457. },
  4458. computeFaceNormals: function () {
  4459. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4460. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4461. var face = this.faces[ f ];
  4462. var vA = this.vertices[ face.a ];
  4463. var vB = this.vertices[ face.b ];
  4464. var vC = this.vertices[ face.c ];
  4465. cb.subVectors( vC, vB );
  4466. ab.subVectors( vA, vB );
  4467. cb.cross( ab );
  4468. cb.normalize();
  4469. face.normal.copy( cb );
  4470. }
  4471. },
  4472. computeVertexNormals: function ( areaWeighted ) {
  4473. var v, vl, f, fl, face, vertices;
  4474. // create internal buffers for reuse when calling this method repeatedly
  4475. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4476. if ( this.__tmpVertices === undefined ) {
  4477. this.__tmpVertices = new Array( this.vertices.length );
  4478. vertices = this.__tmpVertices;
  4479. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4480. vertices[ v ] = new THREE.Vector3();
  4481. }
  4482. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4483. face = this.faces[ f ];
  4484. if ( face instanceof THREE.Face3 ) {
  4485. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4486. } else if ( face instanceof THREE.Face4 ) {
  4487. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4488. }
  4489. }
  4490. } else {
  4491. vertices = this.__tmpVertices;
  4492. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4493. vertices[ v ].set( 0, 0, 0 );
  4494. }
  4495. }
  4496. if ( areaWeighted ) {
  4497. // vertex normals weighted by triangle areas
  4498. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4499. var vA, vB, vC, vD;
  4500. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4501. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4502. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4503. face = this.faces[ f ];
  4504. if ( face instanceof THREE.Face3 ) {
  4505. vA = this.vertices[ face.a ];
  4506. vB = this.vertices[ face.b ];
  4507. vC = this.vertices[ face.c ];
  4508. cb.subVectors( vC, vB );
  4509. ab.subVectors( vA, vB );
  4510. cb.cross( ab );
  4511. vertices[ face.a ].add( cb );
  4512. vertices[ face.b ].add( cb );
  4513. vertices[ face.c ].add( cb );
  4514. } else if ( face instanceof THREE.Face4 ) {
  4515. vA = this.vertices[ face.a ];
  4516. vB = this.vertices[ face.b ];
  4517. vC = this.vertices[ face.c ];
  4518. vD = this.vertices[ face.d ];
  4519. // abd
  4520. db.subVectors( vD, vB );
  4521. ab.subVectors( vA, vB );
  4522. db.cross( ab );
  4523. vertices[ face.a ].add( db );
  4524. vertices[ face.b ].add( db );
  4525. vertices[ face.d ].add( db );
  4526. // bcd
  4527. dc.subVectors( vD, vC );
  4528. bc.subVectors( vB, vC );
  4529. dc.cross( bc );
  4530. vertices[ face.b ].add( dc );
  4531. vertices[ face.c ].add( dc );
  4532. vertices[ face.d ].add( dc );
  4533. }
  4534. }
  4535. } else {
  4536. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4537. face = this.faces[ f ];
  4538. if ( face instanceof THREE.Face3 ) {
  4539. vertices[ face.a ].add( face.normal );
  4540. vertices[ face.b ].add( face.normal );
  4541. vertices[ face.c ].add( face.normal );
  4542. } else if ( face instanceof THREE.Face4 ) {
  4543. vertices[ face.a ].add( face.normal );
  4544. vertices[ face.b ].add( face.normal );
  4545. vertices[ face.c ].add( face.normal );
  4546. vertices[ face.d ].add( face.normal );
  4547. }
  4548. }
  4549. }
  4550. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4551. vertices[ v ].normalize();
  4552. }
  4553. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4554. face = this.faces[ f ];
  4555. if ( face instanceof THREE.Face3 ) {
  4556. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4557. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4558. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4559. } else if ( face instanceof THREE.Face4 ) {
  4560. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4561. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4562. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4563. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4564. }
  4565. }
  4566. },
  4567. computeMorphNormals: function () {
  4568. var i, il, f, fl, face;
  4569. // save original normals
  4570. // - create temp variables on first access
  4571. // otherwise just copy (for faster repeated calls)
  4572. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4573. face = this.faces[ f ];
  4574. if ( ! face.__originalFaceNormal ) {
  4575. face.__originalFaceNormal = face.normal.clone();
  4576. } else {
  4577. face.__originalFaceNormal.copy( face.normal );
  4578. }
  4579. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4580. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4581. if ( ! face.__originalVertexNormals[ i ] ) {
  4582. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4583. } else {
  4584. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4585. }
  4586. }
  4587. }
  4588. // use temp geometry to compute face and vertex normals for each morph
  4589. var tmpGeo = new THREE.Geometry();
  4590. tmpGeo.faces = this.faces;
  4591. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4592. // create on first access
  4593. if ( ! this.morphNormals[ i ] ) {
  4594. this.morphNormals[ i ] = {};
  4595. this.morphNormals[ i ].faceNormals = [];
  4596. this.morphNormals[ i ].vertexNormals = [];
  4597. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4598. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4599. var faceNormal, vertexNormals;
  4600. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4601. face = this.faces[ f ];
  4602. faceNormal = new THREE.Vector3();
  4603. if ( face instanceof THREE.Face3 ) {
  4604. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4605. } else {
  4606. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4607. }
  4608. dstNormalsFace.push( faceNormal );
  4609. dstNormalsVertex.push( vertexNormals );
  4610. }
  4611. }
  4612. var morphNormals = this.morphNormals[ i ];
  4613. // set vertices to morph target
  4614. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4615. // compute morph normals
  4616. tmpGeo.computeFaceNormals();
  4617. tmpGeo.computeVertexNormals();
  4618. // store morph normals
  4619. var faceNormal, vertexNormals;
  4620. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4621. face = this.faces[ f ];
  4622. faceNormal = morphNormals.faceNormals[ f ];
  4623. vertexNormals = morphNormals.vertexNormals[ f ];
  4624. faceNormal.copy( face.normal );
  4625. if ( face instanceof THREE.Face3 ) {
  4626. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4627. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4628. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4629. } else {
  4630. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4631. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4632. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4633. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4634. }
  4635. }
  4636. }
  4637. // restore original normals
  4638. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4639. face = this.faces[ f ];
  4640. face.normal = face.__originalFaceNormal;
  4641. face.vertexNormals = face.__originalVertexNormals;
  4642. }
  4643. },
  4644. computeTangents: function () {
  4645. // based on http://www.terathon.com/code/tangent.html
  4646. // tangents go to vertices
  4647. var f, fl, v, vl, i, il, vertexIndex,
  4648. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4649. x1, x2, y1, y2, z1, z2,
  4650. s1, s2, t1, t2, r, t, test,
  4651. tan1 = [], tan2 = [],
  4652. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4653. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4654. n = new THREE.Vector3(), w;
  4655. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4656. tan1[ v ] = new THREE.Vector3();
  4657. tan2[ v ] = new THREE.Vector3();
  4658. }
  4659. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4660. vA = context.vertices[ a ];
  4661. vB = context.vertices[ b ];
  4662. vC = context.vertices[ c ];
  4663. uvA = uv[ ua ];
  4664. uvB = uv[ ub ];
  4665. uvC = uv[ uc ];
  4666. x1 = vB.x - vA.x;
  4667. x2 = vC.x - vA.x;
  4668. y1 = vB.y - vA.y;
  4669. y2 = vC.y - vA.y;
  4670. z1 = vB.z - vA.z;
  4671. z2 = vC.z - vA.z;
  4672. s1 = uvB.x - uvA.x;
  4673. s2 = uvC.x - uvA.x;
  4674. t1 = uvB.y - uvA.y;
  4675. t2 = uvC.y - uvA.y;
  4676. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4677. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4678. ( t2 * y1 - t1 * y2 ) * r,
  4679. ( t2 * z1 - t1 * z2 ) * r );
  4680. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4681. ( s1 * y2 - s2 * y1 ) * r,
  4682. ( s1 * z2 - s2 * z1 ) * r );
  4683. tan1[ a ].add( sdir );
  4684. tan1[ b ].add( sdir );
  4685. tan1[ c ].add( sdir );
  4686. tan2[ a ].add( tdir );
  4687. tan2[ b ].add( tdir );
  4688. tan2[ c ].add( tdir );
  4689. }
  4690. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4691. face = this.faces[ f ];
  4692. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4693. if ( face instanceof THREE.Face3 ) {
  4694. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4695. } else if ( face instanceof THREE.Face4 ) {
  4696. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4697. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4698. }
  4699. }
  4700. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4701. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4702. face = this.faces[ f ];
  4703. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4704. n.copy( face.vertexNormals[ i ] );
  4705. vertexIndex = face[ faceIndex[ i ] ];
  4706. t = tan1[ vertexIndex ];
  4707. // Gram-Schmidt orthogonalize
  4708. tmp.copy( t );
  4709. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4710. // Calculate handedness
  4711. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4712. test = tmp2.dot( tan2[ vertexIndex ] );
  4713. w = (test < 0.0) ? -1.0 : 1.0;
  4714. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4715. }
  4716. }
  4717. this.hasTangents = true;
  4718. },
  4719. computeLineDistances: function ( ) {
  4720. var d = 0;
  4721. var vertices = this.vertices;
  4722. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4723. if ( i > 0 ) {
  4724. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4725. }
  4726. this.lineDistances[ i ] = d;
  4727. }
  4728. },
  4729. computeBoundingBox: function () {
  4730. if ( this.boundingBox === null ) {
  4731. this.boundingBox = new THREE.Box3();
  4732. }
  4733. this.boundingBox.setFromPoints( this.vertices );
  4734. },
  4735. computeBoundingSphere: function () {
  4736. if ( this.boundingSphere === null ) {
  4737. this.boundingSphere = new THREE.Sphere();
  4738. }
  4739. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4740. },
  4741. /*
  4742. * Checks for duplicate vertices with hashmap.
  4743. * Duplicated vertices are removed
  4744. * and faces' vertices are updated.
  4745. */
  4746. mergeVertices: function () {
  4747. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4748. var unique = [], changes = [];
  4749. var v, key;
  4750. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4751. var precision = Math.pow( 10, precisionPoints );
  4752. var i,il, face;
  4753. var indices, k, j, jl, u;
  4754. // reset cache of vertices as it now will be changing.
  4755. this.__tmpVertices = undefined;
  4756. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4757. v = this.vertices[ i ];
  4758. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4759. if ( verticesMap[ key ] === undefined ) {
  4760. verticesMap[ key ] = i;
  4761. unique.push( this.vertices[ i ] );
  4762. changes[ i ] = unique.length - 1;
  4763. } else {
  4764. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4765. changes[ i ] = changes[ verticesMap[ key ] ];
  4766. }
  4767. };
  4768. // if faces are completely degenerate after merging vertices, we
  4769. // have to remove them from the geometry.
  4770. var faceIndicesToRemove = [];
  4771. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4772. face = this.faces[ i ];
  4773. if ( face instanceof THREE.Face3 ) {
  4774. face.a = changes[ face.a ];
  4775. face.b = changes[ face.b ];
  4776. face.c = changes[ face.c ];
  4777. indices = [ face.a, face.b, face.c ];
  4778. var dupIndex = -1;
  4779. // if any duplicate vertices are found in a Face3
  4780. // we have to remove the face as nothing can be saved
  4781. for ( var n = 0; n < 3; n ++ ) {
  4782. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4783. dupIndex = n;
  4784. faceIndicesToRemove.push( i );
  4785. break;
  4786. }
  4787. }
  4788. } else if ( face instanceof THREE.Face4 ) {
  4789. face.a = changes[ face.a ];
  4790. face.b = changes[ face.b ];
  4791. face.c = changes[ face.c ];
  4792. face.d = changes[ face.d ];
  4793. // check dups in (a, b, c, d) and convert to -> face3
  4794. indices = [ face.a, face.b, face.c, face.d ];
  4795. var dupIndex = -1;
  4796. for ( var n = 0; n < 4; n ++ ) {
  4797. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4798. // if more than one duplicated vertex is found
  4799. // we can't generate any valid Face3's, thus
  4800. // we need to remove this face complete.
  4801. if ( dupIndex >= 0 ) {
  4802. faceIndicesToRemove.push( i );
  4803. }
  4804. dupIndex = n;
  4805. }
  4806. }
  4807. if ( dupIndex >= 0 ) {
  4808. indices.splice( dupIndex, 1 );
  4809. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4810. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4811. u = this.faceVertexUvs[ j ][ i ];
  4812. if ( u ) {
  4813. u.splice( dupIndex, 1 );
  4814. }
  4815. }
  4816. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4817. newFace.vertexNormals = face.vertexNormals;
  4818. newFace.vertexNormals.splice( dupIndex, 1 );
  4819. }
  4820. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4821. newFace.vertexColors = face.vertexColors;
  4822. newFace.vertexColors.splice( dupIndex, 1 );
  4823. }
  4824. this.faces[ i ] = newFace;
  4825. }
  4826. }
  4827. }
  4828. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4829. this.faces.splice( i, 1 );
  4830. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4831. this.faceVertexUvs[ j ].splice( i, 1 );
  4832. }
  4833. }
  4834. // Use unique set of vertices
  4835. var diff = this.vertices.length - unique.length;
  4836. this.vertices = unique;
  4837. return diff;
  4838. },
  4839. clone: function () {
  4840. var geometry = new THREE.Geometry();
  4841. var vertices = this.vertices;
  4842. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4843. geometry.vertices.push( vertices[ i ].clone() );
  4844. }
  4845. var faces = this.faces;
  4846. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4847. geometry.faces.push( faces[ i ].clone() );
  4848. }
  4849. var uvs = this.faceVertexUvs[ 0 ];
  4850. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4851. var uv = uvs[ i ], uvCopy = [];
  4852. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4853. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4854. }
  4855. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4856. }
  4857. return geometry;
  4858. },
  4859. dispose: function () {
  4860. this.dispatchEvent( { type: 'dispose' } );
  4861. }
  4862. };
  4863. THREE.extend( THREE.Geometry.prototype, THREE.EventDispatcher.prototype );
  4864. THREE.GeometryIdCount = 0;
  4865. /**
  4866. * @author alteredq / http://alteredqualia.com/
  4867. */
  4868. THREE.BufferGeometry = function () {
  4869. this.id = THREE.GeometryIdCount ++;
  4870. // attributes
  4871. this.attributes = {};
  4872. // attributes typed arrays are kept only if dynamic flag is set
  4873. this.dynamic = false;
  4874. // offsets for chunks when using indexed elements
  4875. this.offsets = [];
  4876. // boundings
  4877. this.boundingBox = null;
  4878. this.boundingSphere = null;
  4879. this.hasTangents = false;
  4880. // for compatibility
  4881. this.morphTargets = [];
  4882. };
  4883. THREE.BufferGeometry.prototype = {
  4884. constructor: THREE.BufferGeometry,
  4885. applyMatrix: function ( matrix ) {
  4886. var positionArray;
  4887. var normalArray;
  4888. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4889. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4890. if ( positionArray !== undefined ) {
  4891. matrix.multiplyVector3Array( positionArray );
  4892. this.verticesNeedUpdate = true;
  4893. }
  4894. if ( normalArray !== undefined ) {
  4895. var normalMatrix = new THREE.Matrix3();
  4896. normalMatrix.getInverse( matrix ).transpose();
  4897. normalMatrix.multiplyVector3Array( normalArray );
  4898. this.normalizeNormals();
  4899. this.normalsNeedUpdate = true;
  4900. }
  4901. },
  4902. computeBoundingBox: function () {
  4903. if ( this.boundingBox === null ) {
  4904. this.boundingBox = new THREE.Box3();
  4905. }
  4906. var positions = this.attributes[ "position" ].array;
  4907. if ( positions ) {
  4908. var bb = this.boundingBox;
  4909. var x, y, z;
  4910. if( positions.length >= 3 ) {
  4911. bb.min.x = bb.max.x = positions[ 0 ];
  4912. bb.min.y = bb.max.y = positions[ 1 ];
  4913. bb.min.z = bb.max.z = positions[ 2 ];
  4914. }
  4915. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4916. x = positions[ i ];
  4917. y = positions[ i + 1 ];
  4918. z = positions[ i + 2 ];
  4919. // bounding box
  4920. if ( x < bb.min.x ) {
  4921. bb.min.x = x;
  4922. } else if ( x > bb.max.x ) {
  4923. bb.max.x = x;
  4924. }
  4925. if ( y < bb.min.y ) {
  4926. bb.min.y = y;
  4927. } else if ( y > bb.max.y ) {
  4928. bb.max.y = y;
  4929. }
  4930. if ( z < bb.min.z ) {
  4931. bb.min.z = z;
  4932. } else if ( z > bb.max.z ) {
  4933. bb.max.z = z;
  4934. }
  4935. }
  4936. }
  4937. if ( positions === undefined || positions.length === 0 ) {
  4938. this.boundingBox.min.set( 0, 0, 0 );
  4939. this.boundingBox.max.set( 0, 0, 0 );
  4940. }
  4941. },
  4942. computeBoundingSphere: function () {
  4943. if ( this.boundingSphere === null ) {
  4944. this.boundingSphere = new THREE.Sphere();
  4945. }
  4946. var positions = this.attributes[ "position" ].array;
  4947. if ( positions ) {
  4948. var radiusSq, maxRadiusSq = 0;
  4949. var x, y, z;
  4950. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4951. x = positions[ i ];
  4952. y = positions[ i + 1 ];
  4953. z = positions[ i + 2 ];
  4954. radiusSq = x * x + y * y + z * z;
  4955. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4956. }
  4957. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4958. }
  4959. },
  4960. computeVertexNormals: function () {
  4961. if ( this.attributes[ "position" ] ) {
  4962. var i, il;
  4963. var j, jl;
  4964. var nVertexElements = this.attributes[ "position" ].array.length;
  4965. if ( this.attributes[ "normal" ] === undefined ) {
  4966. this.attributes[ "normal" ] = {
  4967. itemSize: 3,
  4968. array: new Float32Array( nVertexElements ),
  4969. numItems: nVertexElements
  4970. };
  4971. } else {
  4972. // reset existing normals to zero
  4973. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4974. this.attributes[ "normal" ].array[ i ] = 0;
  4975. }
  4976. }
  4977. var positions = this.attributes[ "position" ].array;
  4978. var normals = this.attributes[ "normal" ].array;
  4979. var vA, vB, vC, x, y, z,
  4980. pA = new THREE.Vector3(),
  4981. pB = new THREE.Vector3(),
  4982. pC = new THREE.Vector3(),
  4983. cb = new THREE.Vector3(),
  4984. ab = new THREE.Vector3();
  4985. // indexed elements
  4986. if ( this.attributes[ "index" ] ) {
  4987. var indices = this.attributes[ "index" ].array;
  4988. var offsets = this.offsets;
  4989. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4990. var start = offsets[ j ].start;
  4991. var count = offsets[ j ].count;
  4992. var index = offsets[ j ].index;
  4993. for ( i = start, il = start + count; i < il; i += 3 ) {
  4994. vA = index + indices[ i ];
  4995. vB = index + indices[ i + 1 ];
  4996. vC = index + indices[ i + 2 ];
  4997. x = positions[ vA * 3 ];
  4998. y = positions[ vA * 3 + 1 ];
  4999. z = positions[ vA * 3 + 2 ];
  5000. pA.set( x, y, z );
  5001. x = positions[ vB * 3 ];
  5002. y = positions[ vB * 3 + 1 ];
  5003. z = positions[ vB * 3 + 2 ];
  5004. pB.set( x, y, z );
  5005. x = positions[ vC * 3 ];
  5006. y = positions[ vC * 3 + 1 ];
  5007. z = positions[ vC * 3 + 2 ];
  5008. pC.set( x, y, z );
  5009. cb.subVectors( pC, pB );
  5010. ab.subVectors( pA, pB );
  5011. cb.cross( ab );
  5012. normals[ vA * 3 ] += cb.x;
  5013. normals[ vA * 3 + 1 ] += cb.y;
  5014. normals[ vA * 3 + 2 ] += cb.z;
  5015. normals[ vB * 3 ] += cb.x;
  5016. normals[ vB * 3 + 1 ] += cb.y;
  5017. normals[ vB * 3 + 2 ] += cb.z;
  5018. normals[ vC * 3 ] += cb.x;
  5019. normals[ vC * 3 + 1 ] += cb.y;
  5020. normals[ vC * 3 + 2 ] += cb.z;
  5021. }
  5022. }
  5023. // non-indexed elements (unconnected triangle soup)
  5024. } else {
  5025. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5026. x = positions[ i ];
  5027. y = positions[ i + 1 ];
  5028. z = positions[ i + 2 ];
  5029. pA.set( x, y, z );
  5030. x = positions[ i + 3 ];
  5031. y = positions[ i + 4 ];
  5032. z = positions[ i + 5 ];
  5033. pB.set( x, y, z );
  5034. x = positions[ i + 6 ];
  5035. y = positions[ i + 7 ];
  5036. z = positions[ i + 8 ];
  5037. pC.set( x, y, z );
  5038. cb.subVectors( pC, pB );
  5039. ab.subVectors( pA, pB );
  5040. cb.cross( ab );
  5041. normals[ i ] = cb.x;
  5042. normals[ i + 1 ] = cb.y;
  5043. normals[ i + 2 ] = cb.z;
  5044. normals[ i + 3 ] = cb.x;
  5045. normals[ i + 4 ] = cb.y;
  5046. normals[ i + 5 ] = cb.z;
  5047. normals[ i + 6 ] = cb.x;
  5048. normals[ i + 7 ] = cb.y;
  5049. normals[ i + 8 ] = cb.z;
  5050. }
  5051. }
  5052. this.normalizeNormals();
  5053. this.normalsNeedUpdate = true;
  5054. }
  5055. },
  5056. normalizeNormals: function () {
  5057. var normals = this.attributes[ "normal" ].array;
  5058. var x, y, z, n;
  5059. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5060. x = normals[ i ];
  5061. y = normals[ i + 1 ];
  5062. z = normals[ i + 2 ];
  5063. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5064. normals[ i ] *= n;
  5065. normals[ i + 1 ] *= n;
  5066. normals[ i + 2 ] *= n;
  5067. }
  5068. },
  5069. computeTangents: function () {
  5070. // based on http://www.terathon.com/code/tangent.html
  5071. // (per vertex tangents)
  5072. if ( this.attributes[ "index" ] === undefined ||
  5073. this.attributes[ "position" ] === undefined ||
  5074. this.attributes[ "normal" ] === undefined ||
  5075. this.attributes[ "uv" ] === undefined ) {
  5076. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5077. return;
  5078. }
  5079. var indices = this.attributes[ "index" ].array;
  5080. var positions = this.attributes[ "position" ].array;
  5081. var normals = this.attributes[ "normal" ].array;
  5082. var uvs = this.attributes[ "uv" ].array;
  5083. var nVertices = positions.length / 3;
  5084. if ( this.attributes[ "tangent" ] === undefined ) {
  5085. var nTangentElements = 4 * nVertices;
  5086. this.attributes[ "tangent" ] = {
  5087. itemSize: 4,
  5088. array: new Float32Array( nTangentElements ),
  5089. numItems: nTangentElements
  5090. };
  5091. }
  5092. var tangents = this.attributes[ "tangent" ].array;
  5093. var tan1 = [], tan2 = [];
  5094. for ( var k = 0; k < nVertices; k ++ ) {
  5095. tan1[ k ] = new THREE.Vector3();
  5096. tan2[ k ] = new THREE.Vector3();
  5097. }
  5098. var xA, yA, zA,
  5099. xB, yB, zB,
  5100. xC, yC, zC,
  5101. uA, vA,
  5102. uB, vB,
  5103. uC, vC,
  5104. x1, x2, y1, y2, z1, z2,
  5105. s1, s2, t1, t2, r;
  5106. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5107. function handleTriangle( a, b, c ) {
  5108. xA = positions[ a * 3 ];
  5109. yA = positions[ a * 3 + 1 ];
  5110. zA = positions[ a * 3 + 2 ];
  5111. xB = positions[ b * 3 ];
  5112. yB = positions[ b * 3 + 1 ];
  5113. zB = positions[ b * 3 + 2 ];
  5114. xC = positions[ c * 3 ];
  5115. yC = positions[ c * 3 + 1 ];
  5116. zC = positions[ c * 3 + 2 ];
  5117. uA = uvs[ a * 2 ];
  5118. vA = uvs[ a * 2 + 1 ];
  5119. uB = uvs[ b * 2 ];
  5120. vB = uvs[ b * 2 + 1 ];
  5121. uC = uvs[ c * 2 ];
  5122. vC = uvs[ c * 2 + 1 ];
  5123. x1 = xB - xA;
  5124. x2 = xC - xA;
  5125. y1 = yB - yA;
  5126. y2 = yC - yA;
  5127. z1 = zB - zA;
  5128. z2 = zC - zA;
  5129. s1 = uB - uA;
  5130. s2 = uC - uA;
  5131. t1 = vB - vA;
  5132. t2 = vC - vA;
  5133. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5134. sdir.set(
  5135. ( t2 * x1 - t1 * x2 ) * r,
  5136. ( t2 * y1 - t1 * y2 ) * r,
  5137. ( t2 * z1 - t1 * z2 ) * r
  5138. );
  5139. tdir.set(
  5140. ( s1 * x2 - s2 * x1 ) * r,
  5141. ( s1 * y2 - s2 * y1 ) * r,
  5142. ( s1 * z2 - s2 * z1 ) * r
  5143. );
  5144. tan1[ a ].add( sdir );
  5145. tan1[ b ].add( sdir );
  5146. tan1[ c ].add( sdir );
  5147. tan2[ a ].add( tdir );
  5148. tan2[ b ].add( tdir );
  5149. tan2[ c ].add( tdir );
  5150. }
  5151. var i, il;
  5152. var j, jl;
  5153. var iA, iB, iC;
  5154. var offsets = this.offsets;
  5155. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5156. var start = offsets[ j ].start;
  5157. var count = offsets[ j ].count;
  5158. var index = offsets[ j ].index;
  5159. for ( i = start, il = start + count; i < il; i += 3 ) {
  5160. iA = index + indices[ i ];
  5161. iB = index + indices[ i + 1 ];
  5162. iC = index + indices[ i + 2 ];
  5163. handleTriangle( iA, iB, iC );
  5164. }
  5165. }
  5166. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5167. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5168. var w, t, test;
  5169. function handleVertex( v ) {
  5170. n.x = normals[ v * 3 ];
  5171. n.y = normals[ v * 3 + 1 ];
  5172. n.z = normals[ v * 3 + 2 ];
  5173. n2.copy( n );
  5174. t = tan1[ v ];
  5175. // Gram-Schmidt orthogonalize
  5176. tmp.copy( t );
  5177. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5178. // Calculate handedness
  5179. tmp2.crossVectors( n2, t );
  5180. test = tmp2.dot( tan2[ v ] );
  5181. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5182. tangents[ v * 4 ] = tmp.x;
  5183. tangents[ v * 4 + 1 ] = tmp.y;
  5184. tangents[ v * 4 + 2 ] = tmp.z;
  5185. tangents[ v * 4 + 3 ] = w;
  5186. }
  5187. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5188. var start = offsets[ j ].start;
  5189. var count = offsets[ j ].count;
  5190. var index = offsets[ j ].index;
  5191. for ( i = start, il = start + count; i < il; i += 3 ) {
  5192. iA = index + indices[ i ];
  5193. iB = index + indices[ i + 1 ];
  5194. iC = index + indices[ i + 2 ];
  5195. handleVertex( iA );
  5196. handleVertex( iB );
  5197. handleVertex( iC );
  5198. }
  5199. }
  5200. this.hasTangents = true;
  5201. this.tangentsNeedUpdate = true;
  5202. },
  5203. dispose: function () {
  5204. this.dispatchEvent( { type: 'dispose' } );
  5205. }
  5206. };
  5207. THREE.extend( THREE.BufferGeometry.prototype, THREE.EventDispatcher.prototype );
  5208. /**
  5209. * @author mrdoob / http://mrdoob.com/
  5210. * @author mikael emtinger / http://gomo.se/
  5211. * @author WestLangley / http://github.com/WestLangley
  5212. */
  5213. THREE.Camera = function () {
  5214. THREE.Object3D.call( this );
  5215. this.matrixWorldInverse = new THREE.Matrix4();
  5216. this.projectionMatrix = new THREE.Matrix4();
  5217. this.projectionMatrixInverse = new THREE.Matrix4();
  5218. };
  5219. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5220. THREE.Camera.prototype.lookAt = function () {
  5221. // This routine does not support cameras with rotated and/or translated parent(s)
  5222. var m1 = new THREE.Matrix4();
  5223. return function ( vector ) {
  5224. m1.lookAt( this.position, vector, this.up );
  5225. if ( this.useQuaternion === true ) {
  5226. this.quaternion.setFromRotationMatrix( m1 );
  5227. } else {
  5228. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5229. }
  5230. };
  5231. }();
  5232. /**
  5233. * @author alteredq / http://alteredqualia.com/
  5234. */
  5235. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5236. THREE.Camera.call( this );
  5237. this.left = left;
  5238. this.right = right;
  5239. this.top = top;
  5240. this.bottom = bottom;
  5241. this.near = ( near !== undefined ) ? near : 0.1;
  5242. this.far = ( far !== undefined ) ? far : 2000;
  5243. this.updateProjectionMatrix();
  5244. };
  5245. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5246. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5247. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5248. };
  5249. /**
  5250. * @author mrdoob / http://mrdoob.com/
  5251. * @author greggman / http://games.greggman.com/
  5252. * @author zz85 / http://www.lab4games.net/zz85/blog
  5253. */
  5254. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5255. THREE.Camera.call( this );
  5256. this.fov = fov !== undefined ? fov : 50;
  5257. this.aspect = aspect !== undefined ? aspect : 1;
  5258. this.near = near !== undefined ? near : 0.1;
  5259. this.far = far !== undefined ? far : 2000;
  5260. this.updateProjectionMatrix();
  5261. };
  5262. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5263. /**
  5264. * Uses Focal Length (in mm) to estimate and set FOV
  5265. * 35mm (fullframe) camera is used if frame size is not specified;
  5266. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5267. */
  5268. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5269. if ( frameHeight === undefined ) frameHeight = 24;
  5270. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5271. this.updateProjectionMatrix();
  5272. }
  5273. /**
  5274. * Sets an offset in a larger frustum. This is useful for multi-window or
  5275. * multi-monitor/multi-machine setups.
  5276. *
  5277. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5278. * the monitors are in grid like this
  5279. *
  5280. * +---+---+---+
  5281. * | A | B | C |
  5282. * +---+---+---+
  5283. * | D | E | F |
  5284. * +---+---+---+
  5285. *
  5286. * then for each monitor you would call it like this
  5287. *
  5288. * var w = 1920;
  5289. * var h = 1080;
  5290. * var fullWidth = w * 3;
  5291. * var fullHeight = h * 2;
  5292. *
  5293. * --A--
  5294. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5295. * --B--
  5296. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5297. * --C--
  5298. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5299. * --D--
  5300. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5301. * --E--
  5302. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5303. * --F--
  5304. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5305. *
  5306. * Note there is no reason monitors have to be the same size or in a grid.
  5307. */
  5308. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5309. this.fullWidth = fullWidth;
  5310. this.fullHeight = fullHeight;
  5311. this.x = x;
  5312. this.y = y;
  5313. this.width = width;
  5314. this.height = height;
  5315. this.updateProjectionMatrix();
  5316. };
  5317. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5318. if ( this.fullWidth ) {
  5319. var aspect = this.fullWidth / this.fullHeight;
  5320. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5321. var bottom = -top;
  5322. var left = aspect * bottom;
  5323. var right = aspect * top;
  5324. var width = Math.abs( right - left );
  5325. var height = Math.abs( top - bottom );
  5326. this.projectionMatrix.makeFrustum(
  5327. left + this.x * width / this.fullWidth,
  5328. left + ( this.x + this.width ) * width / this.fullWidth,
  5329. top - ( this.y + this.height ) * height / this.fullHeight,
  5330. top - this.y * height / this.fullHeight,
  5331. this.near,
  5332. this.far
  5333. );
  5334. } else {
  5335. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5336. }
  5337. };
  5338. /**
  5339. * @author mrdoob / http://mrdoob.com/
  5340. * @author alteredq / http://alteredqualia.com/
  5341. */
  5342. THREE.Light = function ( hex ) {
  5343. THREE.Object3D.call( this );
  5344. this.color = new THREE.Color( hex );
  5345. };
  5346. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5347. THREE.Light.prototype.clone = function ( light ) {
  5348. if ( light === undefined ) light = new THREE.Light();
  5349. THREE.Object3D.prototype.clone.call( this, light );
  5350. light.color.copy( this.color );
  5351. return light;
  5352. };
  5353. /**
  5354. * @author mrdoob / http://mrdoob.com/
  5355. */
  5356. THREE.AmbientLight = function ( hex ) {
  5357. THREE.Light.call( this, hex );
  5358. };
  5359. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5360. THREE.AmbientLight.prototype.clone = function () {
  5361. var light = new THREE.AmbientLight();
  5362. THREE.Light.prototype.clone.call( this, light );
  5363. return light;
  5364. };
  5365. /**
  5366. * @author MPanknin / http://www.redplant.de/
  5367. * @author alteredq / http://alteredqualia.com/
  5368. */
  5369. THREE.AreaLight = function ( hex, intensity ) {
  5370. THREE.Light.call( this, hex );
  5371. this.normal = new THREE.Vector3( 0, -1, 0 );
  5372. this.right = new THREE.Vector3( 1, 0, 0 );
  5373. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5374. this.width = 1.0;
  5375. this.height = 1.0;
  5376. this.constantAttenuation = 1.5;
  5377. this.linearAttenuation = 0.5;
  5378. this.quadraticAttenuation = 0.1;
  5379. };
  5380. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5381. /**
  5382. * @author mrdoob / http://mrdoob.com/
  5383. * @author alteredq / http://alteredqualia.com/
  5384. */
  5385. THREE.DirectionalLight = function ( hex, intensity ) {
  5386. THREE.Light.call( this, hex );
  5387. this.position.set( 0, 1, 0 );
  5388. this.target = new THREE.Object3D();
  5389. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5390. this.castShadow = false;
  5391. this.onlyShadow = false;
  5392. //
  5393. this.shadowCameraNear = 50;
  5394. this.shadowCameraFar = 5000;
  5395. this.shadowCameraLeft = -500;
  5396. this.shadowCameraRight = 500;
  5397. this.shadowCameraTop = 500;
  5398. this.shadowCameraBottom = -500;
  5399. this.shadowCameraVisible = false;
  5400. this.shadowBias = 0;
  5401. this.shadowDarkness = 0.5;
  5402. this.shadowMapWidth = 512;
  5403. this.shadowMapHeight = 512;
  5404. //
  5405. this.shadowCascade = false;
  5406. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5407. this.shadowCascadeCount = 2;
  5408. this.shadowCascadeBias = [ 0, 0, 0 ];
  5409. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5410. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5411. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5412. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5413. this.shadowCascadeArray = [];
  5414. //
  5415. this.shadowMap = null;
  5416. this.shadowMapSize = null;
  5417. this.shadowCamera = null;
  5418. this.shadowMatrix = null;
  5419. };
  5420. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5421. THREE.DirectionalLight.prototype.clone = function () {
  5422. var light = new THREE.DirectionalLight();
  5423. THREE.Light.prototype.clone.call( this, light );
  5424. light.target = this.target.clone();
  5425. light.intensity = this.intensity;
  5426. light.castShadow = this.castShadow;
  5427. light.onlyShadow = this.onlyShadow;
  5428. return light;
  5429. };
  5430. /**
  5431. * @author alteredq / http://alteredqualia.com/
  5432. */
  5433. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5434. THREE.Light.call( this, skyColorHex );
  5435. this.position.set( 0, 100, 0 );
  5436. this.groundColor = new THREE.Color( groundColorHex );
  5437. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5438. };
  5439. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5440. THREE.HemisphereLight.prototype.clone = function () {
  5441. var light = new THREE.PointLight();
  5442. THREE.Light.prototype.clone.call( this, light );
  5443. light.groundColor.copy( this.groundColor );
  5444. light.intensity = this.intensity;
  5445. return light;
  5446. };
  5447. /**
  5448. * @author mrdoob / http://mrdoob.com/
  5449. */
  5450. THREE.PointLight = function ( hex, intensity, distance ) {
  5451. THREE.Light.call( this, hex );
  5452. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5453. this.distance = ( distance !== undefined ) ? distance : 0;
  5454. };
  5455. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5456. THREE.PointLight.prototype.clone = function () {
  5457. var light = new THREE.PointLight();
  5458. THREE.Light.prototype.clone.call( this, light );
  5459. light.intensity = this.intensity;
  5460. light.distance = this.distance;
  5461. return light;
  5462. };
  5463. /**
  5464. * @author alteredq / http://alteredqualia.com/
  5465. */
  5466. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5467. THREE.Light.call( this, hex );
  5468. this.position.set( 0, 1, 0 );
  5469. this.target = new THREE.Object3D();
  5470. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5471. this.distance = ( distance !== undefined ) ? distance : 0;
  5472. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5473. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5474. this.castShadow = false;
  5475. this.onlyShadow = false;
  5476. //
  5477. this.shadowCameraNear = 50;
  5478. this.shadowCameraFar = 5000;
  5479. this.shadowCameraFov = 50;
  5480. this.shadowCameraVisible = false;
  5481. this.shadowBias = 0;
  5482. this.shadowDarkness = 0.5;
  5483. this.shadowMapWidth = 512;
  5484. this.shadowMapHeight = 512;
  5485. //
  5486. this.shadowMap = null;
  5487. this.shadowMapSize = null;
  5488. this.shadowCamera = null;
  5489. this.shadowMatrix = null;
  5490. };
  5491. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5492. THREE.SpotLight.prototype.clone = function () {
  5493. var light = new THREE.SpotLight();
  5494. THREE.Light.prototype.clone.call( this, light );
  5495. light.target = this.target.clone();
  5496. light.intensity = this.intensity;
  5497. light.distance = this.distance;
  5498. light.angle = this.angle;
  5499. light.exponent = this.exponent;
  5500. light.castShadow = this.castShadow;
  5501. light.onlyShadow = this.onlyShadow;
  5502. return light;
  5503. };
  5504. /**
  5505. * @author alteredq / http://alteredqualia.com/
  5506. */
  5507. THREE.Loader = function ( showStatus ) {
  5508. this.showStatus = showStatus;
  5509. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5510. this.onLoadStart = function () {};
  5511. this.onLoadProgress = function () {};
  5512. this.onLoadComplete = function () {};
  5513. };
  5514. THREE.Loader.prototype = {
  5515. constructor: THREE.Loader,
  5516. crossOrigin: 'anonymous',
  5517. addStatusElement: function () {
  5518. var e = document.createElement( "div" );
  5519. e.style.position = "absolute";
  5520. e.style.right = "0px";
  5521. e.style.top = "0px";
  5522. e.style.fontSize = "0.8em";
  5523. e.style.textAlign = "left";
  5524. e.style.background = "rgba(0,0,0,0.25)";
  5525. e.style.color = "#fff";
  5526. e.style.width = "120px";
  5527. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5528. e.style.zIndex = 1000;
  5529. e.innerHTML = "Loading ...";
  5530. return e;
  5531. },
  5532. updateProgress: function ( progress ) {
  5533. var message = "Loaded ";
  5534. if ( progress.total ) {
  5535. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5536. } else {
  5537. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5538. }
  5539. this.statusDomElement.innerHTML = message;
  5540. },
  5541. extractUrlBase: function ( url ) {
  5542. var parts = url.split( '/' );
  5543. parts.pop();
  5544. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5545. },
  5546. initMaterials: function ( materials, texturePath ) {
  5547. var array = [];
  5548. for ( var i = 0; i < materials.length; ++ i ) {
  5549. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5550. }
  5551. return array;
  5552. },
  5553. needsTangents: function ( materials ) {
  5554. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5555. var m = materials[ i ];
  5556. if ( m instanceof THREE.ShaderMaterial ) return true;
  5557. }
  5558. return false;
  5559. },
  5560. createMaterial: function ( m, texturePath ) {
  5561. var _this = this;
  5562. function is_pow2( n ) {
  5563. var l = Math.log( n ) / Math.LN2;
  5564. return Math.floor( l ) == l;
  5565. }
  5566. function nearest_pow2( n ) {
  5567. var l = Math.log( n ) / Math.LN2;
  5568. return Math.pow( 2, Math.round( l ) );
  5569. }
  5570. function load_image( where, url ) {
  5571. var image = new Image();
  5572. image.onload = function () {
  5573. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5574. var width = nearest_pow2( this.width );
  5575. var height = nearest_pow2( this.height );
  5576. where.image.width = width;
  5577. where.image.height = height;
  5578. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5579. } else {
  5580. where.image = this;
  5581. }
  5582. where.needsUpdate = true;
  5583. };
  5584. image.crossOrigin = _this.crossOrigin;
  5585. image.src = url;
  5586. }
  5587. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5588. var isCompressed = /\.dds$/i.test( sourceFile );
  5589. var fullPath = texturePath + "/" + sourceFile;
  5590. if ( isCompressed ) {
  5591. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5592. where[ name ] = texture;
  5593. } else {
  5594. var texture = document.createElement( 'canvas' );
  5595. where[ name ] = new THREE.Texture( texture );
  5596. }
  5597. where[ name ].sourceFile = sourceFile;
  5598. if( repeat ) {
  5599. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5600. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5601. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5602. }
  5603. if ( offset ) {
  5604. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5605. }
  5606. if ( wrap ) {
  5607. var wrapMap = {
  5608. "repeat": THREE.RepeatWrapping,
  5609. "mirror": THREE.MirroredRepeatWrapping
  5610. }
  5611. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5612. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5613. }
  5614. if ( anisotropy ) {
  5615. where[ name ].anisotropy = anisotropy;
  5616. }
  5617. if ( ! isCompressed ) {
  5618. load_image( where[ name ], fullPath );
  5619. }
  5620. }
  5621. function rgb2hex( rgb ) {
  5622. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5623. }
  5624. // defaults
  5625. var mtype = "MeshLambertMaterial";
  5626. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5627. // parameters from model file
  5628. if ( m.shading ) {
  5629. var shading = m.shading.toLowerCase();
  5630. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5631. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5632. }
  5633. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5634. mpars.blending = THREE[ m.blending ];
  5635. }
  5636. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5637. mpars.transparent = m.transparent;
  5638. }
  5639. if ( m.depthTest !== undefined ) {
  5640. mpars.depthTest = m.depthTest;
  5641. }
  5642. if ( m.depthWrite !== undefined ) {
  5643. mpars.depthWrite = m.depthWrite;
  5644. }
  5645. if ( m.visible !== undefined ) {
  5646. mpars.visible = m.visible;
  5647. }
  5648. if ( m.flipSided !== undefined ) {
  5649. mpars.side = THREE.BackSide;
  5650. }
  5651. if ( m.doubleSided !== undefined ) {
  5652. mpars.side = THREE.DoubleSide;
  5653. }
  5654. if ( m.wireframe !== undefined ) {
  5655. mpars.wireframe = m.wireframe;
  5656. }
  5657. if ( m.vertexColors !== undefined ) {
  5658. if ( m.vertexColors === "face" ) {
  5659. mpars.vertexColors = THREE.FaceColors;
  5660. } else if ( m.vertexColors ) {
  5661. mpars.vertexColors = THREE.VertexColors;
  5662. }
  5663. }
  5664. // colors
  5665. if ( m.colorDiffuse ) {
  5666. mpars.color = rgb2hex( m.colorDiffuse );
  5667. } else if ( m.DbgColor ) {
  5668. mpars.color = m.DbgColor;
  5669. }
  5670. if ( m.colorSpecular ) {
  5671. mpars.specular = rgb2hex( m.colorSpecular );
  5672. }
  5673. if ( m.colorAmbient ) {
  5674. mpars.ambient = rgb2hex( m.colorAmbient );
  5675. }
  5676. // modifiers
  5677. if ( m.transparency ) {
  5678. mpars.opacity = m.transparency;
  5679. }
  5680. if ( m.specularCoef ) {
  5681. mpars.shininess = m.specularCoef;
  5682. }
  5683. // textures
  5684. if ( m.mapDiffuse && texturePath ) {
  5685. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5686. }
  5687. if ( m.mapLight && texturePath ) {
  5688. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5689. }
  5690. if ( m.mapBump && texturePath ) {
  5691. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5692. }
  5693. if ( m.mapNormal && texturePath ) {
  5694. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5695. }
  5696. if ( m.mapSpecular && texturePath ) {
  5697. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5698. }
  5699. //
  5700. if ( m.mapBumpScale ) {
  5701. mpars.bumpScale = m.mapBumpScale;
  5702. }
  5703. // special case for normal mapped material
  5704. if ( m.mapNormal ) {
  5705. var shader = THREE.ShaderLib[ "normalmap" ];
  5706. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5707. uniforms[ "tNormal" ].value = mpars.normalMap;
  5708. if ( m.mapNormalFactor ) {
  5709. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5710. }
  5711. if ( mpars.map ) {
  5712. uniforms[ "tDiffuse" ].value = mpars.map;
  5713. uniforms[ "enableDiffuse" ].value = true;
  5714. }
  5715. if ( mpars.specularMap ) {
  5716. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5717. uniforms[ "enableSpecular" ].value = true;
  5718. }
  5719. if ( mpars.lightMap ) {
  5720. uniforms[ "tAO" ].value = mpars.lightMap;
  5721. uniforms[ "enableAO" ].value = true;
  5722. }
  5723. // for the moment don't handle displacement texture
  5724. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5725. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5726. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5727. uniforms[ "uShininess" ].value = mpars.shininess;
  5728. if ( mpars.opacity !== undefined ) {
  5729. uniforms[ "uOpacity" ].value = mpars.opacity;
  5730. }
  5731. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5732. var material = new THREE.ShaderMaterial( parameters );
  5733. if ( mpars.transparent ) {
  5734. material.transparent = true;
  5735. }
  5736. } else {
  5737. var material = new THREE[ mtype ]( mpars );
  5738. }
  5739. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5740. return material;
  5741. }
  5742. };
  5743. /**
  5744. * @author mrdoob / http://mrdoob.com/
  5745. */
  5746. THREE.ImageLoader = function () {
  5747. this.crossOrigin = null;
  5748. };
  5749. THREE.ImageLoader.prototype.load = function ( url, image ) {
  5750. var scope = this;
  5751. if ( image === undefined ) image = new Image();
  5752. image.addEventListener( 'load', function () {
  5753. scope.dispatchEvent( { type: 'load', content: image } );
  5754. }, false );
  5755. image.addEventListener( 'error', function () {
  5756. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5757. }, false );
  5758. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5759. image.src = url;
  5760. };
  5761. THREE.extend( THREE.ImageLoader.prototype, THREE.EventDispatcher.prototype );
  5762. /**
  5763. * @author mrdoob / http://mrdoob.com/
  5764. * @author alteredq / http://alteredqualia.com/
  5765. */
  5766. THREE.JSONLoader = function ( showStatus ) {
  5767. THREE.Loader.call( this, showStatus );
  5768. this.withCredentials = false;
  5769. };
  5770. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5771. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5772. var scope = this;
  5773. // todo: unify load API to for easier SceneLoader use
  5774. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5775. this.onLoadStart();
  5776. this.loadAjaxJSON( this, url, callback, texturePath );
  5777. };
  5778. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5779. var xhr = new XMLHttpRequest();
  5780. var length = 0;
  5781. xhr.onreadystatechange = function () {
  5782. if ( xhr.readyState === xhr.DONE ) {
  5783. if ( xhr.status === 200 || xhr.status === 0 ) {
  5784. if ( xhr.responseText ) {
  5785. var json = JSON.parse( xhr.responseText );
  5786. var result = context.parse( json, texturePath );
  5787. callback( result.geometry, result.materials );
  5788. } else {
  5789. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5790. }
  5791. // in context of more complex asset initialization
  5792. // do not block on single failed file
  5793. // maybe should go even one more level up
  5794. context.onLoadComplete();
  5795. } else {
  5796. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5797. }
  5798. } else if ( xhr.readyState === xhr.LOADING ) {
  5799. if ( callbackProgress ) {
  5800. if ( length === 0 ) {
  5801. length = xhr.getResponseHeader( "Content-Length" );
  5802. }
  5803. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5804. }
  5805. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5806. length = xhr.getResponseHeader( "Content-Length" );
  5807. }
  5808. };
  5809. xhr.open( "GET", url, true );
  5810. xhr.withCredentials = this.withCredentials;
  5811. xhr.send( null );
  5812. };
  5813. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  5814. var scope = this,
  5815. geometry = new THREE.Geometry(),
  5816. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5817. parseModel( scale );
  5818. parseSkin();
  5819. parseMorphing( scale );
  5820. geometry.computeCentroids();
  5821. geometry.computeFaceNormals();
  5822. function parseModel( scale ) {
  5823. function isBitSet( value, position ) {
  5824. return value & ( 1 << position );
  5825. }
  5826. var i, j, fi,
  5827. offset, zLength, nVertices,
  5828. colorIndex, normalIndex, uvIndex, materialIndex,
  5829. type,
  5830. isQuad,
  5831. hasMaterial,
  5832. hasFaceUv, hasFaceVertexUv,
  5833. hasFaceNormal, hasFaceVertexNormal,
  5834. hasFaceColor, hasFaceVertexColor,
  5835. vertex, face, color, normal,
  5836. uvLayer, uvs, u, v,
  5837. faces = json.faces,
  5838. vertices = json.vertices,
  5839. normals = json.normals,
  5840. colors = json.colors,
  5841. nUvLayers = 0;
  5842. // disregard empty arrays
  5843. for ( i = 0; i < json.uvs.length; i++ ) {
  5844. if ( json.uvs[ i ].length ) nUvLayers ++;
  5845. }
  5846. for ( i = 0; i < nUvLayers; i++ ) {
  5847. geometry.faceUvs[ i ] = [];
  5848. geometry.faceVertexUvs[ i ] = [];
  5849. }
  5850. offset = 0;
  5851. zLength = vertices.length;
  5852. while ( offset < zLength ) {
  5853. vertex = new THREE.Vector3();
  5854. vertex.x = vertices[ offset ++ ] * scale;
  5855. vertex.y = vertices[ offset ++ ] * scale;
  5856. vertex.z = vertices[ offset ++ ] * scale;
  5857. geometry.vertices.push( vertex );
  5858. }
  5859. offset = 0;
  5860. zLength = faces.length;
  5861. while ( offset < zLength ) {
  5862. type = faces[ offset ++ ];
  5863. isQuad = isBitSet( type, 0 );
  5864. hasMaterial = isBitSet( type, 1 );
  5865. hasFaceUv = isBitSet( type, 2 );
  5866. hasFaceVertexUv = isBitSet( type, 3 );
  5867. hasFaceNormal = isBitSet( type, 4 );
  5868. hasFaceVertexNormal = isBitSet( type, 5 );
  5869. hasFaceColor = isBitSet( type, 6 );
  5870. hasFaceVertexColor = isBitSet( type, 7 );
  5871. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5872. if ( isQuad ) {
  5873. face = new THREE.Face4();
  5874. face.a = faces[ offset ++ ];
  5875. face.b = faces[ offset ++ ];
  5876. face.c = faces[ offset ++ ];
  5877. face.d = faces[ offset ++ ];
  5878. nVertices = 4;
  5879. } else {
  5880. face = new THREE.Face3();
  5881. face.a = faces[ offset ++ ];
  5882. face.b = faces[ offset ++ ];
  5883. face.c = faces[ offset ++ ];
  5884. nVertices = 3;
  5885. }
  5886. if ( hasMaterial ) {
  5887. materialIndex = faces[ offset ++ ];
  5888. face.materialIndex = materialIndex;
  5889. }
  5890. // to get face <=> uv index correspondence
  5891. fi = geometry.faces.length;
  5892. if ( hasFaceUv ) {
  5893. for ( i = 0; i < nUvLayers; i++ ) {
  5894. uvLayer = json.uvs[ i ];
  5895. uvIndex = faces[ offset ++ ];
  5896. u = uvLayer[ uvIndex * 2 ];
  5897. v = uvLayer[ uvIndex * 2 + 1 ];
  5898. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5899. }
  5900. }
  5901. if ( hasFaceVertexUv ) {
  5902. for ( i = 0; i < nUvLayers; i++ ) {
  5903. uvLayer = json.uvs[ i ];
  5904. uvs = [];
  5905. for ( j = 0; j < nVertices; j ++ ) {
  5906. uvIndex = faces[ offset ++ ];
  5907. u = uvLayer[ uvIndex * 2 ];
  5908. v = uvLayer[ uvIndex * 2 + 1 ];
  5909. uvs[ j ] = new THREE.Vector2( u, v );
  5910. }
  5911. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5912. }
  5913. }
  5914. if ( hasFaceNormal ) {
  5915. normalIndex = faces[ offset ++ ] * 3;
  5916. normal = new THREE.Vector3();
  5917. normal.x = normals[ normalIndex ++ ];
  5918. normal.y = normals[ normalIndex ++ ];
  5919. normal.z = normals[ normalIndex ];
  5920. face.normal = normal;
  5921. }
  5922. if ( hasFaceVertexNormal ) {
  5923. for ( i = 0; i < nVertices; i++ ) {
  5924. normalIndex = faces[ offset ++ ] * 3;
  5925. normal = new THREE.Vector3();
  5926. normal.x = normals[ normalIndex ++ ];
  5927. normal.y = normals[ normalIndex ++ ];
  5928. normal.z = normals[ normalIndex ];
  5929. face.vertexNormals.push( normal );
  5930. }
  5931. }
  5932. if ( hasFaceColor ) {
  5933. colorIndex = faces[ offset ++ ];
  5934. color = new THREE.Color( colors[ colorIndex ] );
  5935. face.color = color;
  5936. }
  5937. if ( hasFaceVertexColor ) {
  5938. for ( i = 0; i < nVertices; i++ ) {
  5939. colorIndex = faces[ offset ++ ];
  5940. color = new THREE.Color( colors[ colorIndex ] );
  5941. face.vertexColors.push( color );
  5942. }
  5943. }
  5944. geometry.faces.push( face );
  5945. }
  5946. };
  5947. function parseSkin() {
  5948. var i, l, x, y, z, w, a, b, c, d;
  5949. if ( json.skinWeights ) {
  5950. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5951. x = json.skinWeights[ i ];
  5952. y = json.skinWeights[ i + 1 ];
  5953. z = 0;
  5954. w = 0;
  5955. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5956. }
  5957. }
  5958. if ( json.skinIndices ) {
  5959. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5960. a = json.skinIndices[ i ];
  5961. b = json.skinIndices[ i + 1 ];
  5962. c = 0;
  5963. d = 0;
  5964. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5965. }
  5966. }
  5967. geometry.bones = json.bones;
  5968. geometry.animation = json.animation;
  5969. };
  5970. function parseMorphing( scale ) {
  5971. if ( json.morphTargets !== undefined ) {
  5972. var i, l, v, vl, dstVertices, srcVertices;
  5973. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5974. geometry.morphTargets[ i ] = {};
  5975. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5976. geometry.morphTargets[ i ].vertices = [];
  5977. dstVertices = geometry.morphTargets[ i ].vertices;
  5978. srcVertices = json.morphTargets [ i ].vertices;
  5979. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5980. var vertex = new THREE.Vector3();
  5981. vertex.x = srcVertices[ v ] * scale;
  5982. vertex.y = srcVertices[ v + 1 ] * scale;
  5983. vertex.z = srcVertices[ v + 2 ] * scale;
  5984. dstVertices.push( vertex );
  5985. }
  5986. }
  5987. }
  5988. if ( json.morphColors !== undefined ) {
  5989. var i, l, c, cl, dstColors, srcColors, color;
  5990. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5991. geometry.morphColors[ i ] = {};
  5992. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5993. geometry.morphColors[ i ].colors = [];
  5994. dstColors = geometry.morphColors[ i ].colors;
  5995. srcColors = json.morphColors [ i ].colors;
  5996. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5997. color = new THREE.Color( 0xffaa00 );
  5998. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5999. dstColors.push( color );
  6000. }
  6001. }
  6002. }
  6003. };
  6004. if ( json.materials === undefined ) {
  6005. return { geometry: geometry };
  6006. } else {
  6007. var materials = this.initMaterials( json.materials, texturePath );
  6008. if ( this.needsTangents( materials ) ) {
  6009. geometry.computeTangents();
  6010. }
  6011. return { geometry: geometry, materials: materials };
  6012. }
  6013. };
  6014. /**
  6015. * @author mrdoob / http://mrdoob.com/
  6016. */
  6017. THREE.LoadingMonitor = function () {
  6018. var scope = this;
  6019. var loaded = 0;
  6020. var total = 0;
  6021. var onLoad = function ( event ) {
  6022. loaded ++;
  6023. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6024. if ( loaded === total ) {
  6025. scope.dispatchEvent( { type: 'load' } );
  6026. }
  6027. };
  6028. this.add = function ( loader ) {
  6029. total ++;
  6030. loader.addEventListener( 'load', onLoad, false );
  6031. };
  6032. };
  6033. THREE.extend( THREE.LoadingMonitor.prototype, THREE.EventDispatcher.prototype );
  6034. /**
  6035. * @author mrdoob / http://mrdoob.com/
  6036. */
  6037. THREE.GeometryLoader = function () {};
  6038. THREE.extend( THREE.GeometryLoader.prototype, THREE.EventDispatcher.prototype );
  6039. /**
  6040. * @author mrdoob / http://mrdoob.com/
  6041. */
  6042. THREE.MaterialLoader = function () {};
  6043. THREE.MaterialLoader.prototype = {
  6044. constructor: THREE.MaterialLoader,
  6045. load: function ( url ) {
  6046. var scope = this;
  6047. var request = new XMLHttpRequest();
  6048. request.addEventListener( 'load', function ( event ) {
  6049. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6050. scope.dispatchEvent( { type: 'load', content: response } );
  6051. }, false );
  6052. request.addEventListener( 'progress', function ( event ) {
  6053. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6054. }, false );
  6055. request.addEventListener( 'error', function () {
  6056. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6057. }, false );
  6058. request.open( 'GET', url, true );
  6059. request.send( null );
  6060. },
  6061. parse: function ( json ) {
  6062. var material;
  6063. switch ( json.type ) {
  6064. case 'MeshBasicMaterial':
  6065. material = new THREE.MeshBasicMaterial( {
  6066. color: json.color,
  6067. opacity: json.opacity,
  6068. transparent: json.transparent,
  6069. wireframe: json.wireframe
  6070. } );
  6071. break;
  6072. case 'MeshLambertMaterial':
  6073. material = new THREE.MeshLambertMaterial( {
  6074. color: json.color,
  6075. ambient: json.ambient,
  6076. emissive: json.emissive,
  6077. opacity: json.opacity,
  6078. transparent: json.transparent,
  6079. wireframe: json.wireframe
  6080. } );
  6081. break;
  6082. case 'MeshPhongMaterial':
  6083. material = new THREE.MeshPhongMaterial( {
  6084. color: json.color,
  6085. ambient: json.ambient,
  6086. emissive: json.emissive,
  6087. specular: json.specular,
  6088. shininess: json.shininess,
  6089. opacity: json.opacity,
  6090. transparent: json.transparent,
  6091. wireframe: json.wireframe
  6092. } );
  6093. break;
  6094. case 'MeshNormalMaterial':
  6095. material = new THREE.MeshNormalMaterial( {
  6096. opacity: json.opacity,
  6097. transparent: json.transparent,
  6098. wireframe: json.wireframe
  6099. } );
  6100. break;
  6101. case 'MeshDepthMaterial':
  6102. material = new THREE.MeshDepthMaterial( {
  6103. opacity: json.opacity,
  6104. transparent: json.transparent,
  6105. wireframe: json.wireframe
  6106. } );
  6107. break;
  6108. }
  6109. return material;
  6110. }
  6111. };
  6112. THREE.extend( THREE.MaterialLoader.prototype, THREE.EventDispatcher.prototype );
  6113. /**
  6114. * @author alteredq / http://alteredqualia.com/
  6115. */
  6116. THREE.SceneLoader = function () {
  6117. this.onLoadStart = function () {};
  6118. this.onLoadProgress = function() {};
  6119. this.onLoadComplete = function () {};
  6120. this.callbackSync = function () {};
  6121. this.callbackProgress = function () {};
  6122. this.geometryHandlerMap = {};
  6123. this.hierarchyHandlerMap = {};
  6124. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6125. };
  6126. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6127. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6128. var scope = this;
  6129. var xhr = new XMLHttpRequest();
  6130. xhr.onreadystatechange = function () {
  6131. if ( xhr.readyState === 4 ) {
  6132. if ( xhr.status === 200 || xhr.status === 0 ) {
  6133. var json = JSON.parse( xhr.responseText );
  6134. scope.parse( json, callbackFinished, url );
  6135. } else {
  6136. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6137. }
  6138. }
  6139. };
  6140. xhr.open( "GET", url, true );
  6141. xhr.send( null );
  6142. };
  6143. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6144. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6145. };
  6146. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6147. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6148. };
  6149. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6150. var scope = this;
  6151. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6152. var geometry, material, camera, fog,
  6153. texture, images, color,
  6154. light, hex, intensity,
  6155. counter_models, counter_textures,
  6156. total_models, total_textures,
  6157. result;
  6158. var target_array = [];
  6159. var data = json;
  6160. // async geometry loaders
  6161. for ( var typeID in this.geometryHandlerMap ) {
  6162. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6163. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6164. }
  6165. // async hierachy loaders
  6166. for ( var typeID in this.hierarchyHandlerMap ) {
  6167. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6168. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6169. }
  6170. counter_models = 0;
  6171. counter_textures = 0;
  6172. result = {
  6173. scene: new THREE.Scene(),
  6174. geometries: {},
  6175. face_materials: {},
  6176. materials: {},
  6177. textures: {},
  6178. objects: {},
  6179. cameras: {},
  6180. lights: {},
  6181. fogs: {},
  6182. empties: {},
  6183. groups: {}
  6184. };
  6185. if ( data.transform ) {
  6186. var position = data.transform.position,
  6187. rotation = data.transform.rotation,
  6188. scale = data.transform.scale;
  6189. if ( position )
  6190. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6191. if ( rotation )
  6192. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6193. if ( scale )
  6194. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6195. if ( position || rotation || scale ) {
  6196. result.scene.updateMatrix();
  6197. result.scene.updateMatrixWorld();
  6198. }
  6199. }
  6200. function get_url( source_url, url_type ) {
  6201. if ( url_type == "relativeToHTML" ) {
  6202. return source_url;
  6203. } else {
  6204. return urlBase + "/" + source_url;
  6205. }
  6206. };
  6207. // toplevel loader function, delegates to handle_children
  6208. function handle_objects() {
  6209. handle_children( result.scene, data.objects );
  6210. }
  6211. // handle all the children from the loaded json and attach them to given parent
  6212. function handle_children( parent, children ) {
  6213. var mat, dst, pos, rot, scl, quat;
  6214. for ( var objID in children ) {
  6215. // check by id if child has already been handled,
  6216. // if not, create new object
  6217. if ( result.objects[ objID ] === undefined ) {
  6218. var objJSON = children[ objID ];
  6219. var object = null;
  6220. // meshes
  6221. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6222. if ( objJSON.loading === undefined ) {
  6223. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6224. "position": 1, "rotation": 1, "scale" : 1,
  6225. "visible": 1, "children": 1, "userData": 1,
  6226. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6227. var loaderParameters = {};
  6228. for ( var parType in objJSON ) {
  6229. if ( ! ( parType in reservedTypes ) ) {
  6230. loaderParameters[ parType ] = objJSON[ parType ];
  6231. }
  6232. }
  6233. material = result.materials[ objJSON.material ];
  6234. objJSON.loading = true;
  6235. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6236. // ColladaLoader
  6237. if ( loader.options ) {
  6238. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6239. // UTF8Loader
  6240. // OBJLoader
  6241. } else {
  6242. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6243. }
  6244. }
  6245. } else if ( objJSON.geometry !== undefined ) {
  6246. geometry = result.geometries[ objJSON.geometry ];
  6247. // geometry already loaded
  6248. if ( geometry ) {
  6249. var needsTangents = false;
  6250. material = result.materials[ objJSON.material ];
  6251. needsTangents = material instanceof THREE.ShaderMaterial;
  6252. pos = objJSON.position;
  6253. rot = objJSON.rotation;
  6254. scl = objJSON.scale;
  6255. mat = objJSON.matrix;
  6256. quat = objJSON.quaternion;
  6257. // use materials from the model file
  6258. // if there is no material specified in the object
  6259. if ( ! objJSON.material ) {
  6260. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6261. }
  6262. // use materials from the model file
  6263. // if there is just empty face material
  6264. // (must create new material as each model has its own face material)
  6265. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6266. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6267. }
  6268. if ( material instanceof THREE.MeshFaceMaterial ) {
  6269. for ( var i = 0; i < material.materials.length; i ++ ) {
  6270. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6271. }
  6272. }
  6273. if ( needsTangents ) {
  6274. geometry.computeTangents();
  6275. }
  6276. if ( objJSON.skin ) {
  6277. object = new THREE.SkinnedMesh( geometry, material );
  6278. } else if ( objJSON.morph ) {
  6279. object = new THREE.MorphAnimMesh( geometry, material );
  6280. if ( objJSON.duration !== undefined ) {
  6281. object.duration = objJSON.duration;
  6282. }
  6283. if ( objJSON.time !== undefined ) {
  6284. object.time = objJSON.time;
  6285. }
  6286. if ( objJSON.mirroredLoop !== undefined ) {
  6287. object.mirroredLoop = objJSON.mirroredLoop;
  6288. }
  6289. if ( material.morphNormals ) {
  6290. geometry.computeMorphNormals();
  6291. }
  6292. } else {
  6293. object = new THREE.Mesh( geometry, material );
  6294. }
  6295. object.name = objID;
  6296. if ( mat ) {
  6297. object.matrixAutoUpdate = false;
  6298. object.matrix.set(
  6299. mat[0], mat[1], mat[2], mat[3],
  6300. mat[4], mat[5], mat[6], mat[7],
  6301. mat[8], mat[9], mat[10], mat[11],
  6302. mat[12], mat[13], mat[14], mat[15]
  6303. );
  6304. } else {
  6305. object.position.set( pos[0], pos[1], pos[2] );
  6306. if ( quat ) {
  6307. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6308. object.useQuaternion = true;
  6309. } else {
  6310. object.rotation.set( rot[0], rot[1], rot[2] );
  6311. }
  6312. object.scale.set( scl[0], scl[1], scl[2] );
  6313. }
  6314. object.visible = objJSON.visible;
  6315. object.castShadow = objJSON.castShadow;
  6316. object.receiveShadow = objJSON.receiveShadow;
  6317. parent.add( object );
  6318. result.objects[ objID ] = object;
  6319. }
  6320. // lights
  6321. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6322. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6323. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6324. if ( objJSON.type === "DirectionalLight" ) {
  6325. pos = objJSON.direction;
  6326. light = new THREE.DirectionalLight( hex, intensity );
  6327. light.position.set( pos[0], pos[1], pos[2] );
  6328. if ( objJSON.target ) {
  6329. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6330. // kill existing default target
  6331. // otherwise it gets added to scene when parent gets added
  6332. light.target = null;
  6333. }
  6334. } else if ( objJSON.type === "PointLight" ) {
  6335. pos = objJSON.position;
  6336. dst = objJSON.distance;
  6337. light = new THREE.PointLight( hex, intensity, dst );
  6338. light.position.set( pos[0], pos[1], pos[2] );
  6339. } else if ( objJSON.type === "AmbientLight" ) {
  6340. light = new THREE.AmbientLight( hex );
  6341. }
  6342. parent.add( light );
  6343. light.name = objID;
  6344. result.lights[ objID ] = light;
  6345. result.objects[ objID ] = light;
  6346. // cameras
  6347. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6348. if ( objJSON.type === "PerspectiveCamera" ) {
  6349. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6350. } else if ( objJSON.type === "OrthographicCamera" ) {
  6351. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6352. }
  6353. pos = objJSON.position;
  6354. camera.position.set( pos[0], pos[1], pos[2] );
  6355. parent.add( camera );
  6356. camera.name = objID;
  6357. result.cameras[ objID ] = camera;
  6358. result.objects[ objID ] = camera;
  6359. // pure Object3D
  6360. } else {
  6361. pos = objJSON.position;
  6362. rot = objJSON.rotation;
  6363. scl = objJSON.scale;
  6364. quat = objJSON.quaternion;
  6365. object = new THREE.Object3D();
  6366. object.name = objID;
  6367. object.position.set( pos[0], pos[1], pos[2] );
  6368. if ( quat ) {
  6369. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6370. object.useQuaternion = true;
  6371. } else {
  6372. object.rotation.set( rot[0], rot[1], rot[2] );
  6373. }
  6374. object.scale.set( scl[0], scl[1], scl[2] );
  6375. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6376. parent.add( object );
  6377. result.objects[ objID ] = object;
  6378. result.empties[ objID ] = object;
  6379. }
  6380. if ( object ) {
  6381. if ( objJSON.userData !== undefined ) {
  6382. for ( var key in objJSON.userData ) {
  6383. var value = objJSON.userData[ key ];
  6384. object.userData[ key ] = value;
  6385. }
  6386. }
  6387. if ( objJSON.groups !== undefined ) {
  6388. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6389. var groupID = objJSON.groups[ i ];
  6390. if ( result.groups[ groupID ] === undefined ) {
  6391. result.groups[ groupID ] = [];
  6392. }
  6393. result.groups[ groupID ].push( objID );
  6394. }
  6395. }
  6396. if ( objJSON.children !== undefined ) {
  6397. handle_children( object, objJSON.children );
  6398. }
  6399. }
  6400. }
  6401. }
  6402. };
  6403. function handle_mesh( geo, mat, id ) {
  6404. result.geometries[ id ] = geo;
  6405. result.face_materials[ id ] = mat;
  6406. handle_objects();
  6407. };
  6408. function handle_hierarchy( node, id, parent, material, obj ) {
  6409. var p = obj.position;
  6410. var r = obj.rotation;
  6411. var q = obj.quaternion;
  6412. var s = obj.scale;
  6413. node.position.set( p[0], p[1], p[2] );
  6414. if ( q ) {
  6415. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6416. node.useQuaternion = true;
  6417. } else {
  6418. node.rotation.set( r[0], r[1], r[2] );
  6419. }
  6420. node.scale.set( s[0], s[1], s[2] );
  6421. // override children materials
  6422. // if object material was specified in JSON explicitly
  6423. if ( material ) {
  6424. node.traverse( function ( child ) {
  6425. child.material = material;
  6426. } );
  6427. }
  6428. // override children visibility
  6429. // with root node visibility as specified in JSON
  6430. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6431. node.traverse( function ( child ) {
  6432. child.visible = visible;
  6433. } );
  6434. parent.add( node );
  6435. node.name = id;
  6436. result.objects[ id ] = node;
  6437. handle_objects();
  6438. };
  6439. function create_callback_geometry( id ) {
  6440. return function ( geo, mat ) {
  6441. geo.name = id;
  6442. handle_mesh( geo, mat, id );
  6443. counter_models -= 1;
  6444. scope.onLoadComplete();
  6445. async_callback_gate();
  6446. }
  6447. };
  6448. function create_callback_hierachy( id, parent, material, obj ) {
  6449. return function ( event ) {
  6450. var result;
  6451. // loaders which use EventDispatcher
  6452. if ( event.content ) {
  6453. result = event.content;
  6454. // ColladaLoader
  6455. } else if ( event.dae ) {
  6456. result = event.scene;
  6457. // UTF8Loader
  6458. } else {
  6459. result = event;
  6460. }
  6461. handle_hierarchy( result, id, parent, material, obj );
  6462. counter_models -= 1;
  6463. scope.onLoadComplete();
  6464. async_callback_gate();
  6465. }
  6466. };
  6467. function create_callback_embed( id ) {
  6468. return function ( geo, mat ) {
  6469. geo.name = id;
  6470. result.geometries[ id ] = geo;
  6471. result.face_materials[ id ] = mat;
  6472. }
  6473. };
  6474. function async_callback_gate() {
  6475. var progress = {
  6476. totalModels : total_models,
  6477. totalTextures : total_textures,
  6478. loadedModels : total_models - counter_models,
  6479. loadedTextures : total_textures - counter_textures
  6480. };
  6481. scope.callbackProgress( progress, result );
  6482. scope.onLoadProgress();
  6483. if ( counter_models === 0 && counter_textures === 0 ) {
  6484. finalize();
  6485. callbackFinished( result );
  6486. }
  6487. };
  6488. function finalize() {
  6489. // take care of targets which could be asynchronously loaded objects
  6490. for ( var i = 0; i < target_array.length; i ++ ) {
  6491. var ta = target_array[ i ];
  6492. var target = result.objects[ ta.targetName ];
  6493. if ( target ) {
  6494. ta.object.target = target;
  6495. } else {
  6496. // if there was error and target of specified name doesn't exist in the scene file
  6497. // create instead dummy target
  6498. // (target must be added to scene explicitly as parent is already added)
  6499. ta.object.target = new THREE.Object3D();
  6500. result.scene.add( ta.object.target );
  6501. }
  6502. ta.object.target.userData.targetInverse = ta.object;
  6503. }
  6504. };
  6505. var callbackTexture = function ( count ) {
  6506. counter_textures -= count;
  6507. async_callback_gate();
  6508. scope.onLoadComplete();
  6509. };
  6510. // must use this instead of just directly calling callbackTexture
  6511. // because of closure in the calling context loop
  6512. var generateTextureCallback = function ( count ) {
  6513. return function () {
  6514. callbackTexture( count );
  6515. };
  6516. };
  6517. // first go synchronous elements
  6518. // fogs
  6519. var fogID, fogJSON;
  6520. for ( fogID in data.fogs ) {
  6521. fogJSON = data.fogs[ fogID ];
  6522. if ( fogJSON.type === "linear" ) {
  6523. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6524. } else if ( fogJSON.type === "exp2" ) {
  6525. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6526. }
  6527. color = fogJSON.color;
  6528. fog.color.setRGB( color[0], color[1], color[2] );
  6529. result.fogs[ fogID ] = fog;
  6530. }
  6531. // now come potentially asynchronous elements
  6532. // geometries
  6533. // count how many geometries will be loaded asynchronously
  6534. var geoID, geoJSON;
  6535. for ( geoID in data.geometries ) {
  6536. geoJSON = data.geometries[ geoID ];
  6537. if ( geoJSON.type in this.geometryHandlerMap ) {
  6538. counter_models += 1;
  6539. scope.onLoadStart();
  6540. }
  6541. }
  6542. // count how many hierarchies will be loaded asynchronously
  6543. var objID, objJSON;
  6544. for ( objID in data.objects ) {
  6545. objJSON = data.objects[ objID ];
  6546. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6547. counter_models += 1;
  6548. scope.onLoadStart();
  6549. }
  6550. }
  6551. total_models = counter_models;
  6552. for ( geoID in data.geometries ) {
  6553. geoJSON = data.geometries[ geoID ];
  6554. if ( geoJSON.type === "cube" ) {
  6555. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6556. geometry.name = geoID;
  6557. result.geometries[ geoID ] = geometry;
  6558. } else if ( geoJSON.type === "plane" ) {
  6559. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6560. geometry.name = geoID;
  6561. result.geometries[ geoID ] = geometry;
  6562. } else if ( geoJSON.type === "sphere" ) {
  6563. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6564. geometry.name = geoID;
  6565. result.geometries[ geoID ] = geometry;
  6566. } else if ( geoJSON.type === "cylinder" ) {
  6567. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6568. geometry.name = geoID;
  6569. result.geometries[ geoID ] = geometry;
  6570. } else if ( geoJSON.type === "torus" ) {
  6571. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6572. geometry.name = geoID;
  6573. result.geometries[ geoID ] = geometry;
  6574. } else if ( geoJSON.type === "icosahedron" ) {
  6575. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6576. geometry.name = geoID;
  6577. result.geometries[ geoID ] = geometry;
  6578. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6579. var loaderParameters = {};
  6580. for ( var parType in geoJSON ) {
  6581. if ( parType !== "type" && parType !== "url" ) {
  6582. loaderParameters[ parType ] = geoJSON[ parType ];
  6583. }
  6584. }
  6585. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6586. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6587. } else if ( geoJSON.type === "embedded" ) {
  6588. var modelJson = data.embeds[ geoJSON.id ],
  6589. texture_path = "";
  6590. // pass metadata along to jsonLoader so it knows the format version
  6591. modelJson.metadata = data.metadata;
  6592. if ( modelJson ) {
  6593. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6594. var model = jsonLoader.parse( modelJson, texture_path );
  6595. create_callback_embed( geoID )( model.geometry, model.materials );
  6596. }
  6597. }
  6598. }
  6599. // textures
  6600. // count how many textures will be loaded asynchronously
  6601. var textureID, textureJSON;
  6602. for ( textureID in data.textures ) {
  6603. textureJSON = data.textures[ textureID ];
  6604. if ( textureJSON.url instanceof Array ) {
  6605. counter_textures += textureJSON.url.length;
  6606. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6607. scope.onLoadStart();
  6608. }
  6609. } else {
  6610. counter_textures += 1;
  6611. scope.onLoadStart();
  6612. }
  6613. }
  6614. total_textures = counter_textures;
  6615. for ( textureID in data.textures ) {
  6616. textureJSON = data.textures[ textureID ];
  6617. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6618. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6619. }
  6620. if ( textureJSON.url instanceof Array ) {
  6621. var count = textureJSON.url.length;
  6622. var url_array = [];
  6623. for( var i = 0; i < count; i ++ ) {
  6624. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6625. }
  6626. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6627. if ( isCompressed ) {
  6628. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6629. } else {
  6630. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6631. }
  6632. } else {
  6633. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6634. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6635. var textureCallback = generateTextureCallback( 1 );
  6636. if ( isCompressed ) {
  6637. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6638. } else {
  6639. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6640. }
  6641. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6642. texture.minFilter = THREE[ textureJSON.minFilter ];
  6643. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6644. texture.magFilter = THREE[ textureJSON.magFilter ];
  6645. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6646. if ( textureJSON.repeat ) {
  6647. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6648. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6649. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6650. }
  6651. if ( textureJSON.offset ) {
  6652. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6653. }
  6654. // handle wrap after repeat so that default repeat can be overriden
  6655. if ( textureJSON.wrap ) {
  6656. var wrapMap = {
  6657. "repeat" : THREE.RepeatWrapping,
  6658. "mirror" : THREE.MirroredRepeatWrapping
  6659. }
  6660. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6661. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6662. }
  6663. }
  6664. result.textures[ textureID ] = texture;
  6665. }
  6666. // materials
  6667. var matID, matJSON;
  6668. var parID;
  6669. for ( matID in data.materials ) {
  6670. matJSON = data.materials[ matID ];
  6671. for ( parID in matJSON.parameters ) {
  6672. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6673. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6674. } else if ( parID === "shading" ) {
  6675. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6676. } else if ( parID === "side" ) {
  6677. if ( matJSON.parameters[ parID ] == "double" ) {
  6678. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6679. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6680. matJSON.parameters[ parID ] = THREE.BackSide;
  6681. } else {
  6682. matJSON.parameters[ parID ] = THREE.FrontSide;
  6683. }
  6684. } else if ( parID === "blending" ) {
  6685. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6686. } else if ( parID === "combine" ) {
  6687. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6688. } else if ( parID === "vertexColors" ) {
  6689. if ( matJSON.parameters[ parID ] == "face" ) {
  6690. matJSON.parameters[ parID ] = THREE.FaceColors;
  6691. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6692. } else if ( matJSON.parameters[ parID ] ) {
  6693. matJSON.parameters[ parID ] = THREE.VertexColors;
  6694. }
  6695. } else if ( parID === "wrapRGB" ) {
  6696. var v3 = matJSON.parameters[ parID ];
  6697. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6698. }
  6699. }
  6700. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6701. matJSON.parameters.transparent = true;
  6702. }
  6703. if ( matJSON.parameters.normalMap ) {
  6704. var shader = THREE.ShaderLib[ "normalmap" ];
  6705. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6706. var diffuse = matJSON.parameters.color;
  6707. var specular = matJSON.parameters.specular;
  6708. var ambient = matJSON.parameters.ambient;
  6709. var shininess = matJSON.parameters.shininess;
  6710. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6711. if ( matJSON.parameters.normalScale ) {
  6712. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6713. }
  6714. if ( matJSON.parameters.map ) {
  6715. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6716. uniforms[ "enableDiffuse" ].value = true;
  6717. }
  6718. if ( matJSON.parameters.envMap ) {
  6719. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6720. uniforms[ "enableReflection" ].value = true;
  6721. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6722. }
  6723. if ( matJSON.parameters.lightMap ) {
  6724. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6725. uniforms[ "enableAO" ].value = true;
  6726. }
  6727. if ( matJSON.parameters.specularMap ) {
  6728. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6729. uniforms[ "enableSpecular" ].value = true;
  6730. }
  6731. if ( matJSON.parameters.displacementMap ) {
  6732. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6733. uniforms[ "enableDisplacement" ].value = true;
  6734. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6735. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6736. }
  6737. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6738. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6739. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6740. uniforms[ "uShininess" ].value = shininess;
  6741. if ( matJSON.parameters.opacity ) {
  6742. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6743. }
  6744. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6745. material = new THREE.ShaderMaterial( parameters );
  6746. } else {
  6747. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6748. }
  6749. material.name = matID;
  6750. result.materials[ matID ] = material;
  6751. }
  6752. // second pass through all materials to initialize MeshFaceMaterials
  6753. // that could be referring to other materials out of order
  6754. for ( matID in data.materials ) {
  6755. matJSON = data.materials[ matID ];
  6756. if ( matJSON.parameters.materials ) {
  6757. var materialArray = [];
  6758. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6759. var label = matJSON.parameters.materials[ i ];
  6760. materialArray.push( result.materials[ label ] );
  6761. }
  6762. result.materials[ matID ].materials = materialArray;
  6763. }
  6764. }
  6765. // objects ( synchronous init of procedural primitives )
  6766. handle_objects();
  6767. // defaults
  6768. if ( result.cameras && data.defaults.camera ) {
  6769. result.currentCamera = result.cameras[ data.defaults.camera ];
  6770. }
  6771. if ( result.fogs && data.defaults.fog ) {
  6772. result.scene.fog = result.fogs[ data.defaults.fog ];
  6773. }
  6774. // synchronous callback
  6775. scope.callbackSync( result );
  6776. // just in case there are no async elements
  6777. async_callback_gate();
  6778. };
  6779. /**
  6780. * @author mrdoob / http://mrdoob.com/
  6781. */
  6782. THREE.TextureLoader = function () {
  6783. this.crossOrigin = null;
  6784. };
  6785. THREE.TextureLoader.prototype.load = function ( url ) {
  6786. var scope = this;
  6787. var image = new Image();
  6788. image.addEventListener( 'load', function () {
  6789. var texture = new THREE.Texture( image );
  6790. texture.needsUpdate = true;
  6791. scope.dispatchEvent( { type: 'load', content: texture } );
  6792. }, false );
  6793. image.addEventListener( 'error', function () {
  6794. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6795. }, false );
  6796. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6797. image.src = url;
  6798. };
  6799. THREE.extend( THREE.TextureLoader.prototype, THREE.EventDispatcher.prototype );
  6800. /**
  6801. * @author mrdoob / http://mrdoob.com/
  6802. * @author alteredq / http://alteredqualia.com/
  6803. */
  6804. THREE.Material = function () {
  6805. this.id = THREE.MaterialIdCount ++;
  6806. this.name = '';
  6807. this.side = THREE.FrontSide;
  6808. this.opacity = 1;
  6809. this.transparent = false;
  6810. this.blending = THREE.NormalBlending;
  6811. this.blendSrc = THREE.SrcAlphaFactor;
  6812. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6813. this.blendEquation = THREE.AddEquation;
  6814. this.depthTest = true;
  6815. this.depthWrite = true;
  6816. this.polygonOffset = false;
  6817. this.polygonOffsetFactor = 0;
  6818. this.polygonOffsetUnits = 0;
  6819. this.alphaTest = 0;
  6820. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6821. this.visible = true;
  6822. this.needsUpdate = true;
  6823. };
  6824. THREE.Material.prototype = {
  6825. constructor: THREE.Material,
  6826. setValues: function ( values ) {
  6827. if ( values === undefined ) return;
  6828. for ( var key in values ) {
  6829. var newValue = values[ key ];
  6830. if ( newValue === undefined ) {
  6831. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6832. continue;
  6833. }
  6834. if ( key in this ) {
  6835. var currentValue = this[ key ];
  6836. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6837. currentValue.copy( newValue );
  6838. } else if ( currentValue instanceof THREE.Color ) {
  6839. currentValue.set( newValue );
  6840. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6841. currentValue.copy( newValue );
  6842. } else {
  6843. this[ key ] = newValue;
  6844. }
  6845. }
  6846. }
  6847. },
  6848. clone: function ( material ) {
  6849. if ( material === undefined ) material = new THREE.Material();
  6850. material.name = this.name;
  6851. material.side = this.side;
  6852. material.opacity = this.opacity;
  6853. material.transparent = this.transparent;
  6854. material.blending = this.blending;
  6855. material.blendSrc = this.blendSrc;
  6856. material.blendDst = this.blendDst;
  6857. material.blendEquation = this.blendEquation;
  6858. material.depthTest = this.depthTest;
  6859. material.depthWrite = this.depthWrite;
  6860. material.polygonOffset = this.polygonOffset;
  6861. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6862. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6863. material.alphaTest = this.alphaTest;
  6864. material.overdraw = this.overdraw;
  6865. material.visible = this.visible;
  6866. return material;
  6867. },
  6868. dispose: function () {
  6869. this.dispatchEvent( { type: 'dispose' } );
  6870. }
  6871. };
  6872. THREE.extend( THREE.Material.prototype, THREE.EventDispatcher.prototype );
  6873. THREE.MaterialIdCount = 0;
  6874. /**
  6875. * @author mrdoob / http://mrdoob.com/
  6876. * @author alteredq / http://alteredqualia.com/
  6877. *
  6878. * parameters = {
  6879. * color: <hex>,
  6880. * opacity: <float>,
  6881. *
  6882. * blending: THREE.NormalBlending,
  6883. * depthTest: <bool>,
  6884. * depthWrite: <bool>,
  6885. *
  6886. * linewidth: <float>,
  6887. * linecap: "round",
  6888. * linejoin: "round",
  6889. *
  6890. * vertexColors: <bool>
  6891. *
  6892. * fog: <bool>
  6893. * }
  6894. */
  6895. THREE.LineBasicMaterial = function ( parameters ) {
  6896. THREE.Material.call( this );
  6897. this.color = new THREE.Color( 0xffffff );
  6898. this.linewidth = 1;
  6899. this.linecap = 'round';
  6900. this.linejoin = 'round';
  6901. this.vertexColors = false;
  6902. this.fog = true;
  6903. this.setValues( parameters );
  6904. };
  6905. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6906. THREE.LineBasicMaterial.prototype.clone = function () {
  6907. var material = new THREE.LineBasicMaterial();
  6908. THREE.Material.prototype.clone.call( this, material );
  6909. material.color.copy( this.color );
  6910. material.linewidth = this.linewidth;
  6911. material.linecap = this.linecap;
  6912. material.linejoin = this.linejoin;
  6913. material.vertexColors = this.vertexColors;
  6914. material.fog = this.fog;
  6915. return material;
  6916. };
  6917. /**
  6918. * @author alteredq / http://alteredqualia.com/
  6919. *
  6920. * parameters = {
  6921. * color: <hex>,
  6922. * opacity: <float>,
  6923. *
  6924. * blending: THREE.NormalBlending,
  6925. * depthTest: <bool>,
  6926. * depthWrite: <bool>,
  6927. *
  6928. * linewidth: <float>,
  6929. *
  6930. * scale: <float>,
  6931. * dashSize: <float>,
  6932. * gapSize: <float>,
  6933. *
  6934. * vertexColors: <bool>
  6935. *
  6936. * fog: <bool>
  6937. * }
  6938. */
  6939. THREE.LineDashedMaterial = function ( parameters ) {
  6940. THREE.Material.call( this );
  6941. this.color = new THREE.Color( 0xffffff );
  6942. this.linewidth = 1;
  6943. this.scale = 1;
  6944. this.dashSize = 3;
  6945. this.gapSize = 1;
  6946. this.vertexColors = false;
  6947. this.fog = true;
  6948. this.setValues( parameters );
  6949. };
  6950. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6951. THREE.LineDashedMaterial.prototype.clone = function () {
  6952. var material = new THREE.LineDashedMaterial();
  6953. THREE.Material.prototype.clone.call( this, material );
  6954. material.color.copy( this.color );
  6955. material.linewidth = this.linewidth;
  6956. material.scale = this.scale;
  6957. material.dashSize = this.dashSize;
  6958. material.gapSize = this.gapSize;
  6959. material.vertexColors = this.vertexColors;
  6960. material.fog = this.fog;
  6961. return material;
  6962. };
  6963. /**
  6964. * @author mrdoob / http://mrdoob.com/
  6965. * @author alteredq / http://alteredqualia.com/
  6966. *
  6967. * parameters = {
  6968. * color: <hex>,
  6969. * opacity: <float>,
  6970. * map: new THREE.Texture( <Image> ),
  6971. *
  6972. * lightMap: new THREE.Texture( <Image> ),
  6973. *
  6974. * specularMap: new THREE.Texture( <Image> ),
  6975. *
  6976. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6977. * combine: THREE.Multiply,
  6978. * reflectivity: <float>,
  6979. * refractionRatio: <float>,
  6980. *
  6981. * shading: THREE.SmoothShading,
  6982. * blending: THREE.NormalBlending,
  6983. * depthTest: <bool>,
  6984. * depthWrite: <bool>,
  6985. *
  6986. * wireframe: <boolean>,
  6987. * wireframeLinewidth: <float>,
  6988. *
  6989. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6990. *
  6991. * skinning: <bool>,
  6992. * morphTargets: <bool>,
  6993. *
  6994. * fog: <bool>
  6995. * }
  6996. */
  6997. THREE.MeshBasicMaterial = function ( parameters ) {
  6998. THREE.Material.call( this );
  6999. this.color = new THREE.Color( 0xffffff ); // emissive
  7000. this.map = null;
  7001. this.lightMap = null;
  7002. this.specularMap = null;
  7003. this.envMap = null;
  7004. this.combine = THREE.MultiplyOperation;
  7005. this.reflectivity = 1;
  7006. this.refractionRatio = 0.98;
  7007. this.fog = true;
  7008. this.shading = THREE.SmoothShading;
  7009. this.wireframe = false;
  7010. this.wireframeLinewidth = 1;
  7011. this.wireframeLinecap = 'round';
  7012. this.wireframeLinejoin = 'round';
  7013. this.vertexColors = THREE.NoColors;
  7014. this.skinning = false;
  7015. this.morphTargets = false;
  7016. this.setValues( parameters );
  7017. };
  7018. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7019. THREE.MeshBasicMaterial.prototype.clone = function () {
  7020. var material = new THREE.MeshBasicMaterial();
  7021. THREE.Material.prototype.clone.call( this, material );
  7022. material.color.copy( this.color );
  7023. material.map = this.map;
  7024. material.lightMap = this.lightMap;
  7025. material.specularMap = this.specularMap;
  7026. material.envMap = this.envMap;
  7027. material.combine = this.combine;
  7028. material.reflectivity = this.reflectivity;
  7029. material.refractionRatio = this.refractionRatio;
  7030. material.fog = this.fog;
  7031. material.shading = this.shading;
  7032. material.wireframe = this.wireframe;
  7033. material.wireframeLinewidth = this.wireframeLinewidth;
  7034. material.wireframeLinecap = this.wireframeLinecap;
  7035. material.wireframeLinejoin = this.wireframeLinejoin;
  7036. material.vertexColors = this.vertexColors;
  7037. material.skinning = this.skinning;
  7038. material.morphTargets = this.morphTargets;
  7039. return material;
  7040. };
  7041. /**
  7042. * @author mrdoob / http://mrdoob.com/
  7043. * @author alteredq / http://alteredqualia.com/
  7044. *
  7045. * parameters = {
  7046. * color: <hex>,
  7047. * ambient: <hex>,
  7048. * emissive: <hex>,
  7049. * opacity: <float>,
  7050. *
  7051. * map: new THREE.Texture( <Image> ),
  7052. *
  7053. * lightMap: new THREE.Texture( <Image> ),
  7054. *
  7055. * specularMap: new THREE.Texture( <Image> ),
  7056. *
  7057. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7058. * combine: THREE.Multiply,
  7059. * reflectivity: <float>,
  7060. * refractionRatio: <float>,
  7061. *
  7062. * shading: THREE.SmoothShading,
  7063. * blending: THREE.NormalBlending,
  7064. * depthTest: <bool>,
  7065. * depthWrite: <bool>,
  7066. *
  7067. * wireframe: <boolean>,
  7068. * wireframeLinewidth: <float>,
  7069. *
  7070. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7071. *
  7072. * skinning: <bool>,
  7073. * morphTargets: <bool>,
  7074. * morphNormals: <bool>,
  7075. *
  7076. * fog: <bool>
  7077. * }
  7078. */
  7079. THREE.MeshLambertMaterial = function ( parameters ) {
  7080. THREE.Material.call( this );
  7081. this.color = new THREE.Color( 0xffffff ); // diffuse
  7082. this.ambient = new THREE.Color( 0xffffff );
  7083. this.emissive = new THREE.Color( 0x000000 );
  7084. this.wrapAround = false;
  7085. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7086. this.map = null;
  7087. this.lightMap = null;
  7088. this.specularMap = null;
  7089. this.envMap = null;
  7090. this.combine = THREE.MultiplyOperation;
  7091. this.reflectivity = 1;
  7092. this.refractionRatio = 0.98;
  7093. this.fog = true;
  7094. this.shading = THREE.SmoothShading;
  7095. this.wireframe = false;
  7096. this.wireframeLinewidth = 1;
  7097. this.wireframeLinecap = 'round';
  7098. this.wireframeLinejoin = 'round';
  7099. this.vertexColors = THREE.NoColors;
  7100. this.skinning = false;
  7101. this.morphTargets = false;
  7102. this.morphNormals = false;
  7103. this.setValues( parameters );
  7104. };
  7105. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7106. THREE.MeshLambertMaterial.prototype.clone = function () {
  7107. var material = new THREE.MeshLambertMaterial();
  7108. THREE.Material.prototype.clone.call( this, material );
  7109. material.color.copy( this.color );
  7110. material.ambient.copy( this.ambient );
  7111. material.emissive.copy( this.emissive );
  7112. material.wrapAround = this.wrapAround;
  7113. material.wrapRGB.copy( this.wrapRGB );
  7114. material.map = this.map;
  7115. material.lightMap = this.lightMap;
  7116. material.specularMap = this.specularMap;
  7117. material.envMap = this.envMap;
  7118. material.combine = this.combine;
  7119. material.reflectivity = this.reflectivity;
  7120. material.refractionRatio = this.refractionRatio;
  7121. material.fog = this.fog;
  7122. material.shading = this.shading;
  7123. material.wireframe = this.wireframe;
  7124. material.wireframeLinewidth = this.wireframeLinewidth;
  7125. material.wireframeLinecap = this.wireframeLinecap;
  7126. material.wireframeLinejoin = this.wireframeLinejoin;
  7127. material.vertexColors = this.vertexColors;
  7128. material.skinning = this.skinning;
  7129. material.morphTargets = this.morphTargets;
  7130. material.morphNormals = this.morphNormals;
  7131. return material;
  7132. };
  7133. /**
  7134. * @author mrdoob / http://mrdoob.com/
  7135. * @author alteredq / http://alteredqualia.com/
  7136. *
  7137. * parameters = {
  7138. * color: <hex>,
  7139. * ambient: <hex>,
  7140. * emissive: <hex>,
  7141. * specular: <hex>,
  7142. * shininess: <float>,
  7143. * opacity: <float>,
  7144. *
  7145. * map: new THREE.Texture( <Image> ),
  7146. *
  7147. * lightMap: new THREE.Texture( <Image> ),
  7148. *
  7149. * bumpMap: new THREE.Texture( <Image> ),
  7150. * bumpScale: <float>,
  7151. *
  7152. * normalMap: new THREE.Texture( <Image> ),
  7153. * normalScale: <Vector2>,
  7154. *
  7155. * specularMap: new THREE.Texture( <Image> ),
  7156. *
  7157. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7158. * combine: THREE.Multiply,
  7159. * reflectivity: <float>,
  7160. * refractionRatio: <float>,
  7161. *
  7162. * shading: THREE.SmoothShading,
  7163. * blending: THREE.NormalBlending,
  7164. * depthTest: <bool>,
  7165. * depthWrite: <bool>,
  7166. *
  7167. * wireframe: <boolean>,
  7168. * wireframeLinewidth: <float>,
  7169. *
  7170. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7171. *
  7172. * skinning: <bool>,
  7173. * morphTargets: <bool>,
  7174. * morphNormals: <bool>,
  7175. *
  7176. * fog: <bool>
  7177. * }
  7178. */
  7179. THREE.MeshPhongMaterial = function ( parameters ) {
  7180. THREE.Material.call( this );
  7181. this.color = new THREE.Color( 0xffffff ); // diffuse
  7182. this.ambient = new THREE.Color( 0xffffff );
  7183. this.emissive = new THREE.Color( 0x000000 );
  7184. this.specular = new THREE.Color( 0x111111 );
  7185. this.shininess = 30;
  7186. this.metal = false;
  7187. this.perPixel = true;
  7188. this.wrapAround = false;
  7189. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7190. this.map = null;
  7191. this.lightMap = null;
  7192. this.bumpMap = null;
  7193. this.bumpScale = 1;
  7194. this.normalMap = null;
  7195. this.normalScale = new THREE.Vector2( 1, 1 );
  7196. this.specularMap = null;
  7197. this.envMap = null;
  7198. this.combine = THREE.MultiplyOperation;
  7199. this.reflectivity = 1;
  7200. this.refractionRatio = 0.98;
  7201. this.fog = true;
  7202. this.shading = THREE.SmoothShading;
  7203. this.wireframe = false;
  7204. this.wireframeLinewidth = 1;
  7205. this.wireframeLinecap = 'round';
  7206. this.wireframeLinejoin = 'round';
  7207. this.vertexColors = THREE.NoColors;
  7208. this.skinning = false;
  7209. this.morphTargets = false;
  7210. this.morphNormals = false;
  7211. this.setValues( parameters );
  7212. };
  7213. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7214. THREE.MeshPhongMaterial.prototype.clone = function () {
  7215. var material = new THREE.MeshPhongMaterial();
  7216. THREE.Material.prototype.clone.call( this, material );
  7217. material.color.copy( this.color );
  7218. material.ambient.copy( this.ambient );
  7219. material.emissive.copy( this.emissive );
  7220. material.specular.copy( this.specular );
  7221. material.shininess = this.shininess;
  7222. material.metal = this.metal;
  7223. material.perPixel = this.perPixel;
  7224. material.wrapAround = this.wrapAround;
  7225. material.wrapRGB.copy( this.wrapRGB );
  7226. material.map = this.map;
  7227. material.lightMap = this.lightMap;
  7228. material.bumpMap = this.bumpMap;
  7229. material.bumpScale = this.bumpScale;
  7230. material.normalMap = this.normalMap;
  7231. material.normalScale.copy( this.normalScale );
  7232. material.specularMap = this.specularMap;
  7233. material.envMap = this.envMap;
  7234. material.combine = this.combine;
  7235. material.reflectivity = this.reflectivity;
  7236. material.refractionRatio = this.refractionRatio;
  7237. material.fog = this.fog;
  7238. material.shading = this.shading;
  7239. material.wireframe = this.wireframe;
  7240. material.wireframeLinewidth = this.wireframeLinewidth;
  7241. material.wireframeLinecap = this.wireframeLinecap;
  7242. material.wireframeLinejoin = this.wireframeLinejoin;
  7243. material.vertexColors = this.vertexColors;
  7244. material.skinning = this.skinning;
  7245. material.morphTargets = this.morphTargets;
  7246. material.morphNormals = this.morphNormals;
  7247. return material;
  7248. };
  7249. /**
  7250. * @author mrdoob / http://mrdoob.com/
  7251. * @author alteredq / http://alteredqualia.com/
  7252. *
  7253. * parameters = {
  7254. * opacity: <float>,
  7255. *
  7256. * blending: THREE.NormalBlending,
  7257. * depthTest: <bool>,
  7258. * depthWrite: <bool>,
  7259. *
  7260. * wireframe: <boolean>,
  7261. * wireframeLinewidth: <float>
  7262. * }
  7263. */
  7264. THREE.MeshDepthMaterial = function ( parameters ) {
  7265. THREE.Material.call( this );
  7266. this.wireframe = false;
  7267. this.wireframeLinewidth = 1;
  7268. this.setValues( parameters );
  7269. };
  7270. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7271. THREE.MeshDepthMaterial.prototype.clone = function () {
  7272. var material = new THREE.MeshDepthMaterial();
  7273. THREE.Material.prototype.clone.call( this, material );
  7274. material.wireframe = this.wireframe;
  7275. material.wireframeLinewidth = this.wireframeLinewidth;
  7276. return material;
  7277. };
  7278. /**
  7279. * @author mrdoob / http://mrdoob.com/
  7280. *
  7281. * parameters = {
  7282. * opacity: <float>,
  7283. *
  7284. * shading: THREE.FlatShading,
  7285. * blending: THREE.NormalBlending,
  7286. * depthTest: <bool>,
  7287. * depthWrite: <bool>,
  7288. *
  7289. * wireframe: <boolean>,
  7290. * wireframeLinewidth: <float>
  7291. * }
  7292. */
  7293. THREE.MeshNormalMaterial = function ( parameters ) {
  7294. THREE.Material.call( this, parameters );
  7295. this.shading = THREE.FlatShading;
  7296. this.wireframe = false;
  7297. this.wireframeLinewidth = 1;
  7298. this.morphTargets = false;
  7299. this.setValues( parameters );
  7300. };
  7301. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7302. THREE.MeshNormalMaterial.prototype.clone = function () {
  7303. var material = new THREE.MeshNormalMaterial();
  7304. THREE.Material.prototype.clone.call( this, material );
  7305. material.shading = this.shading;
  7306. material.wireframe = this.wireframe;
  7307. material.wireframeLinewidth = this.wireframeLinewidth;
  7308. return material;
  7309. };
  7310. /**
  7311. * @author mrdoob / http://mrdoob.com/
  7312. */
  7313. THREE.MeshFaceMaterial = function ( materials ) {
  7314. this.materials = materials instanceof Array ? materials : [];
  7315. };
  7316. THREE.MeshFaceMaterial.prototype.clone = function () {
  7317. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7318. };
  7319. /**
  7320. * @author mrdoob / http://mrdoob.com/
  7321. * @author alteredq / http://alteredqualia.com/
  7322. *
  7323. * parameters = {
  7324. * color: <hex>,
  7325. * opacity: <float>,
  7326. * map: new THREE.Texture( <Image> ),
  7327. *
  7328. * size: <float>,
  7329. *
  7330. * blending: THREE.NormalBlending,
  7331. * depthTest: <bool>,
  7332. * depthWrite: <bool>,
  7333. *
  7334. * vertexColors: <bool>,
  7335. *
  7336. * fog: <bool>
  7337. * }
  7338. */
  7339. THREE.ParticleBasicMaterial = function ( parameters ) {
  7340. THREE.Material.call( this );
  7341. this.color = new THREE.Color( 0xffffff );
  7342. this.map = null;
  7343. this.size = 1;
  7344. this.sizeAttenuation = true;
  7345. this.vertexColors = false;
  7346. this.fog = true;
  7347. this.setValues( parameters );
  7348. };
  7349. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7350. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7351. var material = new THREE.ParticleBasicMaterial();
  7352. THREE.Material.prototype.clone.call( this, material );
  7353. material.color.copy( this.color );
  7354. material.map = this.map;
  7355. material.size = this.size;
  7356. material.sizeAttenuation = this.sizeAttenuation;
  7357. material.vertexColors = this.vertexColors;
  7358. material.fog = this.fog;
  7359. return material;
  7360. };
  7361. /**
  7362. * @author mrdoob / http://mrdoob.com/
  7363. *
  7364. * parameters = {
  7365. * color: <hex>,
  7366. * program: <function>,
  7367. * opacity: <float>,
  7368. * blending: THREE.NormalBlending
  7369. * }
  7370. */
  7371. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7372. THREE.Material.call( this );
  7373. this.color = new THREE.Color( 0xffffff );
  7374. this.program = function ( context, color ) {};
  7375. this.setValues( parameters );
  7376. };
  7377. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7378. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7379. var material = new THREE.ParticleCanvasMaterial();
  7380. THREE.Material.prototype.clone.call( this, material );
  7381. material.color.copy( this.color );
  7382. material.program = this.program;
  7383. return material;
  7384. };
  7385. /**
  7386. * @author alteredq / http://alteredqualia.com/
  7387. *
  7388. * parameters = {
  7389. * fragmentShader: <string>,
  7390. * vertexShader: <string>,
  7391. *
  7392. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7393. *
  7394. * defines: { "label" : "value" },
  7395. *
  7396. * shading: THREE.SmoothShading,
  7397. * blending: THREE.NormalBlending,
  7398. * depthTest: <bool>,
  7399. * depthWrite: <bool>,
  7400. *
  7401. * wireframe: <boolean>,
  7402. * wireframeLinewidth: <float>,
  7403. *
  7404. * lights: <bool>,
  7405. *
  7406. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7407. *
  7408. * skinning: <bool>,
  7409. * morphTargets: <bool>,
  7410. * morphNormals: <bool>,
  7411. *
  7412. * fog: <bool>
  7413. * }
  7414. */
  7415. THREE.ShaderMaterial = function ( parameters ) {
  7416. THREE.Material.call( this );
  7417. this.fragmentShader = "void main() {}";
  7418. this.vertexShader = "void main() {}";
  7419. this.uniforms = {};
  7420. this.defines = {};
  7421. this.attributes = null;
  7422. this.shading = THREE.SmoothShading;
  7423. this.linewidth = 1;
  7424. this.wireframe = false;
  7425. this.wireframeLinewidth = 1;
  7426. this.fog = false; // set to use scene fog
  7427. this.lights = false; // set to use scene lights
  7428. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7429. this.skinning = false; // set to use skinning attribute streams
  7430. this.morphTargets = false; // set to use morph targets
  7431. this.morphNormals = false; // set to use morph normals
  7432. this.setValues( parameters );
  7433. };
  7434. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7435. THREE.ShaderMaterial.prototype.clone = function () {
  7436. var material = new THREE.ShaderMaterial();
  7437. THREE.Material.prototype.clone.call( this, material );
  7438. material.fragmentShader = this.fragmentShader;
  7439. material.vertexShader = this.vertexShader;
  7440. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7441. material.attributes = this.attributes;
  7442. material.defines = this.defines;
  7443. material.shading = this.shading;
  7444. material.wireframe = this.wireframe;
  7445. material.wireframeLinewidth = this.wireframeLinewidth;
  7446. material.fog = this.fog;
  7447. material.lights = this.lights;
  7448. material.vertexColors = this.vertexColors;
  7449. material.skinning = this.skinning;
  7450. material.morphTargets = this.morphTargets;
  7451. material.morphNormals = this.morphNormals;
  7452. return material;
  7453. };
  7454. /**
  7455. * @author alteredq / http://alteredqualia.com/
  7456. *
  7457. * parameters = {
  7458. * color: <hex>,
  7459. * opacity: <float>,
  7460. * map: new THREE.Texture( <Image> ),
  7461. *
  7462. * blending: THREE.NormalBlending,
  7463. * depthTest: <bool>,
  7464. * depthWrite: <bool>,
  7465. *
  7466. * useScreenCoordinates: <bool>,
  7467. * sizeAttenuation: <bool>,
  7468. * scaleByViewport: <bool>,
  7469. * alignment: THREE.SpriteAlignment.center,
  7470. *
  7471. * uvOffset: new THREE.Vector2(),
  7472. * uvScale: new THREE.Vector2(),
  7473. *
  7474. * fog: <bool>
  7475. * }
  7476. */
  7477. THREE.SpriteMaterial = function ( parameters ) {
  7478. THREE.Material.call( this );
  7479. // defaults
  7480. this.color = new THREE.Color( 0xffffff );
  7481. this.map = new THREE.Texture();
  7482. this.useScreenCoordinates = true;
  7483. this.depthTest = !this.useScreenCoordinates;
  7484. this.sizeAttenuation = !this.useScreenCoordinates;
  7485. this.scaleByViewport = !this.sizeAttenuation;
  7486. this.alignment = THREE.SpriteAlignment.center.clone();
  7487. this.fog = false;
  7488. this.uvOffset = new THREE.Vector2( 0, 0 );
  7489. this.uvScale = new THREE.Vector2( 1, 1 );
  7490. // set parameters
  7491. this.setValues( parameters );
  7492. // override coupled defaults if not specified explicitly by parameters
  7493. parameters = parameters || {};
  7494. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7495. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7496. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7497. };
  7498. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7499. THREE.SpriteMaterial.prototype.clone = function () {
  7500. var material = new THREE.SpriteMaterial();
  7501. THREE.Material.prototype.clone.call( this, material );
  7502. material.color.copy( this.color );
  7503. material.map = this.map;
  7504. material.useScreenCoordinates = this.useScreenCoordinates;
  7505. material.sizeAttenuation = this.sizeAttenuation;
  7506. material.scaleByViewport = this.scaleByViewport;
  7507. material.alignment.copy( this.alignment );
  7508. material.uvOffset.copy( this.uvOffset );
  7509. material.uvScale.copy( this.uvScale );
  7510. material.fog = this.fog;
  7511. return material;
  7512. };
  7513. // Alignment enums
  7514. THREE.SpriteAlignment = {};
  7515. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7516. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7517. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7518. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7519. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7520. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7521. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7522. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7523. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7524. /**
  7525. * @author mrdoob / http://mrdoob.com/
  7526. * @author alteredq / http://alteredqualia.com/
  7527. * @author szimek / https://github.com/szimek/
  7528. */
  7529. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7530. this.id = THREE.TextureIdCount ++;
  7531. this.name = '';
  7532. this.image = image;
  7533. this.mipmaps = [];
  7534. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7535. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7536. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7537. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7538. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7539. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7540. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7541. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7542. this.offset = new THREE.Vector2( 0, 0 );
  7543. this.repeat = new THREE.Vector2( 1, 1 );
  7544. this.generateMipmaps = true;
  7545. this.premultiplyAlpha = false;
  7546. this.flipY = true;
  7547. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7548. this.needsUpdate = false;
  7549. this.onUpdate = null;
  7550. };
  7551. THREE.Texture.prototype = {
  7552. constructor: THREE.Texture,
  7553. clone: function ( texture ) {
  7554. if ( texture === undefined ) texture = new THREE.Texture();
  7555. texture.image = this.image;
  7556. texture.mipmaps = this.mipmaps.slice(0);
  7557. texture.mapping = this.mapping;
  7558. texture.wrapS = this.wrapS;
  7559. texture.wrapT = this.wrapT;
  7560. texture.magFilter = this.magFilter;
  7561. texture.minFilter = this.minFilter;
  7562. texture.anisotropy = this.anisotropy;
  7563. texture.format = this.format;
  7564. texture.type = this.type;
  7565. texture.offset.copy( this.offset );
  7566. texture.repeat.copy( this.repeat );
  7567. texture.generateMipmaps = this.generateMipmaps;
  7568. texture.premultiplyAlpha = this.premultiplyAlpha;
  7569. texture.flipY = this.flipY;
  7570. texture.unpackAlignment = this.unpackAlignment;
  7571. return texture;
  7572. },
  7573. dispose: function () {
  7574. this.dispatchEvent( { type: 'dispose' } );
  7575. }
  7576. };
  7577. THREE.extend( THREE.Texture.prototype, THREE.EventDispatcher.prototype );
  7578. THREE.TextureIdCount = 0;
  7579. /**
  7580. * @author alteredq / http://alteredqualia.com/
  7581. */
  7582. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7583. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7584. this.image = { width: width, height: height };
  7585. this.mipmaps = mipmaps;
  7586. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7587. };
  7588. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7589. THREE.CompressedTexture.prototype.clone = function () {
  7590. var texture = new THREE.CompressedTexture();
  7591. THREE.Texture.prototype.clone.call( this, texture );
  7592. return texture;
  7593. };
  7594. /**
  7595. * @author alteredq / http://alteredqualia.com/
  7596. */
  7597. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7598. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7599. this.image = { data: data, width: width, height: height };
  7600. };
  7601. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7602. THREE.DataTexture.prototype.clone = function () {
  7603. var texture = new THREE.DataTexture();
  7604. THREE.Texture.prototype.clone.call( this, texture );
  7605. return texture;
  7606. };
  7607. /**
  7608. * @author mrdoob / http://mrdoob.com/
  7609. */
  7610. THREE.Particle = function ( material ) {
  7611. THREE.Object3D.call( this );
  7612. this.material = material;
  7613. };
  7614. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7615. THREE.Particle.prototype.clone = function ( object ) {
  7616. if ( object === undefined ) object = new THREE.Particle( this.material );
  7617. THREE.Object3D.prototype.clone.call( this, object );
  7618. return object;
  7619. };
  7620. /**
  7621. * @author alteredq / http://alteredqualia.com/
  7622. */
  7623. THREE.ParticleSystem = function ( geometry, material ) {
  7624. THREE.Object3D.call( this );
  7625. this.geometry = geometry;
  7626. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7627. this.sortParticles = false;
  7628. if ( this.geometry ) {
  7629. // calc bound radius
  7630. if( this.geometry.boundingSphere === null ) {
  7631. this.geometry.computeBoundingSphere();
  7632. }
  7633. }
  7634. this.frustumCulled = false;
  7635. };
  7636. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7637. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7638. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7639. object.sortParticles = this.sortParticles;
  7640. THREE.Object3D.prototype.clone.call( this, object );
  7641. return object;
  7642. };
  7643. /**
  7644. * @author mrdoob / http://mrdoob.com/
  7645. */
  7646. THREE.Line = function ( geometry, material, type ) {
  7647. THREE.Object3D.call( this );
  7648. this.geometry = geometry;
  7649. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7650. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7651. if ( this.geometry ) {
  7652. if ( ! this.geometry.boundingSphere ) {
  7653. this.geometry.computeBoundingSphere();
  7654. }
  7655. }
  7656. };
  7657. THREE.LineStrip = 0;
  7658. THREE.LinePieces = 1;
  7659. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7660. THREE.Line.prototype.clone = function ( object ) {
  7661. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7662. THREE.Object3D.prototype.clone.call( this, object );
  7663. return object;
  7664. };
  7665. /**
  7666. * @author mrdoob / http://mrdoob.com/
  7667. * @author alteredq / http://alteredqualia.com/
  7668. * @author mikael emtinger / http://gomo.se/
  7669. * @author jonobr1 / http://jonobr1.com/
  7670. */
  7671. THREE.Mesh = function ( geometry, material ) {
  7672. THREE.Object3D.call( this );
  7673. this.geometry = null;
  7674. this.material = null;
  7675. this.setGeometry( geometry );
  7676. this.setMaterial( material );
  7677. };
  7678. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7679. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  7680. if ( geometry !== undefined ) {
  7681. this.geometry = geometry;
  7682. if ( this.geometry.boundingSphere === null ) {
  7683. this.geometry.computeBoundingSphere();
  7684. }
  7685. this.updateMorphTargets();
  7686. }
  7687. };
  7688. THREE.Mesh.prototype.setMaterial = function ( material ) {
  7689. if ( material !== undefined ) {
  7690. this.material = material;
  7691. } else {
  7692. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7693. }
  7694. };
  7695. THREE.Mesh.prototype.updateMorphTargets = function () {
  7696. if ( this.geometry.morphTargets.length > 0 ) {
  7697. this.morphTargetBase = -1;
  7698. this.morphTargetForcedOrder = [];
  7699. this.morphTargetInfluences = [];
  7700. this.morphTargetDictionary = {};
  7701. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7702. this.morphTargetInfluences.push( 0 );
  7703. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7704. }
  7705. }
  7706. };
  7707. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7708. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7709. return this.morphTargetDictionary[ name ];
  7710. }
  7711. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7712. return 0;
  7713. };
  7714. THREE.Mesh.prototype.clone = function ( object ) {
  7715. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7716. THREE.Object3D.prototype.clone.call( this, object );
  7717. return object;
  7718. };
  7719. /**
  7720. * @author mikael emtinger / http://gomo.se/
  7721. * @author alteredq / http://alteredqualia.com/
  7722. */
  7723. THREE.Bone = function( belongsToSkin ) {
  7724. THREE.Object3D.call( this );
  7725. this.skin = belongsToSkin;
  7726. this.skinMatrix = new THREE.Matrix4();
  7727. };
  7728. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7729. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7730. // update local
  7731. if ( this.matrixAutoUpdate ) {
  7732. forceUpdate |= this.updateMatrix();
  7733. }
  7734. // update skin matrix
  7735. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7736. if( parentSkinMatrix ) {
  7737. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7738. } else {
  7739. this.skinMatrix.copy( this.matrix );
  7740. }
  7741. this.matrixWorldNeedsUpdate = false;
  7742. forceUpdate = true;
  7743. }
  7744. // update children
  7745. var child, i, l = this.children.length;
  7746. for ( i = 0; i < l; i ++ ) {
  7747. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7748. }
  7749. };
  7750. /**
  7751. * @author mikael emtinger / http://gomo.se/
  7752. * @author alteredq / http://alteredqualia.com/
  7753. */
  7754. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7755. THREE.Mesh.call( this, geometry, material );
  7756. //
  7757. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7758. // init bones
  7759. this.identityMatrix = new THREE.Matrix4();
  7760. this.bones = [];
  7761. this.boneMatrices = [];
  7762. var b, bone, gbone, p, q, s;
  7763. if ( this.geometry && this.geometry.bones !== undefined ) {
  7764. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7765. gbone = this.geometry.bones[ b ];
  7766. p = gbone.pos;
  7767. q = gbone.rotq;
  7768. s = gbone.scl;
  7769. bone = this.addBone();
  7770. bone.name = gbone.name;
  7771. bone.position.set( p[0], p[1], p[2] );
  7772. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7773. bone.useQuaternion = true;
  7774. if ( s !== undefined ) {
  7775. bone.scale.set( s[0], s[1], s[2] );
  7776. } else {
  7777. bone.scale.set( 1, 1, 1 );
  7778. }
  7779. }
  7780. for ( b = 0; b < this.bones.length; b ++ ) {
  7781. gbone = this.geometry.bones[ b ];
  7782. bone = this.bones[ b ];
  7783. if ( gbone.parent === -1 ) {
  7784. this.add( bone );
  7785. } else {
  7786. this.bones[ gbone.parent ].add( bone );
  7787. }
  7788. }
  7789. //
  7790. var nBones = this.bones.length;
  7791. if ( this.useVertexTexture ) {
  7792. // layout (1 matrix = 4 pixels)
  7793. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7794. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7795. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7796. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7797. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7798. var size;
  7799. if ( nBones > 256 )
  7800. size = 64;
  7801. else if ( nBones > 64 )
  7802. size = 32;
  7803. else if ( nBones > 16 )
  7804. size = 16;
  7805. else
  7806. size = 8;
  7807. this.boneTextureWidth = size;
  7808. this.boneTextureHeight = size;
  7809. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7810. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7811. this.boneTexture.minFilter = THREE.NearestFilter;
  7812. this.boneTexture.magFilter = THREE.NearestFilter;
  7813. this.boneTexture.generateMipmaps = false;
  7814. this.boneTexture.flipY = false;
  7815. } else {
  7816. this.boneMatrices = new Float32Array( 16 * nBones );
  7817. }
  7818. this.pose();
  7819. }
  7820. };
  7821. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7822. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7823. if ( bone === undefined ) {
  7824. bone = new THREE.Bone( this );
  7825. }
  7826. this.bones.push( bone );
  7827. return bone;
  7828. };
  7829. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7830. this.matrixAutoUpdate && this.updateMatrix();
  7831. // update matrixWorld
  7832. if ( this.matrixWorldNeedsUpdate || force ) {
  7833. if ( this.parent ) {
  7834. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7835. } else {
  7836. this.matrixWorld.copy( this.matrix );
  7837. }
  7838. this.matrixWorldNeedsUpdate = false;
  7839. force = true;
  7840. }
  7841. // update children
  7842. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7843. var child = this.children[ i ];
  7844. if ( child instanceof THREE.Bone ) {
  7845. child.update( this.identityMatrix, false );
  7846. } else {
  7847. child.updateMatrixWorld( true );
  7848. }
  7849. }
  7850. // make a snapshot of the bones' rest position
  7851. if ( this.boneInverses == undefined ) {
  7852. this.boneInverses = [];
  7853. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7854. var inverse = new THREE.Matrix4();
  7855. inverse.getInverse( this.bones[ b ].skinMatrix );
  7856. this.boneInverses.push( inverse );
  7857. }
  7858. }
  7859. // flatten bone matrices to array
  7860. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7861. // compute the offset between the current and the original transform;
  7862. //TODO: we could get rid of this multiplication step if the skinMatrix
  7863. // was already representing the offset; however, this requires some
  7864. // major changes to the animation system
  7865. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7866. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7867. }
  7868. if ( this.useVertexTexture ) {
  7869. this.boneTexture.needsUpdate = true;
  7870. }
  7871. };
  7872. THREE.SkinnedMesh.prototype.pose = function () {
  7873. this.updateMatrixWorld( true );
  7874. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7875. // normalize weights
  7876. var sw = this.geometry.skinWeights[ i ];
  7877. var scale = 1.0 / sw.lengthManhattan();
  7878. if ( scale !== Infinity ) {
  7879. sw.multiplyScalar( scale );
  7880. } else {
  7881. sw.set( 1 ); // this will be normalized by the shader anyway
  7882. }
  7883. }
  7884. };
  7885. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7886. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7887. THREE.Mesh.prototype.clone.call( this, object );
  7888. return object;
  7889. };
  7890. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7891. /**
  7892. * @author alteredq / http://alteredqualia.com/
  7893. */
  7894. THREE.MorphAnimMesh = function ( geometry, material ) {
  7895. THREE.Mesh.call( this, geometry, material );
  7896. // API
  7897. this.duration = 1000; // milliseconds
  7898. this.mirroredLoop = false;
  7899. this.time = 0;
  7900. // internals
  7901. this.lastKeyframe = 0;
  7902. this.currentKeyframe = 0;
  7903. this.direction = 1;
  7904. this.directionBackwards = false;
  7905. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7906. };
  7907. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7908. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7909. this.startKeyframe = start;
  7910. this.endKeyframe = end;
  7911. this.length = this.endKeyframe - this.startKeyframe + 1;
  7912. };
  7913. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7914. this.direction = 1;
  7915. this.directionBackwards = false;
  7916. };
  7917. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7918. this.direction = -1;
  7919. this.directionBackwards = true;
  7920. };
  7921. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7922. var geometry = this.geometry;
  7923. if ( ! geometry.animations ) geometry.animations = {};
  7924. var firstAnimation, animations = geometry.animations;
  7925. var pattern = /([a-z]+)(\d+)/;
  7926. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7927. var morph = geometry.morphTargets[ i ];
  7928. var parts = morph.name.match( pattern );
  7929. if ( parts && parts.length > 1 ) {
  7930. var label = parts[ 1 ];
  7931. var num = parts[ 2 ];
  7932. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7933. var animation = animations[ label ];
  7934. if ( i < animation.start ) animation.start = i;
  7935. if ( i > animation.end ) animation.end = i;
  7936. if ( ! firstAnimation ) firstAnimation = label;
  7937. }
  7938. }
  7939. geometry.firstAnimation = firstAnimation;
  7940. };
  7941. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7942. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7943. this.geometry.animations[ label ] = { start: start, end: end };
  7944. };
  7945. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7946. var animation = this.geometry.animations[ label ];
  7947. if ( animation ) {
  7948. this.setFrameRange( animation.start, animation.end );
  7949. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7950. this.time = 0;
  7951. } else {
  7952. console.warn( "animation[" + label + "] undefined" );
  7953. }
  7954. };
  7955. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7956. var frameTime = this.duration / this.length;
  7957. this.time += this.direction * delta;
  7958. if ( this.mirroredLoop ) {
  7959. if ( this.time > this.duration || this.time < 0 ) {
  7960. this.direction *= -1;
  7961. if ( this.time > this.duration ) {
  7962. this.time = this.duration;
  7963. this.directionBackwards = true;
  7964. }
  7965. if ( this.time < 0 ) {
  7966. this.time = 0;
  7967. this.directionBackwards = false;
  7968. }
  7969. }
  7970. } else {
  7971. this.time = this.time % this.duration;
  7972. if ( this.time < 0 ) this.time += this.duration;
  7973. }
  7974. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7975. if ( keyframe !== this.currentKeyframe ) {
  7976. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7977. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7978. this.morphTargetInfluences[ keyframe ] = 0;
  7979. this.lastKeyframe = this.currentKeyframe;
  7980. this.currentKeyframe = keyframe;
  7981. }
  7982. var mix = ( this.time % frameTime ) / frameTime;
  7983. if ( this.directionBackwards ) {
  7984. mix = 1 - mix;
  7985. }
  7986. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7987. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7988. };
  7989. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7990. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7991. object.duration = this.duration;
  7992. object.mirroredLoop = this.mirroredLoop;
  7993. object.time = this.time;
  7994. object.lastKeyframe = this.lastKeyframe;
  7995. object.currentKeyframe = this.currentKeyframe;
  7996. object.direction = this.direction;
  7997. object.directionBackwards = this.directionBackwards;
  7998. THREE.Mesh.prototype.clone.call( this, object );
  7999. return object;
  8000. };
  8001. /**
  8002. * @author alteredq / http://alteredqualia.com/
  8003. */
  8004. THREE.Ribbon = function ( geometry, material ) {
  8005. THREE.Object3D.call( this );
  8006. this.geometry = geometry;
  8007. this.material = material;
  8008. };
  8009. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8010. THREE.Ribbon.prototype.clone = function ( object ) {
  8011. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8012. THREE.Object3D.prototype.clone.call( this, object );
  8013. return object;
  8014. };
  8015. /**
  8016. * @author mikael emtinger / http://gomo.se/
  8017. * @author alteredq / http://alteredqualia.com/
  8018. * @author mrdoob / http://mrdoob.com/
  8019. */
  8020. THREE.LOD = function () {
  8021. THREE.Object3D.call( this );
  8022. this.objects = [];
  8023. };
  8024. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8025. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8026. if ( distance === undefined ) distance = 0;
  8027. distance = Math.abs( distance );
  8028. for ( var l = 0; l < this.objects.length; l ++ ) {
  8029. if ( distance < this.objects[ l ].distance ) {
  8030. break;
  8031. }
  8032. }
  8033. this.objects.splice( l, 0, { distance: distance, object: object } );
  8034. this.add( object );
  8035. };
  8036. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8037. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8038. if ( distance < this.objects[ i ].distance ) {
  8039. break;
  8040. }
  8041. }
  8042. return this.objects[ i - 1 ].object;
  8043. };
  8044. THREE.LOD.prototype.update = function () {
  8045. var v1 = new THREE.Vector3();
  8046. var v2 = new THREE.Vector3();
  8047. return function ( camera ) {
  8048. if ( this.objects.length > 1 ) {
  8049. v1.getPositionFromMatrix( camera.matrixWorld );
  8050. v2.getPositionFromMatrix( this.matrixWorld );
  8051. var distance = v1.distanceTo( v2 );
  8052. this.objects[ 0 ].object.visible = true;
  8053. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8054. if ( distance >= this.objects[ i ].distance ) {
  8055. this.objects[ i - 1 ].object.visible = false;
  8056. this.objects[ i ].object.visible = true;
  8057. } else {
  8058. break;
  8059. }
  8060. }
  8061. for( ; i < l; i ++ ) {
  8062. this.objects[ i ].object.visible = false;
  8063. }
  8064. }
  8065. };
  8066. }();
  8067. THREE.LOD.prototype.clone = function () {
  8068. // TODO
  8069. };
  8070. /**
  8071. * @author mikael emtinger / http://gomo.se/
  8072. * @author alteredq / http://alteredqualia.com/
  8073. */
  8074. THREE.Sprite = function ( material ) {
  8075. THREE.Object3D.call( this );
  8076. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8077. this.rotation3d = this.rotation;
  8078. this.rotation = 0;
  8079. };
  8080. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8081. /*
  8082. * Custom update matrix
  8083. */
  8084. THREE.Sprite.prototype.updateMatrix = function () {
  8085. this.matrix.setPosition( this.position );
  8086. this.rotation3d.set( 0, 0, this.rotation );
  8087. this.matrix.setRotationFromEuler( this.rotation3d );
  8088. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  8089. this.matrix.scale( this.scale );
  8090. }
  8091. this.matrixWorldNeedsUpdate = true;
  8092. };
  8093. THREE.Sprite.prototype.clone = function ( object ) {
  8094. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8095. THREE.Object3D.prototype.clone.call( this, object );
  8096. return object;
  8097. };
  8098. /**
  8099. * @author mrdoob / http://mrdoob.com/
  8100. */
  8101. THREE.Scene = function () {
  8102. THREE.Object3D.call( this );
  8103. this.fog = null;
  8104. this.overrideMaterial = null;
  8105. this.matrixAutoUpdate = false;
  8106. this.__objects = [];
  8107. this.__lights = [];
  8108. this.__objectsAdded = [];
  8109. this.__objectsRemoved = [];
  8110. };
  8111. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8112. THREE.Scene.prototype.__addObject = function ( object ) {
  8113. if ( object instanceof THREE.Light ) {
  8114. if ( this.__lights.indexOf( object ) === - 1 ) {
  8115. this.__lights.push( object );
  8116. }
  8117. if ( object.target && object.target.parent === undefined ) {
  8118. this.add( object.target );
  8119. }
  8120. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8121. if ( this.__objects.indexOf( object ) === - 1 ) {
  8122. this.__objects.push( object );
  8123. this.__objectsAdded.push( object );
  8124. // check if previously removed
  8125. var i = this.__objectsRemoved.indexOf( object );
  8126. if ( i !== -1 ) {
  8127. this.__objectsRemoved.splice( i, 1 );
  8128. }
  8129. }
  8130. }
  8131. for ( var c = 0; c < object.children.length; c ++ ) {
  8132. this.__addObject( object.children[ c ] );
  8133. }
  8134. };
  8135. THREE.Scene.prototype.__removeObject = function ( object ) {
  8136. if ( object instanceof THREE.Light ) {
  8137. var i = this.__lights.indexOf( object );
  8138. if ( i !== -1 ) {
  8139. this.__lights.splice( i, 1 );
  8140. }
  8141. } else if ( !( object instanceof THREE.Camera ) ) {
  8142. var i = this.__objects.indexOf( object );
  8143. if( i !== -1 ) {
  8144. this.__objects.splice( i, 1 );
  8145. this.__objectsRemoved.push( object );
  8146. // check if previously added
  8147. var ai = this.__objectsAdded.indexOf( object );
  8148. if ( ai !== -1 ) {
  8149. this.__objectsAdded.splice( ai, 1 );
  8150. }
  8151. }
  8152. }
  8153. for ( var c = 0; c < object.children.length; c ++ ) {
  8154. this.__removeObject( object.children[ c ] );
  8155. }
  8156. };
  8157. /**
  8158. * @author mrdoob / http://mrdoob.com/
  8159. * @author alteredq / http://alteredqualia.com/
  8160. */
  8161. THREE.Fog = function ( hex, near, far ) {
  8162. this.name = '';
  8163. this.color = new THREE.Color( hex );
  8164. this.near = ( near !== undefined ) ? near : 1;
  8165. this.far = ( far !== undefined ) ? far : 1000;
  8166. };
  8167. THREE.Fog.prototype.clone = function () {
  8168. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8169. };
  8170. /**
  8171. * @author mrdoob / http://mrdoob.com/
  8172. * @author alteredq / http://alteredqualia.com/
  8173. */
  8174. THREE.FogExp2 = function ( hex, density ) {
  8175. this.name = '';
  8176. this.color = new THREE.Color( hex );
  8177. this.density = ( density !== undefined ) ? density : 0.00025;
  8178. };
  8179. THREE.FogExp2.prototype.clone = function () {
  8180. return new THREE.FogExp2( this.color.getHex(), this.density );
  8181. };
  8182. /**
  8183. * @author mrdoob / http://mrdoob.com/
  8184. */
  8185. THREE.CanvasRenderer = function ( parameters ) {
  8186. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8187. var smoothstep = THREE.Math.smoothstep;
  8188. parameters = parameters || {};
  8189. var _this = this,
  8190. _renderData, _elements, _lights,
  8191. _projector = new THREE.Projector(),
  8192. _canvas = parameters.canvas !== undefined
  8193. ? parameters.canvas
  8194. : document.createElement( 'canvas' ),
  8195. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8196. _context = _canvas.getContext( '2d' ),
  8197. _clearColor = new THREE.Color( 0x000000 ),
  8198. _clearOpacity = 0,
  8199. _contextGlobalAlpha = 1,
  8200. _contextGlobalCompositeOperation = 0,
  8201. _contextStrokeStyle = null,
  8202. _contextFillStyle = null,
  8203. _contextLineWidth = null,
  8204. _contextLineCap = null,
  8205. _contextLineJoin = null,
  8206. _contextDashSize = null,
  8207. _contextGapSize = 0,
  8208. _v1, _v2, _v3, _v4,
  8209. _v5 = new THREE.RenderableVertex(),
  8210. _v6 = new THREE.RenderableVertex(),
  8211. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8212. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8213. _color = new THREE.Color(),
  8214. _color1 = new THREE.Color(),
  8215. _color2 = new THREE.Color(),
  8216. _color3 = new THREE.Color(),
  8217. _color4 = new THREE.Color(),
  8218. _diffuseColor = new THREE.Color(),
  8219. _emissiveColor = new THREE.Color(),
  8220. _lightColor = new THREE.Color(),
  8221. _patterns = {}, _imagedatas = {},
  8222. _near, _far,
  8223. _image, _uvs,
  8224. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8225. _clipBox = new THREE.Box2(),
  8226. _clearBox = new THREE.Box2(),
  8227. _elemBox = new THREE.Box2(),
  8228. _ambientLight = new THREE.Color(),
  8229. _directionalLights = new THREE.Color(),
  8230. _pointLights = new THREE.Color(),
  8231. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8232. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8233. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8234. _pixelMap = document.createElement( 'canvas' );
  8235. _pixelMap.width = _pixelMap.height = 2;
  8236. _pixelMapContext = _pixelMap.getContext( '2d' );
  8237. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8238. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8239. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8240. _pixelMapData = _pixelMapImage.data;
  8241. _gradientMap = document.createElement( 'canvas' );
  8242. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8243. _gradientMapContext = _gradientMap.getContext( '2d' );
  8244. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8245. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8246. _gradientMapQuality --; // Fix UVs
  8247. // dash+gap fallbacks for Firefox and everything else
  8248. if ( _context.setLineDash === undefined ) {
  8249. if ( _context.mozDash !== undefined ) {
  8250. _context.setLineDash = function ( values ) {
  8251. _context.mozDash = values[ 0 ] !== null ? values : null;
  8252. }
  8253. } else {
  8254. _context.setLineDash = function () {}
  8255. }
  8256. }
  8257. this.domElement = _canvas;
  8258. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8259. ? parameters.devicePixelRatio
  8260. : window.devicePixelRatio !== undefined
  8261. ? window.devicePixelRatio
  8262. : 1;
  8263. this.autoClear = true;
  8264. this.sortObjects = true;
  8265. this.sortElements = true;
  8266. this.info = {
  8267. render: {
  8268. vertices: 0,
  8269. faces: 0
  8270. }
  8271. }
  8272. // WebGLRenderer compatibility
  8273. this.supportsVertexTextures = function () {};
  8274. this.setFaceCulling = function () {};
  8275. this.setSize = function ( width, height ) {
  8276. _canvasWidth = width * this.devicePixelRatio;
  8277. _canvasHeight = height * this.devicePixelRatio;
  8278. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8279. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8280. _canvas.width = _canvasWidth;
  8281. _canvas.height = _canvasHeight;
  8282. _canvas.style.width = width + 'px';
  8283. _canvas.style.height = height + 'px';
  8284. _clipBox.set(
  8285. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8286. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8287. );
  8288. _clearBox.set(
  8289. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8290. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8291. );
  8292. _contextGlobalAlpha = 1;
  8293. _contextGlobalCompositeOperation = 0;
  8294. _contextStrokeStyle = null;
  8295. _contextFillStyle = null;
  8296. _contextLineWidth = null;
  8297. _contextLineCap = null;
  8298. _contextLineJoin = null;
  8299. };
  8300. this.setClearColor = function ( color, opacity ) {
  8301. _clearColor.copy( color );
  8302. _clearOpacity = opacity !== undefined ? opacity : 1;
  8303. _clearBox.set(
  8304. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8305. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8306. );
  8307. };
  8308. this.setClearColorHex = function ( hex, opacity ) {
  8309. _clearColor.setHex( hex );
  8310. _clearOpacity = opacity !== undefined ? opacity : 1;
  8311. _clearBox.set(
  8312. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8313. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8314. );
  8315. };
  8316. this.getMaxAnisotropy = function () {
  8317. return 0;
  8318. };
  8319. this.clear = function () {
  8320. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8321. if ( _clearBox.empty() === false ) {
  8322. _clearBox.intersect( _clipBox );
  8323. _clearBox.expandByScalar( 2 );
  8324. if ( _clearOpacity < 1 ) {
  8325. _context.clearRect(
  8326. _clearBox.min.x | 0,
  8327. _clearBox.min.y | 0,
  8328. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8329. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8330. );
  8331. }
  8332. if ( _clearOpacity > 0 ) {
  8333. setBlending( THREE.NormalBlending );
  8334. setOpacity( 1 );
  8335. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8336. _context.fillRect(
  8337. _clearBox.min.x | 0,
  8338. _clearBox.min.y | 0,
  8339. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8340. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8341. );
  8342. }
  8343. _clearBox.makeEmpty();
  8344. }
  8345. };
  8346. this.render = function ( scene, camera ) {
  8347. if ( camera instanceof THREE.Camera === false ) {
  8348. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8349. return;
  8350. }
  8351. if ( this.autoClear === true ) {
  8352. this.clear();
  8353. }
  8354. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8355. _this.info.render.vertices = 0;
  8356. _this.info.render.faces = 0;
  8357. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8358. _elements = _renderData.elements;
  8359. _lights = _renderData.lights;
  8360. /* DEBUG
  8361. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8362. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8363. */
  8364. calculateLights();
  8365. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8366. var element = _elements[ e ];
  8367. var material = element.material;
  8368. if ( material === undefined || material.visible === false ) continue;
  8369. _elemBox.makeEmpty();
  8370. if ( element instanceof THREE.RenderableParticle ) {
  8371. _v1 = element;
  8372. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8373. renderParticle( _v1, element, material );
  8374. } else if ( element instanceof THREE.RenderableLine ) {
  8375. _v1 = element.v1; _v2 = element.v2;
  8376. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8377. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8378. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8379. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8380. renderLine( _v1, _v2, element, material );
  8381. }
  8382. } else if ( element instanceof THREE.RenderableFace3 ) {
  8383. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8384. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8385. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8386. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8387. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8388. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8389. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8390. if ( material.overdraw === true ) {
  8391. expand( _v1.positionScreen, _v2.positionScreen );
  8392. expand( _v2.positionScreen, _v3.positionScreen );
  8393. expand( _v3.positionScreen, _v1.positionScreen );
  8394. }
  8395. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8396. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8397. } else if ( element instanceof THREE.RenderableFace4 ) {
  8398. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8399. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8400. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8401. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8402. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8403. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8404. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8405. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8406. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8407. _v5.positionScreen.copy( _v2.positionScreen );
  8408. _v6.positionScreen.copy( _v4.positionScreen );
  8409. if ( material.overdraw === true ) {
  8410. expand( _v1.positionScreen, _v2.positionScreen );
  8411. expand( _v2.positionScreen, _v4.positionScreen );
  8412. expand( _v4.positionScreen, _v1.positionScreen );
  8413. expand( _v3.positionScreen, _v5.positionScreen );
  8414. expand( _v3.positionScreen, _v6.positionScreen );
  8415. }
  8416. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8417. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8418. }
  8419. /* DEBUG
  8420. setLineWidth( 1 );
  8421. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8422. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8423. */
  8424. _clearBox.union( _elemBox );
  8425. }
  8426. /* DEBUG
  8427. setLineWidth( 1 );
  8428. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8429. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8430. */
  8431. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8432. //
  8433. function calculateLights() {
  8434. _ambientLight.setRGB( 0, 0, 0 );
  8435. _directionalLights.setRGB( 0, 0, 0 );
  8436. _pointLights.setRGB( 0, 0, 0 );
  8437. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8438. var light = _lights[ l ];
  8439. var lightColor = light.color;
  8440. if ( light instanceof THREE.AmbientLight ) {
  8441. _ambientLight.add( lightColor );
  8442. } else if ( light instanceof THREE.DirectionalLight ) {
  8443. // for particles
  8444. _directionalLights.add( lightColor );
  8445. } else if ( light instanceof THREE.PointLight ) {
  8446. // for particles
  8447. _pointLights.add( lightColor );
  8448. }
  8449. }
  8450. }
  8451. function calculateLight( position, normal, color ) {
  8452. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8453. var light = _lights[ l ];
  8454. _lightColor.copy( light.color );
  8455. if ( light instanceof THREE.DirectionalLight ) {
  8456. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8457. var amount = normal.dot( lightPosition );
  8458. if ( amount <= 0 ) continue;
  8459. amount *= light.intensity;
  8460. color.add( _lightColor.multiplyScalar( amount ) );
  8461. } else if ( light instanceof THREE.PointLight ) {
  8462. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8463. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8464. if ( amount <= 0 ) continue;
  8465. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8466. if ( amount == 0 ) continue;
  8467. amount *= light.intensity;
  8468. color.add( _lightColor.multiplyScalar( amount ) );
  8469. }
  8470. }
  8471. }
  8472. function renderParticle( v1, element, material ) {
  8473. setOpacity( material.opacity );
  8474. setBlending( material.blending );
  8475. var width, height, scaleX, scaleY,
  8476. bitmap, bitmapWidth, bitmapHeight;
  8477. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8478. if ( material.map === null ) {
  8479. scaleX = element.object.scale.x;
  8480. scaleY = element.object.scale.y;
  8481. // TODO: Be able to disable this
  8482. scaleX *= element.scale.x * _canvasWidthHalf;
  8483. scaleY *= element.scale.y * _canvasHeightHalf;
  8484. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8485. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8486. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8487. return;
  8488. }
  8489. setFillStyle( material.color.getStyle() );
  8490. _context.save();
  8491. _context.translate( v1.x, v1.y );
  8492. _context.rotate( - element.rotation );
  8493. _context.scale( scaleX, scaleY );
  8494. _context.fillRect( -1, -1, 2, 2 );
  8495. _context.restore();
  8496. } else {
  8497. bitmap = material.map.image;
  8498. bitmapWidth = bitmap.width >> 1;
  8499. bitmapHeight = bitmap.height >> 1;
  8500. scaleX = element.scale.x * _canvasWidthHalf;
  8501. scaleY = element.scale.y * _canvasHeightHalf;
  8502. width = scaleX * bitmapWidth;
  8503. height = scaleY * bitmapHeight;
  8504. // TODO: Rotations break this...
  8505. _elemBox.min.set( v1.x - width, v1.y - height );
  8506. _elemBox.max.set( v1.x + width, v1.y + height );
  8507. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8508. return;
  8509. }
  8510. _context.save();
  8511. _context.translate( v1.x, v1.y );
  8512. _context.rotate( - element.rotation );
  8513. _context.scale( scaleX, - scaleY );
  8514. _context.translate( - bitmapWidth, - bitmapHeight );
  8515. _context.drawImage( bitmap, 0, 0 );
  8516. _context.restore();
  8517. }
  8518. /* DEBUG
  8519. setStrokeStyle( 'rgb(255,255,0)' );
  8520. _context.beginPath();
  8521. _context.moveTo( v1.x - 10, v1.y );
  8522. _context.lineTo( v1.x + 10, v1.y );
  8523. _context.moveTo( v1.x, v1.y - 10 );
  8524. _context.lineTo( v1.x, v1.y + 10 );
  8525. _context.stroke();
  8526. */
  8527. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8528. width = element.scale.x * _canvasWidthHalf;
  8529. height = element.scale.y * _canvasHeightHalf;
  8530. _elemBox.min.set( v1.x - width, v1.y - height );
  8531. _elemBox.max.set( v1.x + width, v1.y + height );
  8532. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8533. return;
  8534. }
  8535. setStrokeStyle( material.color.getStyle() );
  8536. setFillStyle( material.color.getStyle() );
  8537. _context.save();
  8538. _context.translate( v1.x, v1.y );
  8539. _context.rotate( - element.rotation );
  8540. _context.scale( width, height );
  8541. material.program( _context );
  8542. _context.restore();
  8543. }
  8544. }
  8545. function renderLine( v1, v2, element, material ) {
  8546. setOpacity( material.opacity );
  8547. setBlending( material.blending );
  8548. _context.beginPath();
  8549. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8550. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8551. if ( material instanceof THREE.LineBasicMaterial ) {
  8552. setLineWidth( material.linewidth );
  8553. setLineCap( material.linecap );
  8554. setLineJoin( material.linejoin );
  8555. setStrokeStyle( material.color.getStyle() );
  8556. _context.stroke();
  8557. _elemBox.expandByScalar( material.linewidth * 2 );
  8558. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8559. setLineWidth( material.linewidth );
  8560. setLineCap( material.linecap );
  8561. setLineJoin( material.linejoin );
  8562. setStrokeStyle( material.color.getStyle() );
  8563. setDashAndGap( material.dashSize, material.gapSize );
  8564. _context.stroke();
  8565. _elemBox.expandByScalar( material.linewidth * 2 );
  8566. setDashAndGap( null, null );
  8567. }
  8568. }
  8569. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8570. _this.info.render.vertices += 3;
  8571. _this.info.render.faces ++;
  8572. setOpacity( material.opacity );
  8573. setBlending( material.blending );
  8574. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8575. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8576. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8577. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8578. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8579. _diffuseColor.copy( material.color );
  8580. _emissiveColor.copy( material.emissive );
  8581. if ( material.vertexColors === THREE.FaceColors ) {
  8582. _diffuseColor.multiply( element.color );
  8583. }
  8584. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8585. _color1.copy( _ambientLight );
  8586. _color2.copy( _ambientLight );
  8587. _color3.copy( _ambientLight );
  8588. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8589. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8590. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8591. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8592. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8593. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8594. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8595. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8596. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8597. } else {
  8598. _color.copy( _ambientLight );
  8599. calculateLight( element.centroidModel, element.normalModel, _color );
  8600. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8601. material.wireframe === true
  8602. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8603. : fillPath( _color );
  8604. }
  8605. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8606. if ( material.map !== null ) {
  8607. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8608. _uvs = element.uvs[ 0 ];
  8609. 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 );
  8610. }
  8611. } else if ( material.envMap !== null ) {
  8612. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8613. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8614. _uv1x = 0.5 * _vector3.x + 0.5;
  8615. _uv1y = 0.5 * _vector3.y + 0.5;
  8616. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8617. _uv2x = 0.5 * _vector3.x + 0.5;
  8618. _uv2y = 0.5 * _vector3.y + 0.5;
  8619. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8620. _uv3x = 0.5 * _vector3.x + 0.5;
  8621. _uv3y = 0.5 * _vector3.y + 0.5;
  8622. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8623. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8624. }*/
  8625. } else {
  8626. _color.copy( material.color );
  8627. if ( material.vertexColors === THREE.FaceColors ) {
  8628. _color.multiply( element.color );
  8629. }
  8630. material.wireframe === true
  8631. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8632. : fillPath( _color );
  8633. }
  8634. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8635. _near = camera.near;
  8636. _far = camera.far;
  8637. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8638. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8639. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8640. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8641. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8642. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8643. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8644. var normal;
  8645. if ( material.shading == THREE.FlatShading ) {
  8646. normal = element.normalModelView;
  8647. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8648. material.wireframe === true
  8649. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8650. : fillPath( _color );
  8651. } else if ( material.shading == THREE.SmoothShading ) {
  8652. normal = element.vertexNormalsModelView[ uv1 ];
  8653. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8654. normal = element.vertexNormalsModelView[ uv2 ];
  8655. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8656. normal = element.vertexNormalsModelView[ uv3 ];
  8657. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8658. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8659. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8660. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8661. }
  8662. }
  8663. }
  8664. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8665. _this.info.render.vertices += 4;
  8666. _this.info.render.faces ++;
  8667. setOpacity( material.opacity );
  8668. setBlending( material.blending );
  8669. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8670. // Let renderFace3() handle this
  8671. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8672. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8673. return;
  8674. }
  8675. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8676. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8677. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8678. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8679. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8680. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8681. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8682. _diffuseColor.copy( material.color );
  8683. _emissiveColor.copy( material.emissive );
  8684. if ( material.vertexColors === THREE.FaceColors ) {
  8685. _diffuseColor.multiply( element.color );
  8686. }
  8687. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8688. _color1.copy( _ambientLight );
  8689. _color2.copy( _ambientLight );
  8690. _color3.copy( _ambientLight );
  8691. _color4.copy( _ambientLight );
  8692. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8693. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8694. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8695. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8696. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8697. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8698. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8699. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8700. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8701. // TODO: UVs are incorrect, v4->v3?
  8702. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8703. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8704. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8705. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8706. } else {
  8707. _color.copy( _ambientLight );
  8708. calculateLight( element.centroidModel, element.normalModel, _color );
  8709. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8710. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8711. material.wireframe === true
  8712. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8713. : fillPath( _color );
  8714. }
  8715. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8716. _color.copy( material.color );
  8717. if ( material.vertexColors === THREE.FaceColors ) {
  8718. _color.multiply( element.color );
  8719. }
  8720. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8721. material.wireframe === true
  8722. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8723. : fillPath( _color );
  8724. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8725. var normal;
  8726. if ( material.shading == THREE.FlatShading ) {
  8727. normal = element.normalModelView;
  8728. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8729. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8730. material.wireframe === true
  8731. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8732. : fillPath( _color );
  8733. } else if ( material.shading == THREE.SmoothShading ) {
  8734. normal = element.vertexNormalsModelView[ 0 ];
  8735. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8736. normal = element.vertexNormalsModelView[ 1 ];
  8737. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8738. normal = element.vertexNormalsModelView[ 3 ];
  8739. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8740. normal = element.vertexNormalsModelView[ 2 ];
  8741. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8742. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8743. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8744. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8745. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8746. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8747. }
  8748. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8749. _near = camera.near;
  8750. _far = camera.far;
  8751. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8752. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8753. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8754. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8755. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8756. // TODO: UVs are incorrect, v4->v3?
  8757. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8758. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8759. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8760. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8761. }
  8762. }
  8763. //
  8764. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8765. _context.beginPath();
  8766. _context.moveTo( x0, y0 );
  8767. _context.lineTo( x1, y1 );
  8768. _context.lineTo( x2, y2 );
  8769. _context.closePath();
  8770. }
  8771. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8772. _context.beginPath();
  8773. _context.moveTo( x0, y0 );
  8774. _context.lineTo( x1, y1 );
  8775. _context.lineTo( x2, y2 );
  8776. _context.lineTo( x3, y3 );
  8777. _context.closePath();
  8778. }
  8779. function strokePath( color, linewidth, linecap, linejoin ) {
  8780. setLineWidth( linewidth );
  8781. setLineCap( linecap );
  8782. setLineJoin( linejoin );
  8783. setStrokeStyle( color.getStyle() );
  8784. _context.stroke();
  8785. _elemBox.expandByScalar( linewidth * 2 );
  8786. }
  8787. function fillPath( color ) {
  8788. setFillStyle( color.getStyle() );
  8789. _context.fill();
  8790. }
  8791. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8792. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8793. if ( texture.needsUpdate === true ) {
  8794. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8795. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8796. _patterns[ texture.id ] = _context.createPattern(
  8797. texture.image, repeatX === true && repeatY === true
  8798. ? 'repeat'
  8799. : repeatX === true && repeatY === false
  8800. ? 'repeat-x'
  8801. : repeatX === false && repeatY === true
  8802. ? 'repeat-y'
  8803. : 'no-repeat'
  8804. );
  8805. texture.needsUpdate = false;
  8806. }
  8807. _patterns[ texture.id ] === undefined
  8808. ? setFillStyle( 'rgba(0,0,0,1)' )
  8809. : setFillStyle( _patterns[ texture.id ] );
  8810. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8811. var a, b, c, d, e, f, det, idet,
  8812. offsetX = texture.offset.x / texture.repeat.x,
  8813. offsetY = texture.offset.y / texture.repeat.y,
  8814. width = texture.image.width * texture.repeat.x,
  8815. height = texture.image.height * texture.repeat.y;
  8816. u0 = ( u0 + offsetX ) * width;
  8817. v0 = ( 1.0 - v0 + offsetY ) * height;
  8818. u1 = ( u1 + offsetX ) * width;
  8819. v1 = ( 1.0 - v1 + offsetY ) * height;
  8820. u2 = ( u2 + offsetX ) * width;
  8821. v2 = ( 1.0 - v2 + offsetY ) * height;
  8822. x1 -= x0; y1 -= y0;
  8823. x2 -= x0; y2 -= y0;
  8824. u1 -= u0; v1 -= v0;
  8825. u2 -= u0; v2 -= v0;
  8826. det = u1 * v2 - u2 * v1;
  8827. if ( det === 0 ) {
  8828. if ( _imagedatas[ texture.id ] === undefined ) {
  8829. var canvas = document.createElement( 'canvas' )
  8830. canvas.width = texture.image.width;
  8831. canvas.height = texture.image.height;
  8832. var context = canvas.getContext( '2d' );
  8833. context.drawImage( texture.image, 0, 0 );
  8834. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8835. }
  8836. var data = _imagedatas[ texture.id ];
  8837. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8838. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8839. fillPath( _color );
  8840. return;
  8841. }
  8842. idet = 1 / det;
  8843. a = ( v2 * x1 - v1 * x2 ) * idet;
  8844. b = ( v2 * y1 - v1 * y2 ) * idet;
  8845. c = ( u1 * x2 - u2 * x1 ) * idet;
  8846. d = ( u1 * y2 - u2 * y1 ) * idet;
  8847. e = x0 - a * u0 - c * v0;
  8848. f = y0 - b * u0 - d * v0;
  8849. _context.save();
  8850. _context.transform( a, b, c, d, e, f );
  8851. _context.fill();
  8852. _context.restore();
  8853. }
  8854. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8855. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8856. var a, b, c, d, e, f, det, idet,
  8857. width = image.width - 1,
  8858. height = image.height - 1;
  8859. u0 *= width; v0 *= height;
  8860. u1 *= width; v1 *= height;
  8861. u2 *= width; v2 *= height;
  8862. x1 -= x0; y1 -= y0;
  8863. x2 -= x0; y2 -= y0;
  8864. u1 -= u0; v1 -= v0;
  8865. u2 -= u0; v2 -= v0;
  8866. det = u1 * v2 - u2 * v1;
  8867. idet = 1 / det;
  8868. a = ( v2 * x1 - v1 * x2 ) * idet;
  8869. b = ( v2 * y1 - v1 * y2 ) * idet;
  8870. c = ( u1 * x2 - u2 * x1 ) * idet;
  8871. d = ( u1 * y2 - u2 * y1 ) * idet;
  8872. e = x0 - a * u0 - c * v0;
  8873. f = y0 - b * u0 - d * v0;
  8874. _context.save();
  8875. _context.transform( a, b, c, d, e, f );
  8876. _context.clip();
  8877. _context.drawImage( image, 0, 0 );
  8878. _context.restore();
  8879. }
  8880. function getGradientTexture( color1, color2, color3, color4 ) {
  8881. // http://mrdoob.com/blog/post/710
  8882. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8883. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8884. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8885. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8886. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8887. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8888. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8889. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8890. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8891. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8892. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8893. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8894. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8895. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8896. return _gradientMap;
  8897. }
  8898. // Hide anti-alias gaps
  8899. function expand( v1, v2 ) {
  8900. var x = v2.x - v1.x, y = v2.y - v1.y,
  8901. det = x * x + y * y, idet;
  8902. if ( det === 0 ) return;
  8903. idet = 1 / Math.sqrt( det );
  8904. x *= idet; y *= idet;
  8905. v2.x += x; v2.y += y;
  8906. v1.x -= x; v1.y -= y;
  8907. }
  8908. };
  8909. // Context cached methods.
  8910. function setOpacity( value ) {
  8911. if ( _contextGlobalAlpha !== value ) {
  8912. _context.globalAlpha = value;
  8913. _contextGlobalAlpha = value;
  8914. }
  8915. }
  8916. function setBlending( value ) {
  8917. if ( _contextGlobalCompositeOperation !== value ) {
  8918. if ( value === THREE.NormalBlending ) {
  8919. _context.globalCompositeOperation = 'source-over';
  8920. } else if ( value === THREE.AdditiveBlending ) {
  8921. _context.globalCompositeOperation = 'lighter';
  8922. } else if ( value === THREE.SubtractiveBlending ) {
  8923. _context.globalCompositeOperation = 'darker';
  8924. }
  8925. _contextGlobalCompositeOperation = value;
  8926. }
  8927. }
  8928. function setLineWidth( value ) {
  8929. if ( _contextLineWidth !== value ) {
  8930. _context.lineWidth = value;
  8931. _contextLineWidth = value;
  8932. }
  8933. }
  8934. function setLineCap( value ) {
  8935. // "butt", "round", "square"
  8936. if ( _contextLineCap !== value ) {
  8937. _context.lineCap = value;
  8938. _contextLineCap = value;
  8939. }
  8940. }
  8941. function setLineJoin( value ) {
  8942. // "round", "bevel", "miter"
  8943. if ( _contextLineJoin !== value ) {
  8944. _context.lineJoin = value;
  8945. _contextLineJoin = value;
  8946. }
  8947. }
  8948. function setStrokeStyle( value ) {
  8949. if ( _contextStrokeStyle !== value ) {
  8950. _context.strokeStyle = value;
  8951. _contextStrokeStyle = value;
  8952. }
  8953. }
  8954. function setFillStyle( value ) {
  8955. if ( _contextFillStyle !== value ) {
  8956. _context.fillStyle = value;
  8957. _contextFillStyle = value;
  8958. }
  8959. }
  8960. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8961. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8962. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8963. _contextDashSize = dashSizeValue;
  8964. _contextGapSize = gapSizeValue;
  8965. }
  8966. }
  8967. };
  8968. /**
  8969. * @author alteredq / http://alteredqualia.com/
  8970. * @author mrdoob / http://mrdoob.com/
  8971. * @author mikael emtinger / http://gomo.se/
  8972. */
  8973. THREE.ShaderChunk = {
  8974. // FOG
  8975. fog_pars_fragment: [
  8976. "#ifdef USE_FOG",
  8977. "uniform vec3 fogColor;",
  8978. "#ifdef FOG_EXP2",
  8979. "uniform float fogDensity;",
  8980. "#else",
  8981. "uniform float fogNear;",
  8982. "uniform float fogFar;",
  8983. "#endif",
  8984. "#endif"
  8985. ].join("\n"),
  8986. fog_fragment: [
  8987. "#ifdef USE_FOG",
  8988. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8989. "#ifdef FOG_EXP2",
  8990. "const float LOG2 = 1.442695;",
  8991. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8992. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8993. "#else",
  8994. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8995. "#endif",
  8996. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8997. "#endif"
  8998. ].join("\n"),
  8999. // ENVIRONMENT MAP
  9000. envmap_pars_fragment: [
  9001. "#ifdef USE_ENVMAP",
  9002. "uniform float reflectivity;",
  9003. "uniform samplerCube envMap;",
  9004. "uniform float flipEnvMap;",
  9005. "uniform int combine;",
  9006. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9007. "uniform bool useRefract;",
  9008. "uniform float refractionRatio;",
  9009. "#else",
  9010. "varying vec3 vReflect;",
  9011. "#endif",
  9012. "#endif"
  9013. ].join("\n"),
  9014. envmap_fragment: [
  9015. "#ifdef USE_ENVMAP",
  9016. "vec3 reflectVec;",
  9017. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9018. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9019. "if ( useRefract ) {",
  9020. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9021. "} else { ",
  9022. "reflectVec = reflect( cameraToVertex, normal );",
  9023. "}",
  9024. "#else",
  9025. "reflectVec = vReflect;",
  9026. "#endif",
  9027. "#ifdef DOUBLE_SIDED",
  9028. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9029. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9030. "#else",
  9031. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9032. "#endif",
  9033. "#ifdef GAMMA_INPUT",
  9034. "cubeColor.xyz *= cubeColor.xyz;",
  9035. "#endif",
  9036. "if ( combine == 1 ) {",
  9037. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9038. "} else if ( combine == 2 ) {",
  9039. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9040. "} else {",
  9041. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9042. "}",
  9043. "#endif"
  9044. ].join("\n"),
  9045. envmap_pars_vertex: [
  9046. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9047. "varying vec3 vReflect;",
  9048. "uniform float refractionRatio;",
  9049. "uniform bool useRefract;",
  9050. "#endif"
  9051. ].join("\n"),
  9052. worldpos_vertex : [
  9053. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9054. "#ifdef USE_SKINNING",
  9055. "vec4 worldPosition = modelMatrix * skinned;",
  9056. "#endif",
  9057. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9058. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9059. "#endif",
  9060. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9061. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9062. "#endif",
  9063. "#endif"
  9064. ].join("\n"),
  9065. envmap_vertex : [
  9066. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9067. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9068. "worldNormal = normalize( worldNormal );",
  9069. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9070. "if ( useRefract ) {",
  9071. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9072. "} else {",
  9073. "vReflect = reflect( cameraToVertex, worldNormal );",
  9074. "}",
  9075. "#endif"
  9076. ].join("\n"),
  9077. // COLOR MAP (particles)
  9078. map_particle_pars_fragment: [
  9079. "#ifdef USE_MAP",
  9080. "uniform sampler2D map;",
  9081. "#endif"
  9082. ].join("\n"),
  9083. map_particle_fragment: [
  9084. "#ifdef USE_MAP",
  9085. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9086. "#endif"
  9087. ].join("\n"),
  9088. // COLOR MAP (triangles)
  9089. map_pars_vertex: [
  9090. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9091. "varying vec2 vUv;",
  9092. "uniform vec4 offsetRepeat;",
  9093. "#endif"
  9094. ].join("\n"),
  9095. map_pars_fragment: [
  9096. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9097. "varying vec2 vUv;",
  9098. "#endif",
  9099. "#ifdef USE_MAP",
  9100. "uniform sampler2D map;",
  9101. "#endif"
  9102. ].join("\n"),
  9103. map_vertex: [
  9104. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9105. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9106. "#endif"
  9107. ].join("\n"),
  9108. map_fragment: [
  9109. "#ifdef USE_MAP",
  9110. "vec4 texelColor = texture2D( map, vUv );",
  9111. "#ifdef GAMMA_INPUT",
  9112. "texelColor.xyz *= texelColor.xyz;",
  9113. "#endif",
  9114. "gl_FragColor = gl_FragColor * texelColor;",
  9115. "#endif"
  9116. ].join("\n"),
  9117. // LIGHT MAP
  9118. lightmap_pars_fragment: [
  9119. "#ifdef USE_LIGHTMAP",
  9120. "varying vec2 vUv2;",
  9121. "uniform sampler2D lightMap;",
  9122. "#endif"
  9123. ].join("\n"),
  9124. lightmap_pars_vertex: [
  9125. "#ifdef USE_LIGHTMAP",
  9126. "varying vec2 vUv2;",
  9127. "#endif"
  9128. ].join("\n"),
  9129. lightmap_fragment: [
  9130. "#ifdef USE_LIGHTMAP",
  9131. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9132. "#endif"
  9133. ].join("\n"),
  9134. lightmap_vertex: [
  9135. "#ifdef USE_LIGHTMAP",
  9136. "vUv2 = uv2;",
  9137. "#endif"
  9138. ].join("\n"),
  9139. // BUMP MAP
  9140. bumpmap_pars_fragment: [
  9141. "#ifdef USE_BUMPMAP",
  9142. "uniform sampler2D bumpMap;",
  9143. "uniform float bumpScale;",
  9144. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9145. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9146. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9147. "vec2 dHdxy_fwd() {",
  9148. "vec2 dSTdx = dFdx( vUv );",
  9149. "vec2 dSTdy = dFdy( vUv );",
  9150. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9151. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9152. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9153. "return vec2( dBx, dBy );",
  9154. "}",
  9155. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9156. "vec3 vSigmaX = dFdx( surf_pos );",
  9157. "vec3 vSigmaY = dFdy( surf_pos );",
  9158. "vec3 vN = surf_norm;", // normalized
  9159. "vec3 R1 = cross( vSigmaY, vN );",
  9160. "vec3 R2 = cross( vN, vSigmaX );",
  9161. "float fDet = dot( vSigmaX, R1 );",
  9162. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9163. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9164. "}",
  9165. "#endif"
  9166. ].join("\n"),
  9167. // NORMAL MAP
  9168. normalmap_pars_fragment: [
  9169. "#ifdef USE_NORMALMAP",
  9170. "uniform sampler2D normalMap;",
  9171. "uniform vec2 normalScale;",
  9172. // Per-Pixel Tangent Space Normal Mapping
  9173. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9174. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9175. "vec3 q0 = dFdx( eye_pos.xyz );",
  9176. "vec3 q1 = dFdy( eye_pos.xyz );",
  9177. "vec2 st0 = dFdx( vUv.st );",
  9178. "vec2 st1 = dFdy( vUv.st );",
  9179. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9180. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9181. "vec3 N = normalize( surf_norm );",
  9182. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9183. "mapN.xy = normalScale * mapN.xy;",
  9184. "mat3 tsn = mat3( S, T, N );",
  9185. "return normalize( tsn * mapN );",
  9186. "}",
  9187. "#endif"
  9188. ].join("\n"),
  9189. // SPECULAR MAP
  9190. specularmap_pars_fragment: [
  9191. "#ifdef USE_SPECULARMAP",
  9192. "uniform sampler2D specularMap;",
  9193. "#endif"
  9194. ].join("\n"),
  9195. specularmap_fragment: [
  9196. "float specularStrength;",
  9197. "#ifdef USE_SPECULARMAP",
  9198. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9199. "specularStrength = texelSpecular.r;",
  9200. "#else",
  9201. "specularStrength = 1.0;",
  9202. "#endif"
  9203. ].join("\n"),
  9204. // LIGHTS LAMBERT
  9205. lights_lambert_pars_vertex: [
  9206. "uniform vec3 ambient;",
  9207. "uniform vec3 diffuse;",
  9208. "uniform vec3 emissive;",
  9209. "uniform vec3 ambientLightColor;",
  9210. "#if MAX_DIR_LIGHTS > 0",
  9211. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9212. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9213. "#endif",
  9214. "#if MAX_HEMI_LIGHTS > 0",
  9215. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9216. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9217. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9218. "#endif",
  9219. "#if MAX_POINT_LIGHTS > 0",
  9220. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9221. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9222. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9223. "#endif",
  9224. "#if MAX_SPOT_LIGHTS > 0",
  9225. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9226. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9227. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9228. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9229. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9230. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9231. "#endif",
  9232. "#ifdef WRAP_AROUND",
  9233. "uniform vec3 wrapRGB;",
  9234. "#endif"
  9235. ].join("\n"),
  9236. lights_lambert_vertex: [
  9237. "vLightFront = vec3( 0.0 );",
  9238. "#ifdef DOUBLE_SIDED",
  9239. "vLightBack = vec3( 0.0 );",
  9240. "#endif",
  9241. "transformedNormal = normalize( transformedNormal );",
  9242. "#if MAX_DIR_LIGHTS > 0",
  9243. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9244. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9245. "vec3 dirVector = normalize( lDirection.xyz );",
  9246. "float dotProduct = dot( transformedNormal, dirVector );",
  9247. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9248. "#ifdef DOUBLE_SIDED",
  9249. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9250. "#ifdef WRAP_AROUND",
  9251. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9252. "#endif",
  9253. "#endif",
  9254. "#ifdef WRAP_AROUND",
  9255. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9256. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9257. "#ifdef DOUBLE_SIDED",
  9258. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9259. "#endif",
  9260. "#endif",
  9261. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9262. "#ifdef DOUBLE_SIDED",
  9263. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9264. "#endif",
  9265. "}",
  9266. "#endif",
  9267. "#if MAX_POINT_LIGHTS > 0",
  9268. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9269. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9270. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9271. "float lDistance = 1.0;",
  9272. "if ( pointLightDistance[ i ] > 0.0 )",
  9273. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9274. "lVector = normalize( lVector );",
  9275. "float dotProduct = dot( transformedNormal, lVector );",
  9276. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9277. "#ifdef DOUBLE_SIDED",
  9278. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9279. "#ifdef WRAP_AROUND",
  9280. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9281. "#endif",
  9282. "#endif",
  9283. "#ifdef WRAP_AROUND",
  9284. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9285. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9286. "#ifdef DOUBLE_SIDED",
  9287. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9288. "#endif",
  9289. "#endif",
  9290. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9291. "#ifdef DOUBLE_SIDED",
  9292. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9293. "#endif",
  9294. "}",
  9295. "#endif",
  9296. "#if MAX_SPOT_LIGHTS > 0",
  9297. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9298. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9299. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9300. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9301. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9302. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9303. "float lDistance = 1.0;",
  9304. "if ( spotLightDistance[ i ] > 0.0 )",
  9305. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9306. "lVector = normalize( lVector );",
  9307. "float dotProduct = dot( transformedNormal, lVector );",
  9308. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9309. "#ifdef DOUBLE_SIDED",
  9310. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9311. "#ifdef WRAP_AROUND",
  9312. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9313. "#endif",
  9314. "#endif",
  9315. "#ifdef WRAP_AROUND",
  9316. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9317. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9318. "#ifdef DOUBLE_SIDED",
  9319. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9320. "#endif",
  9321. "#endif",
  9322. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9323. "#ifdef DOUBLE_SIDED",
  9324. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9325. "#endif",
  9326. "}",
  9327. "}",
  9328. "#endif",
  9329. "#if MAX_HEMI_LIGHTS > 0",
  9330. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9331. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9332. "vec3 lVector = normalize( lDirection.xyz );",
  9333. "float dotProduct = dot( transformedNormal, lVector );",
  9334. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9335. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9336. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9337. "#ifdef DOUBLE_SIDED",
  9338. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9339. "#endif",
  9340. "}",
  9341. "#endif",
  9342. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9343. "#ifdef DOUBLE_SIDED",
  9344. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9345. "#endif"
  9346. ].join("\n"),
  9347. // LIGHTS PHONG
  9348. lights_phong_pars_vertex: [
  9349. "#ifndef PHONG_PER_PIXEL",
  9350. "#if MAX_POINT_LIGHTS > 0",
  9351. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9352. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9353. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9354. "#endif",
  9355. "#if MAX_SPOT_LIGHTS > 0",
  9356. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9357. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9358. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9359. "#endif",
  9360. "#endif",
  9361. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9362. "varying vec3 vWorldPosition;",
  9363. "#endif"
  9364. ].join("\n"),
  9365. lights_phong_vertex: [
  9366. "#ifndef PHONG_PER_PIXEL",
  9367. "#if MAX_POINT_LIGHTS > 0",
  9368. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9369. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9370. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9371. "float lDistance = 1.0;",
  9372. "if ( pointLightDistance[ i ] > 0.0 )",
  9373. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9374. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9375. "}",
  9376. "#endif",
  9377. "#if MAX_SPOT_LIGHTS > 0",
  9378. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9379. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9380. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9381. "float lDistance = 1.0;",
  9382. "if ( spotLightDistance[ i ] > 0.0 )",
  9383. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9384. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9385. "}",
  9386. "#endif",
  9387. "#endif",
  9388. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9389. "vWorldPosition = worldPosition.xyz;",
  9390. "#endif"
  9391. ].join("\n"),
  9392. lights_phong_pars_fragment: [
  9393. "uniform vec3 ambientLightColor;",
  9394. "#if MAX_DIR_LIGHTS > 0",
  9395. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9396. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9397. "#endif",
  9398. "#if MAX_HEMI_LIGHTS > 0",
  9399. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9400. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9401. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9402. "#endif",
  9403. "#if MAX_POINT_LIGHTS > 0",
  9404. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9405. "#ifdef PHONG_PER_PIXEL",
  9406. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9407. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9408. "#else",
  9409. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9410. "#endif",
  9411. "#endif",
  9412. "#if MAX_SPOT_LIGHTS > 0",
  9413. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9414. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9415. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9416. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9417. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9418. "#ifdef PHONG_PER_PIXEL",
  9419. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9420. "#else",
  9421. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9422. "#endif",
  9423. "#endif",
  9424. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9425. "varying vec3 vWorldPosition;",
  9426. "#endif",
  9427. "#ifdef WRAP_AROUND",
  9428. "uniform vec3 wrapRGB;",
  9429. "#endif",
  9430. "varying vec3 vViewPosition;",
  9431. "varying vec3 vNormal;"
  9432. ].join("\n"),
  9433. lights_phong_fragment: [
  9434. "vec3 normal = normalize( vNormal );",
  9435. "vec3 viewPosition = normalize( vViewPosition );",
  9436. "#ifdef DOUBLE_SIDED",
  9437. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9438. "#endif",
  9439. "#ifdef USE_NORMALMAP",
  9440. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9441. "#elif defined( USE_BUMPMAP )",
  9442. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9443. "#endif",
  9444. "#if MAX_POINT_LIGHTS > 0",
  9445. "vec3 pointDiffuse = vec3( 0.0 );",
  9446. "vec3 pointSpecular = vec3( 0.0 );",
  9447. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9448. "#ifdef PHONG_PER_PIXEL",
  9449. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9450. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9451. "float lDistance = 1.0;",
  9452. "if ( pointLightDistance[ i ] > 0.0 )",
  9453. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9454. "lVector = normalize( lVector );",
  9455. "#else",
  9456. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9457. "float lDistance = vPointLight[ i ].w;",
  9458. "#endif",
  9459. // diffuse
  9460. "float dotProduct = dot( normal, lVector );",
  9461. "#ifdef WRAP_AROUND",
  9462. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9463. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9464. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9465. "#else",
  9466. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9467. "#endif",
  9468. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9469. // specular
  9470. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9471. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9472. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9473. "#ifdef PHYSICALLY_BASED_SHADING",
  9474. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9475. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9476. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9477. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9478. "#else",
  9479. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9480. "#endif",
  9481. "}",
  9482. "#endif",
  9483. "#if MAX_SPOT_LIGHTS > 0",
  9484. "vec3 spotDiffuse = vec3( 0.0 );",
  9485. "vec3 spotSpecular = vec3( 0.0 );",
  9486. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9487. "#ifdef PHONG_PER_PIXEL",
  9488. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9489. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9490. "float lDistance = 1.0;",
  9491. "if ( spotLightDistance[ i ] > 0.0 )",
  9492. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9493. "lVector = normalize( lVector );",
  9494. "#else",
  9495. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9496. "float lDistance = vSpotLight[ i ].w;",
  9497. "#endif",
  9498. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9499. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9500. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9501. // diffuse
  9502. "float dotProduct = dot( normal, lVector );",
  9503. "#ifdef WRAP_AROUND",
  9504. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9505. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9506. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9507. "#else",
  9508. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9509. "#endif",
  9510. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9511. // specular
  9512. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9513. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9514. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9515. "#ifdef PHYSICALLY_BASED_SHADING",
  9516. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9517. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9518. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9519. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9520. "#else",
  9521. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9522. "#endif",
  9523. "}",
  9524. "}",
  9525. "#endif",
  9526. "#if MAX_DIR_LIGHTS > 0",
  9527. "vec3 dirDiffuse = vec3( 0.0 );",
  9528. "vec3 dirSpecular = vec3( 0.0 );" ,
  9529. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9530. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9531. "vec3 dirVector = normalize( lDirection.xyz );",
  9532. // diffuse
  9533. "float dotProduct = dot( normal, dirVector );",
  9534. "#ifdef WRAP_AROUND",
  9535. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9536. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9537. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9538. "#else",
  9539. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9540. "#endif",
  9541. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9542. // specular
  9543. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9544. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9545. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9546. "#ifdef PHYSICALLY_BASED_SHADING",
  9547. /*
  9548. // fresnel term from skin shader
  9549. "const float F0 = 0.128;",
  9550. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9551. "float exponential = pow( base, 5.0 );",
  9552. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9553. */
  9554. /*
  9555. // fresnel term from fresnel shader
  9556. "const float mFresnelBias = 0.08;",
  9557. "const float mFresnelScale = 0.3;",
  9558. "const float mFresnelPower = 5.0;",
  9559. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9560. */
  9561. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9562. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9563. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9564. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9565. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9566. "#else",
  9567. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9568. "#endif",
  9569. "}",
  9570. "#endif",
  9571. "#if MAX_HEMI_LIGHTS > 0",
  9572. "vec3 hemiDiffuse = vec3( 0.0 );",
  9573. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9574. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9575. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9576. "vec3 lVector = normalize( lDirection.xyz );",
  9577. // diffuse
  9578. "float dotProduct = dot( normal, lVector );",
  9579. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9580. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9581. "hemiDiffuse += diffuse * hemiColor;",
  9582. // specular (sky light)
  9583. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9584. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9585. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9586. // specular (ground light)
  9587. "vec3 lVectorGround = -lVector;",
  9588. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9589. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9590. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9591. "#ifdef PHYSICALLY_BASED_SHADING",
  9592. "float dotProductGround = dot( normal, lVectorGround );",
  9593. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9594. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9595. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9596. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9597. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9598. "#else",
  9599. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9600. "#endif",
  9601. "}",
  9602. "#endif",
  9603. "vec3 totalDiffuse = vec3( 0.0 );",
  9604. "vec3 totalSpecular = vec3( 0.0 );",
  9605. "#if MAX_DIR_LIGHTS > 0",
  9606. "totalDiffuse += dirDiffuse;",
  9607. "totalSpecular += dirSpecular;",
  9608. "#endif",
  9609. "#if MAX_HEMI_LIGHTS > 0",
  9610. "totalDiffuse += hemiDiffuse;",
  9611. "totalSpecular += hemiSpecular;",
  9612. "#endif",
  9613. "#if MAX_POINT_LIGHTS > 0",
  9614. "totalDiffuse += pointDiffuse;",
  9615. "totalSpecular += pointSpecular;",
  9616. "#endif",
  9617. "#if MAX_SPOT_LIGHTS > 0",
  9618. "totalDiffuse += spotDiffuse;",
  9619. "totalSpecular += spotSpecular;",
  9620. "#endif",
  9621. "#ifdef METAL",
  9622. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9623. "#else",
  9624. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9625. "#endif"
  9626. ].join("\n"),
  9627. // VERTEX COLORS
  9628. color_pars_fragment: [
  9629. "#ifdef USE_COLOR",
  9630. "varying vec3 vColor;",
  9631. "#endif"
  9632. ].join("\n"),
  9633. color_fragment: [
  9634. "#ifdef USE_COLOR",
  9635. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9636. "#endif"
  9637. ].join("\n"),
  9638. color_pars_vertex: [
  9639. "#ifdef USE_COLOR",
  9640. "varying vec3 vColor;",
  9641. "#endif"
  9642. ].join("\n"),
  9643. color_vertex: [
  9644. "#ifdef USE_COLOR",
  9645. "#ifdef GAMMA_INPUT",
  9646. "vColor = color * color;",
  9647. "#else",
  9648. "vColor = color;",
  9649. "#endif",
  9650. "#endif"
  9651. ].join("\n"),
  9652. // SKINNING
  9653. skinning_pars_vertex: [
  9654. "#ifdef USE_SKINNING",
  9655. "#ifdef BONE_TEXTURE",
  9656. "uniform sampler2D boneTexture;",
  9657. "mat4 getBoneMatrix( const in float i ) {",
  9658. "float j = i * 4.0;",
  9659. "float x = mod( j, N_BONE_PIXEL_X );",
  9660. "float y = floor( j / N_BONE_PIXEL_X );",
  9661. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9662. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9663. "y = dy * ( y + 0.5 );",
  9664. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9665. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9666. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9667. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9668. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9669. "return bone;",
  9670. "}",
  9671. "#else",
  9672. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9673. "mat4 getBoneMatrix( const in float i ) {",
  9674. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9675. "return bone;",
  9676. "}",
  9677. "#endif",
  9678. "#endif"
  9679. ].join("\n"),
  9680. skinbase_vertex: [
  9681. "#ifdef USE_SKINNING",
  9682. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9683. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9684. "#endif"
  9685. ].join("\n"),
  9686. skinning_vertex: [
  9687. "#ifdef USE_SKINNING",
  9688. "#ifdef USE_MORPHTARGETS",
  9689. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9690. "#else",
  9691. "vec4 skinVertex = vec4( position, 1.0 );",
  9692. "#endif",
  9693. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9694. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9695. "#endif"
  9696. ].join("\n"),
  9697. // MORPHING
  9698. morphtarget_pars_vertex: [
  9699. "#ifdef USE_MORPHTARGETS",
  9700. "#ifndef USE_MORPHNORMALS",
  9701. "uniform float morphTargetInfluences[ 8 ];",
  9702. "#else",
  9703. "uniform float morphTargetInfluences[ 4 ];",
  9704. "#endif",
  9705. "#endif"
  9706. ].join("\n"),
  9707. morphtarget_vertex: [
  9708. "#ifdef USE_MORPHTARGETS",
  9709. "vec3 morphed = vec3( 0.0 );",
  9710. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9711. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9712. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9713. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9714. "#ifndef USE_MORPHNORMALS",
  9715. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9716. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9717. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9718. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9719. "#endif",
  9720. "morphed += position;",
  9721. "#endif"
  9722. ].join("\n"),
  9723. default_vertex : [
  9724. "vec4 mvPosition;",
  9725. "#ifdef USE_SKINNING",
  9726. "mvPosition = modelViewMatrix * skinned;",
  9727. "#endif",
  9728. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9729. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9730. "#endif",
  9731. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9732. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9733. "#endif",
  9734. "gl_Position = projectionMatrix * mvPosition;"
  9735. ].join("\n"),
  9736. morphnormal_vertex: [
  9737. "#ifdef USE_MORPHNORMALS",
  9738. "vec3 morphedNormal = vec3( 0.0 );",
  9739. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9740. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9741. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9742. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9743. "morphedNormal += normal;",
  9744. "#endif"
  9745. ].join("\n"),
  9746. skinnormal_vertex: [
  9747. "#ifdef USE_SKINNING",
  9748. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9749. "skinMatrix += skinWeight.y * boneMatY;",
  9750. "#ifdef USE_MORPHNORMALS",
  9751. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9752. "#else",
  9753. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9754. "#endif",
  9755. "#endif"
  9756. ].join("\n"),
  9757. defaultnormal_vertex: [
  9758. "vec3 objectNormal;",
  9759. "#ifdef USE_SKINNING",
  9760. "objectNormal = skinnedNormal.xyz;",
  9761. "#endif",
  9762. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9763. "objectNormal = morphedNormal;",
  9764. "#endif",
  9765. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9766. "objectNormal = normal;",
  9767. "#endif",
  9768. "#ifdef FLIP_SIDED",
  9769. "objectNormal = -objectNormal;",
  9770. "#endif",
  9771. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9772. ].join("\n"),
  9773. // SHADOW MAP
  9774. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9775. // http://spidergl.org/example.php?id=6
  9776. // http://fabiensanglard.net/shadowmapping
  9777. shadowmap_pars_fragment: [
  9778. "#ifdef USE_SHADOWMAP",
  9779. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9780. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9781. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9782. "uniform float shadowBias[ MAX_SHADOWS ];",
  9783. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9784. "float unpackDepth( const in vec4 rgba_depth ) {",
  9785. "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 );",
  9786. "float depth = dot( rgba_depth, bit_shift );",
  9787. "return depth;",
  9788. "}",
  9789. "#endif"
  9790. ].join("\n"),
  9791. shadowmap_fragment: [
  9792. "#ifdef USE_SHADOWMAP",
  9793. "#ifdef SHADOWMAP_DEBUG",
  9794. "vec3 frustumColors[3];",
  9795. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9796. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9797. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9798. "#endif",
  9799. "#ifdef SHADOWMAP_CASCADE",
  9800. "int inFrustumCount = 0;",
  9801. "#endif",
  9802. "float fDepth;",
  9803. "vec3 shadowColor = vec3( 1.0 );",
  9804. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9805. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9806. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9807. // "if ( all( something, something ) )" using this instead
  9808. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9809. "bool inFrustum = all( inFrustumVec );",
  9810. // don't shadow pixels outside of light frustum
  9811. // use just first frustum (for cascades)
  9812. // don't shadow pixels behind far plane of light frustum
  9813. "#ifdef SHADOWMAP_CASCADE",
  9814. "inFrustumCount += int( inFrustum );",
  9815. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9816. "#else",
  9817. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9818. "#endif",
  9819. "bool frustumTest = all( frustumTestVec );",
  9820. "if ( frustumTest ) {",
  9821. "shadowCoord.z += shadowBias[ i ];",
  9822. "#if defined( SHADOWMAP_TYPE_PCF )",
  9823. // Percentage-close filtering
  9824. // (9 pixel kernel)
  9825. // http://fabiensanglard.net/shadowmappingPCF/
  9826. "float shadow = 0.0;",
  9827. /*
  9828. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9829. // must enroll loop manually
  9830. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9831. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9832. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9833. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9834. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9835. "float fDepth = unpackDepth( rgbaDepth );",
  9836. "if ( fDepth < shadowCoord.z )",
  9837. "shadow += 1.0;",
  9838. "}",
  9839. "shadow /= 9.0;",
  9840. */
  9841. "const float shadowDelta = 1.0 / 9.0;",
  9842. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9843. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9844. "float dx0 = -1.25 * xPixelOffset;",
  9845. "float dy0 = -1.25 * yPixelOffset;",
  9846. "float dx1 = 1.25 * xPixelOffset;",
  9847. "float dy1 = 1.25 * yPixelOffset;",
  9848. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9849. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9850. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9851. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9852. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9853. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9854. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9855. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9856. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9857. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9858. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9859. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9860. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9861. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9862. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9863. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9864. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9865. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9866. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9867. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9868. // Percentage-close filtering
  9869. // (9 pixel kernel)
  9870. // http://fabiensanglard.net/shadowmappingPCF/
  9871. "float shadow = 0.0;",
  9872. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9873. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9874. "float dx0 = -1.0 * xPixelOffset;",
  9875. "float dy0 = -1.0 * yPixelOffset;",
  9876. "float dx1 = 1.0 * xPixelOffset;",
  9877. "float dy1 = 1.0 * yPixelOffset;",
  9878. "mat3 shadowKernel;",
  9879. "mat3 depthKernel;",
  9880. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9881. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9882. "else shadowKernel[0][0] = 0.0;",
  9883. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9884. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9885. "else shadowKernel[0][1] = 0.0;",
  9886. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9887. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9888. "else shadowKernel[0][2] = 0.0;",
  9889. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9890. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9891. "else shadowKernel[1][0] = 0.0;",
  9892. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9893. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9894. "else shadowKernel[1][1] = 0.0;",
  9895. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9896. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9897. "else shadowKernel[1][2] = 0.0;",
  9898. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9899. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9900. "else shadowKernel[2][0] = 0.0;",
  9901. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9902. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9903. "else shadowKernel[2][1] = 0.0;",
  9904. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9905. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9906. "else shadowKernel[2][2] = 0.0;",
  9907. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9908. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9909. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9910. "vec4 shadowValues;",
  9911. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9912. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9913. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9914. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9915. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9916. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9917. "#else",
  9918. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9919. "float fDepth = unpackDepth( rgbaDepth );",
  9920. "if ( fDepth < shadowCoord.z )",
  9921. // spot with multiple shadows is darker
  9922. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9923. // spot with multiple shadows has the same color as single shadow spot
  9924. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9925. "#endif",
  9926. "}",
  9927. "#ifdef SHADOWMAP_DEBUG",
  9928. "#ifdef SHADOWMAP_CASCADE",
  9929. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9930. "#else",
  9931. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9932. "#endif",
  9933. "#endif",
  9934. "}",
  9935. "#ifdef GAMMA_OUTPUT",
  9936. "shadowColor *= shadowColor;",
  9937. "#endif",
  9938. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9939. "#endif"
  9940. ].join("\n"),
  9941. shadowmap_pars_vertex: [
  9942. "#ifdef USE_SHADOWMAP",
  9943. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9944. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9945. "#endif"
  9946. ].join("\n"),
  9947. shadowmap_vertex: [
  9948. "#ifdef USE_SHADOWMAP",
  9949. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9950. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9951. "}",
  9952. "#endif"
  9953. ].join("\n"),
  9954. // ALPHATEST
  9955. alphatest_fragment: [
  9956. "#ifdef ALPHATEST",
  9957. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9958. "#endif"
  9959. ].join("\n"),
  9960. // LINEAR SPACE
  9961. linear_to_gamma_fragment: [
  9962. "#ifdef GAMMA_OUTPUT",
  9963. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9964. "#endif"
  9965. ].join("\n")
  9966. };
  9967. THREE.UniformsUtils = {
  9968. merge: function ( uniforms ) {
  9969. var u, p, tmp, merged = {};
  9970. for ( u = 0; u < uniforms.length; u ++ ) {
  9971. tmp = this.clone( uniforms[ u ] );
  9972. for ( p in tmp ) {
  9973. merged[ p ] = tmp[ p ];
  9974. }
  9975. }
  9976. return merged;
  9977. },
  9978. clone: function ( uniforms_src ) {
  9979. var u, p, parameter, parameter_src, uniforms_dst = {};
  9980. for ( u in uniforms_src ) {
  9981. uniforms_dst[ u ] = {};
  9982. for ( p in uniforms_src[ u ] ) {
  9983. parameter_src = uniforms_src[ u ][ p ];
  9984. if ( parameter_src instanceof THREE.Color ||
  9985. parameter_src instanceof THREE.Vector2 ||
  9986. parameter_src instanceof THREE.Vector3 ||
  9987. parameter_src instanceof THREE.Vector4 ||
  9988. parameter_src instanceof THREE.Matrix4 ||
  9989. parameter_src instanceof THREE.Texture ) {
  9990. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9991. } else if ( parameter_src instanceof Array ) {
  9992. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9993. } else {
  9994. uniforms_dst[ u ][ p ] = parameter_src;
  9995. }
  9996. }
  9997. }
  9998. return uniforms_dst;
  9999. }
  10000. };
  10001. THREE.UniformsLib = {
  10002. common: {
  10003. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10004. "opacity" : { type: "f", value: 1.0 },
  10005. "map" : { type: "t", value: null },
  10006. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10007. "lightMap" : { type: "t", value: null },
  10008. "specularMap" : { type: "t", value: null },
  10009. "envMap" : { type: "t", value: null },
  10010. "flipEnvMap" : { type: "f", value: -1 },
  10011. "useRefract" : { type: "i", value: 0 },
  10012. "reflectivity" : { type: "f", value: 1.0 },
  10013. "refractionRatio" : { type: "f", value: 0.98 },
  10014. "combine" : { type: "i", value: 0 },
  10015. "morphTargetInfluences" : { type: "f", value: 0 }
  10016. },
  10017. bump: {
  10018. "bumpMap" : { type: "t", value: null },
  10019. "bumpScale" : { type: "f", value: 1 }
  10020. },
  10021. normalmap: {
  10022. "normalMap" : { type: "t", value: null },
  10023. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10024. },
  10025. fog : {
  10026. "fogDensity" : { type: "f", value: 0.00025 },
  10027. "fogNear" : { type: "f", value: 1 },
  10028. "fogFar" : { type: "f", value: 2000 },
  10029. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10030. },
  10031. lights: {
  10032. "ambientLightColor" : { type: "fv", value: [] },
  10033. "directionalLightDirection" : { type: "fv", value: [] },
  10034. "directionalLightColor" : { type: "fv", value: [] },
  10035. "hemisphereLightDirection" : { type: "fv", value: [] },
  10036. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10037. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10038. "pointLightColor" : { type: "fv", value: [] },
  10039. "pointLightPosition" : { type: "fv", value: [] },
  10040. "pointLightDistance" : { type: "fv1", value: [] },
  10041. "spotLightColor" : { type: "fv", value: [] },
  10042. "spotLightPosition" : { type: "fv", value: [] },
  10043. "spotLightDirection" : { type: "fv", value: [] },
  10044. "spotLightDistance" : { type: "fv1", value: [] },
  10045. "spotLightAngleCos" : { type: "fv1", value: [] },
  10046. "spotLightExponent" : { type: "fv1", value: [] }
  10047. },
  10048. particle: {
  10049. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10050. "opacity" : { type: "f", value: 1.0 },
  10051. "size" : { type: "f", value: 1.0 },
  10052. "scale" : { type: "f", value: 1.0 },
  10053. "map" : { type: "t", value: null },
  10054. "fogDensity" : { type: "f", value: 0.00025 },
  10055. "fogNear" : { type: "f", value: 1 },
  10056. "fogFar" : { type: "f", value: 2000 },
  10057. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10058. },
  10059. shadowmap: {
  10060. "shadowMap": { type: "tv", value: [] },
  10061. "shadowMapSize": { type: "v2v", value: [] },
  10062. "shadowBias" : { type: "fv1", value: [] },
  10063. "shadowDarkness": { type: "fv1", value: [] },
  10064. "shadowMatrix" : { type: "m4v", value: [] }
  10065. }
  10066. };
  10067. THREE.ShaderLib = {
  10068. 'basic': {
  10069. uniforms: THREE.UniformsUtils.merge( [
  10070. THREE.UniformsLib[ "common" ],
  10071. THREE.UniformsLib[ "fog" ],
  10072. THREE.UniformsLib[ "shadowmap" ]
  10073. ] ),
  10074. vertexShader: [
  10075. THREE.ShaderChunk[ "map_pars_vertex" ],
  10076. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10077. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10078. THREE.ShaderChunk[ "color_pars_vertex" ],
  10079. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10080. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10081. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10082. "void main() {",
  10083. THREE.ShaderChunk[ "map_vertex" ],
  10084. THREE.ShaderChunk[ "lightmap_vertex" ],
  10085. THREE.ShaderChunk[ "color_vertex" ],
  10086. THREE.ShaderChunk[ "skinbase_vertex" ],
  10087. "#ifdef USE_ENVMAP",
  10088. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10089. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10090. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10091. "#endif",
  10092. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10093. THREE.ShaderChunk[ "skinning_vertex" ],
  10094. THREE.ShaderChunk[ "default_vertex" ],
  10095. THREE.ShaderChunk[ "worldpos_vertex" ],
  10096. THREE.ShaderChunk[ "envmap_vertex" ],
  10097. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10098. "}"
  10099. ].join("\n"),
  10100. fragmentShader: [
  10101. "uniform vec3 diffuse;",
  10102. "uniform float opacity;",
  10103. THREE.ShaderChunk[ "color_pars_fragment" ],
  10104. THREE.ShaderChunk[ "map_pars_fragment" ],
  10105. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10106. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10107. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10108. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10109. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10110. "void main() {",
  10111. "gl_FragColor = vec4( diffuse, opacity );",
  10112. THREE.ShaderChunk[ "map_fragment" ],
  10113. THREE.ShaderChunk[ "alphatest_fragment" ],
  10114. THREE.ShaderChunk[ "specularmap_fragment" ],
  10115. THREE.ShaderChunk[ "lightmap_fragment" ],
  10116. THREE.ShaderChunk[ "color_fragment" ],
  10117. THREE.ShaderChunk[ "envmap_fragment" ],
  10118. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10119. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10120. THREE.ShaderChunk[ "fog_fragment" ],
  10121. "}"
  10122. ].join("\n")
  10123. },
  10124. 'lambert': {
  10125. uniforms: THREE.UniformsUtils.merge( [
  10126. THREE.UniformsLib[ "common" ],
  10127. THREE.UniformsLib[ "fog" ],
  10128. THREE.UniformsLib[ "lights" ],
  10129. THREE.UniformsLib[ "shadowmap" ],
  10130. {
  10131. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10132. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10133. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10134. }
  10135. ] ),
  10136. vertexShader: [
  10137. "#define LAMBERT",
  10138. "varying vec3 vLightFront;",
  10139. "#ifdef DOUBLE_SIDED",
  10140. "varying vec3 vLightBack;",
  10141. "#endif",
  10142. THREE.ShaderChunk[ "map_pars_vertex" ],
  10143. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10144. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10145. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10146. THREE.ShaderChunk[ "color_pars_vertex" ],
  10147. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10148. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10149. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10150. "void main() {",
  10151. THREE.ShaderChunk[ "map_vertex" ],
  10152. THREE.ShaderChunk[ "lightmap_vertex" ],
  10153. THREE.ShaderChunk[ "color_vertex" ],
  10154. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10155. THREE.ShaderChunk[ "skinbase_vertex" ],
  10156. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10157. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10158. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10159. THREE.ShaderChunk[ "skinning_vertex" ],
  10160. THREE.ShaderChunk[ "default_vertex" ],
  10161. THREE.ShaderChunk[ "worldpos_vertex" ],
  10162. THREE.ShaderChunk[ "envmap_vertex" ],
  10163. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10164. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10165. "}"
  10166. ].join("\n"),
  10167. fragmentShader: [
  10168. "uniform float opacity;",
  10169. "varying vec3 vLightFront;",
  10170. "#ifdef DOUBLE_SIDED",
  10171. "varying vec3 vLightBack;",
  10172. "#endif",
  10173. THREE.ShaderChunk[ "color_pars_fragment" ],
  10174. THREE.ShaderChunk[ "map_pars_fragment" ],
  10175. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10176. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10177. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10178. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10179. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10180. "void main() {",
  10181. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10182. THREE.ShaderChunk[ "map_fragment" ],
  10183. THREE.ShaderChunk[ "alphatest_fragment" ],
  10184. THREE.ShaderChunk[ "specularmap_fragment" ],
  10185. "#ifdef DOUBLE_SIDED",
  10186. //"float isFront = float( gl_FrontFacing );",
  10187. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10188. "if ( gl_FrontFacing )",
  10189. "gl_FragColor.xyz *= vLightFront;",
  10190. "else",
  10191. "gl_FragColor.xyz *= vLightBack;",
  10192. "#else",
  10193. "gl_FragColor.xyz *= vLightFront;",
  10194. "#endif",
  10195. THREE.ShaderChunk[ "lightmap_fragment" ],
  10196. THREE.ShaderChunk[ "color_fragment" ],
  10197. THREE.ShaderChunk[ "envmap_fragment" ],
  10198. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10199. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10200. THREE.ShaderChunk[ "fog_fragment" ],
  10201. "}"
  10202. ].join("\n")
  10203. },
  10204. 'phong': {
  10205. uniforms: THREE.UniformsUtils.merge( [
  10206. THREE.UniformsLib[ "common" ],
  10207. THREE.UniformsLib[ "bump" ],
  10208. THREE.UniformsLib[ "normalmap" ],
  10209. THREE.UniformsLib[ "fog" ],
  10210. THREE.UniformsLib[ "lights" ],
  10211. THREE.UniformsLib[ "shadowmap" ],
  10212. {
  10213. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10214. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10215. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10216. "shininess": { type: "f", value: 30 },
  10217. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10218. }
  10219. ] ),
  10220. vertexShader: [
  10221. "#define PHONG",
  10222. "varying vec3 vViewPosition;",
  10223. "varying vec3 vNormal;",
  10224. THREE.ShaderChunk[ "map_pars_vertex" ],
  10225. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10226. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10227. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10228. THREE.ShaderChunk[ "color_pars_vertex" ],
  10229. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10230. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10231. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10232. "void main() {",
  10233. THREE.ShaderChunk[ "map_vertex" ],
  10234. THREE.ShaderChunk[ "lightmap_vertex" ],
  10235. THREE.ShaderChunk[ "color_vertex" ],
  10236. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10237. THREE.ShaderChunk[ "skinbase_vertex" ],
  10238. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10239. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10240. "vNormal = normalize( transformedNormal );",
  10241. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10242. THREE.ShaderChunk[ "skinning_vertex" ],
  10243. THREE.ShaderChunk[ "default_vertex" ],
  10244. "vViewPosition = -mvPosition.xyz;",
  10245. THREE.ShaderChunk[ "worldpos_vertex" ],
  10246. THREE.ShaderChunk[ "envmap_vertex" ],
  10247. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10248. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10249. "}"
  10250. ].join("\n"),
  10251. fragmentShader: [
  10252. "uniform vec3 diffuse;",
  10253. "uniform float opacity;",
  10254. "uniform vec3 ambient;",
  10255. "uniform vec3 emissive;",
  10256. "uniform vec3 specular;",
  10257. "uniform float shininess;",
  10258. THREE.ShaderChunk[ "color_pars_fragment" ],
  10259. THREE.ShaderChunk[ "map_pars_fragment" ],
  10260. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10261. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10262. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10263. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10264. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10265. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10266. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10267. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10268. "void main() {",
  10269. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10270. THREE.ShaderChunk[ "map_fragment" ],
  10271. THREE.ShaderChunk[ "alphatest_fragment" ],
  10272. THREE.ShaderChunk[ "specularmap_fragment" ],
  10273. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10274. THREE.ShaderChunk[ "lightmap_fragment" ],
  10275. THREE.ShaderChunk[ "color_fragment" ],
  10276. THREE.ShaderChunk[ "envmap_fragment" ],
  10277. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10278. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10279. THREE.ShaderChunk[ "fog_fragment" ],
  10280. "}"
  10281. ].join("\n")
  10282. },
  10283. 'particle_basic': {
  10284. uniforms: THREE.UniformsUtils.merge( [
  10285. THREE.UniformsLib[ "particle" ],
  10286. THREE.UniformsLib[ "shadowmap" ]
  10287. ] ),
  10288. vertexShader: [
  10289. "uniform float size;",
  10290. "uniform float scale;",
  10291. THREE.ShaderChunk[ "color_pars_vertex" ],
  10292. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10293. "void main() {",
  10294. THREE.ShaderChunk[ "color_vertex" ],
  10295. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10296. "#ifdef USE_SIZEATTENUATION",
  10297. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10298. "#else",
  10299. "gl_PointSize = size;",
  10300. "#endif",
  10301. "gl_Position = projectionMatrix * mvPosition;",
  10302. THREE.ShaderChunk[ "worldpos_vertex" ],
  10303. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10304. "}"
  10305. ].join("\n"),
  10306. fragmentShader: [
  10307. "uniform vec3 psColor;",
  10308. "uniform float opacity;",
  10309. THREE.ShaderChunk[ "color_pars_fragment" ],
  10310. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10311. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10312. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10313. "void main() {",
  10314. "gl_FragColor = vec4( psColor, opacity );",
  10315. THREE.ShaderChunk[ "map_particle_fragment" ],
  10316. THREE.ShaderChunk[ "alphatest_fragment" ],
  10317. THREE.ShaderChunk[ "color_fragment" ],
  10318. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10319. THREE.ShaderChunk[ "fog_fragment" ],
  10320. "}"
  10321. ].join("\n")
  10322. },
  10323. 'dashed': {
  10324. uniforms: THREE.UniformsUtils.merge( [
  10325. THREE.UniformsLib[ "common" ],
  10326. THREE.UniformsLib[ "fog" ],
  10327. {
  10328. "scale": { type: "f", value: 1 },
  10329. "dashSize": { type: "f", value: 1 },
  10330. "totalSize": { type: "f", value: 2 }
  10331. }
  10332. ] ),
  10333. vertexShader: [
  10334. "uniform float scale;",
  10335. "attribute float lineDistance;",
  10336. "varying float vLineDistance;",
  10337. THREE.ShaderChunk[ "color_pars_vertex" ],
  10338. "void main() {",
  10339. THREE.ShaderChunk[ "color_vertex" ],
  10340. "vLineDistance = scale * lineDistance;",
  10341. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10342. "gl_Position = projectionMatrix * mvPosition;",
  10343. "}"
  10344. ].join("\n"),
  10345. fragmentShader: [
  10346. "uniform vec3 diffuse;",
  10347. "uniform float opacity;",
  10348. "uniform float dashSize;",
  10349. "uniform float totalSize;",
  10350. "varying float vLineDistance;",
  10351. THREE.ShaderChunk[ "color_pars_fragment" ],
  10352. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10353. "void main() {",
  10354. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10355. "discard;",
  10356. "}",
  10357. "gl_FragColor = vec4( diffuse, opacity );",
  10358. THREE.ShaderChunk[ "color_fragment" ],
  10359. THREE.ShaderChunk[ "fog_fragment" ],
  10360. "}"
  10361. ].join("\n")
  10362. },
  10363. 'depth': {
  10364. uniforms: {
  10365. "mNear": { type: "f", value: 1.0 },
  10366. "mFar" : { type: "f", value: 2000.0 },
  10367. "opacity" : { type: "f", value: 1.0 }
  10368. },
  10369. vertexShader: [
  10370. "void main() {",
  10371. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10372. "}"
  10373. ].join("\n"),
  10374. fragmentShader: [
  10375. "uniform float mNear;",
  10376. "uniform float mFar;",
  10377. "uniform float opacity;",
  10378. "void main() {",
  10379. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10380. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10381. "gl_FragColor = vec4( vec3( color ), opacity );",
  10382. "}"
  10383. ].join("\n")
  10384. },
  10385. 'normal': {
  10386. uniforms: {
  10387. "opacity" : { type: "f", value: 1.0 }
  10388. },
  10389. vertexShader: [
  10390. "varying vec3 vNormal;",
  10391. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10392. "void main() {",
  10393. "vNormal = normalize( normalMatrix * normal );",
  10394. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10395. THREE.ShaderChunk[ "default_vertex" ],
  10396. "}"
  10397. ].join("\n"),
  10398. fragmentShader: [
  10399. "uniform float opacity;",
  10400. "varying vec3 vNormal;",
  10401. "void main() {",
  10402. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10403. "}"
  10404. ].join("\n")
  10405. },
  10406. /* -------------------------------------------------------------------------
  10407. // Normal map shader
  10408. // - Blinn-Phong
  10409. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10410. // - point and directional lights (use with "lights: true" material option)
  10411. ------------------------------------------------------------------------- */
  10412. 'normalmap' : {
  10413. uniforms: THREE.UniformsUtils.merge( [
  10414. THREE.UniformsLib[ "fog" ],
  10415. THREE.UniformsLib[ "lights" ],
  10416. THREE.UniformsLib[ "shadowmap" ],
  10417. {
  10418. "enableAO" : { type: "i", value: 0 },
  10419. "enableDiffuse" : { type: "i", value: 0 },
  10420. "enableSpecular" : { type: "i", value: 0 },
  10421. "enableReflection": { type: "i", value: 0 },
  10422. "enableDisplacement": { type: "i", value: 0 },
  10423. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10424. "tDiffuse" : { type: "t", value: null },
  10425. "tCube" : { type: "t", value: null },
  10426. "tNormal" : { type: "t", value: null },
  10427. "tSpecular" : { type: "t", value: null },
  10428. "tAO" : { type: "t", value: null },
  10429. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10430. "uDisplacementBias": { type: "f", value: 0.0 },
  10431. "uDisplacementScale": { type: "f", value: 1.0 },
  10432. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10433. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10434. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10435. "uShininess": { type: "f", value: 30 },
  10436. "uOpacity": { type: "f", value: 1 },
  10437. "useRefract": { type: "i", value: 0 },
  10438. "uRefractionRatio": { type: "f", value: 0.98 },
  10439. "uReflectivity": { type: "f", value: 0.5 },
  10440. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10441. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10442. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10443. }
  10444. ] ),
  10445. fragmentShader: [
  10446. "uniform vec3 uAmbientColor;",
  10447. "uniform vec3 uDiffuseColor;",
  10448. "uniform vec3 uSpecularColor;",
  10449. "uniform float uShininess;",
  10450. "uniform float uOpacity;",
  10451. "uniform bool enableDiffuse;",
  10452. "uniform bool enableSpecular;",
  10453. "uniform bool enableAO;",
  10454. "uniform bool enableReflection;",
  10455. "uniform sampler2D tDiffuse;",
  10456. "uniform sampler2D tNormal;",
  10457. "uniform sampler2D tSpecular;",
  10458. "uniform sampler2D tAO;",
  10459. "uniform samplerCube tCube;",
  10460. "uniform vec2 uNormalScale;",
  10461. "uniform bool useRefract;",
  10462. "uniform float uRefractionRatio;",
  10463. "uniform float uReflectivity;",
  10464. "varying vec3 vTangent;",
  10465. "varying vec3 vBinormal;",
  10466. "varying vec3 vNormal;",
  10467. "varying vec2 vUv;",
  10468. "uniform vec3 ambientLightColor;",
  10469. "#if MAX_DIR_LIGHTS > 0",
  10470. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10471. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10472. "#endif",
  10473. "#if MAX_HEMI_LIGHTS > 0",
  10474. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10475. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10476. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10477. "#endif",
  10478. "#if MAX_POINT_LIGHTS > 0",
  10479. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10480. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10481. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10482. "#endif",
  10483. "#if MAX_SPOT_LIGHTS > 0",
  10484. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10485. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10486. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10487. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10488. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10489. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10490. "#endif",
  10491. "#ifdef WRAP_AROUND",
  10492. "uniform vec3 wrapRGB;",
  10493. "#endif",
  10494. "varying vec3 vWorldPosition;",
  10495. "varying vec3 vViewPosition;",
  10496. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10497. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10498. "void main() {",
  10499. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10500. "vec3 specularTex = vec3( 1.0 );",
  10501. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10502. "normalTex.xy *= uNormalScale;",
  10503. "normalTex = normalize( normalTex );",
  10504. "if( enableDiffuse ) {",
  10505. "#ifdef GAMMA_INPUT",
  10506. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10507. "texelColor.xyz *= texelColor.xyz;",
  10508. "gl_FragColor = gl_FragColor * texelColor;",
  10509. "#else",
  10510. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10511. "#endif",
  10512. "}",
  10513. "if( enableAO ) {",
  10514. "#ifdef GAMMA_INPUT",
  10515. "vec4 aoColor = texture2D( tAO, vUv );",
  10516. "aoColor.xyz *= aoColor.xyz;",
  10517. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10518. "#else",
  10519. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10520. "#endif",
  10521. "}",
  10522. "if( enableSpecular )",
  10523. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10524. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10525. "vec3 finalNormal = tsb * normalTex;",
  10526. "#ifdef FLIP_SIDED",
  10527. "finalNormal = -finalNormal;",
  10528. "#endif",
  10529. "vec3 normal = normalize( finalNormal );",
  10530. "vec3 viewPosition = normalize( vViewPosition );",
  10531. // point lights
  10532. "#if MAX_POINT_LIGHTS > 0",
  10533. "vec3 pointDiffuse = vec3( 0.0 );",
  10534. "vec3 pointSpecular = vec3( 0.0 );",
  10535. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10536. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10537. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10538. "float pointDistance = 1.0;",
  10539. "if ( pointLightDistance[ i ] > 0.0 )",
  10540. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10541. "pointVector = normalize( pointVector );",
  10542. // diffuse
  10543. "#ifdef WRAP_AROUND",
  10544. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10545. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10546. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10547. "#else",
  10548. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10549. "#endif",
  10550. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10551. // specular
  10552. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10553. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10554. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10555. "#ifdef PHYSICALLY_BASED_SHADING",
  10556. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10557. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10558. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10559. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10560. "#else",
  10561. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10562. "#endif",
  10563. "}",
  10564. "#endif",
  10565. // spot lights
  10566. "#if MAX_SPOT_LIGHTS > 0",
  10567. "vec3 spotDiffuse = vec3( 0.0 );",
  10568. "vec3 spotSpecular = vec3( 0.0 );",
  10569. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10570. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10571. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10572. "float spotDistance = 1.0;",
  10573. "if ( spotLightDistance[ i ] > 0.0 )",
  10574. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10575. "spotVector = normalize( spotVector );",
  10576. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10577. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10578. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10579. // diffuse
  10580. "#ifdef WRAP_AROUND",
  10581. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10582. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10583. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10584. "#else",
  10585. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10586. "#endif",
  10587. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10588. // specular
  10589. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10590. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10591. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10592. "#ifdef PHYSICALLY_BASED_SHADING",
  10593. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10594. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10595. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10596. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10597. "#else",
  10598. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10599. "#endif",
  10600. "}",
  10601. "}",
  10602. "#endif",
  10603. // directional lights
  10604. "#if MAX_DIR_LIGHTS > 0",
  10605. "vec3 dirDiffuse = vec3( 0.0 );",
  10606. "vec3 dirSpecular = vec3( 0.0 );",
  10607. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10608. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10609. "vec3 dirVector = normalize( lDirection.xyz );",
  10610. // diffuse
  10611. "#ifdef WRAP_AROUND",
  10612. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10613. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10614. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10615. "#else",
  10616. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10617. "#endif",
  10618. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10619. // specular
  10620. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10621. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10622. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10623. "#ifdef PHYSICALLY_BASED_SHADING",
  10624. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10625. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10626. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10627. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10628. "#else",
  10629. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10630. "#endif",
  10631. "}",
  10632. "#endif",
  10633. // hemisphere lights
  10634. "#if MAX_HEMI_LIGHTS > 0",
  10635. "vec3 hemiDiffuse = vec3( 0.0 );",
  10636. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10637. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10638. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10639. "vec3 lVector = normalize( lDirection.xyz );",
  10640. // diffuse
  10641. "float dotProduct = dot( normal, lVector );",
  10642. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10643. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10644. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10645. // specular (sky light)
  10646. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10647. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10648. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10649. // specular (ground light)
  10650. "vec3 lVectorGround = -lVector;",
  10651. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10652. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10653. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10654. "#ifdef PHYSICALLY_BASED_SHADING",
  10655. "float dotProductGround = dot( normal, lVectorGround );",
  10656. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10657. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10658. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10659. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10660. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10661. "#else",
  10662. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10663. "#endif",
  10664. "}",
  10665. "#endif",
  10666. // all lights contribution summation
  10667. "vec3 totalDiffuse = vec3( 0.0 );",
  10668. "vec3 totalSpecular = vec3( 0.0 );",
  10669. "#if MAX_DIR_LIGHTS > 0",
  10670. "totalDiffuse += dirDiffuse;",
  10671. "totalSpecular += dirSpecular;",
  10672. "#endif",
  10673. "#if MAX_HEMI_LIGHTS > 0",
  10674. "totalDiffuse += hemiDiffuse;",
  10675. "totalSpecular += hemiSpecular;",
  10676. "#endif",
  10677. "#if MAX_POINT_LIGHTS > 0",
  10678. "totalDiffuse += pointDiffuse;",
  10679. "totalSpecular += pointSpecular;",
  10680. "#endif",
  10681. "#if MAX_SPOT_LIGHTS > 0",
  10682. "totalDiffuse += spotDiffuse;",
  10683. "totalSpecular += spotSpecular;",
  10684. "#endif",
  10685. "#ifdef METAL",
  10686. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10687. "#else",
  10688. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10689. "#endif",
  10690. "if ( enableReflection ) {",
  10691. "vec3 vReflect;",
  10692. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10693. "if ( useRefract ) {",
  10694. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10695. "} else {",
  10696. "vReflect = reflect( cameraToVertex, normal );",
  10697. "}",
  10698. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10699. "#ifdef GAMMA_INPUT",
  10700. "cubeColor.xyz *= cubeColor.xyz;",
  10701. "#endif",
  10702. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10703. "}",
  10704. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10705. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10706. THREE.ShaderChunk[ "fog_fragment" ],
  10707. "}"
  10708. ].join("\n"),
  10709. vertexShader: [
  10710. "attribute vec4 tangent;",
  10711. "uniform vec2 uOffset;",
  10712. "uniform vec2 uRepeat;",
  10713. "uniform bool enableDisplacement;",
  10714. "#ifdef VERTEX_TEXTURES",
  10715. "uniform sampler2D tDisplacement;",
  10716. "uniform float uDisplacementScale;",
  10717. "uniform float uDisplacementBias;",
  10718. "#endif",
  10719. "varying vec3 vTangent;",
  10720. "varying vec3 vBinormal;",
  10721. "varying vec3 vNormal;",
  10722. "varying vec2 vUv;",
  10723. "varying vec3 vWorldPosition;",
  10724. "varying vec3 vViewPosition;",
  10725. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10726. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10727. "void main() {",
  10728. THREE.ShaderChunk[ "skinbase_vertex" ],
  10729. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10730. // normal, tangent and binormal vectors
  10731. "#ifdef USE_SKINNING",
  10732. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10733. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10734. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10735. "#else",
  10736. "vNormal = normalize( normalMatrix * normal );",
  10737. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10738. "#endif",
  10739. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10740. "vUv = uv * uRepeat + uOffset;",
  10741. // displacement mapping
  10742. "vec3 displacedPosition;",
  10743. "#ifdef VERTEX_TEXTURES",
  10744. "if ( enableDisplacement ) {",
  10745. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10746. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10747. "displacedPosition = position + normalize( normal ) * df;",
  10748. "} else {",
  10749. "#ifdef USE_SKINNING",
  10750. "vec4 skinVertex = vec4( position, 1.0 );",
  10751. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10752. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10753. "displacedPosition = skinned.xyz;",
  10754. "#else",
  10755. "displacedPosition = position;",
  10756. "#endif",
  10757. "}",
  10758. "#else",
  10759. "#ifdef USE_SKINNING",
  10760. "vec4 skinVertex = vec4( position, 1.0 );",
  10761. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10762. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10763. "displacedPosition = skinned.xyz;",
  10764. "#else",
  10765. "displacedPosition = position;",
  10766. "#endif",
  10767. "#endif",
  10768. //
  10769. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10770. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10771. "gl_Position = projectionMatrix * mvPosition;",
  10772. //
  10773. "vWorldPosition = worldPosition.xyz;",
  10774. "vViewPosition = -mvPosition.xyz;",
  10775. // shadows
  10776. "#ifdef USE_SHADOWMAP",
  10777. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10778. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10779. "}",
  10780. "#endif",
  10781. "}"
  10782. ].join("\n")
  10783. },
  10784. /* -------------------------------------------------------------------------
  10785. // Cube map shader
  10786. ------------------------------------------------------------------------- */
  10787. 'cube': {
  10788. uniforms: { "tCube": { type: "t", value: null },
  10789. "tFlip": { type: "f", value: -1 } },
  10790. vertexShader: [
  10791. "varying vec3 vWorldPosition;",
  10792. "void main() {",
  10793. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10794. "vWorldPosition = worldPosition.xyz;",
  10795. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10796. "}"
  10797. ].join("\n"),
  10798. fragmentShader: [
  10799. "uniform samplerCube tCube;",
  10800. "uniform float tFlip;",
  10801. "varying vec3 vWorldPosition;",
  10802. "void main() {",
  10803. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10804. "}"
  10805. ].join("\n")
  10806. },
  10807. // Depth encoding into RGBA texture
  10808. // based on SpiderGL shadow map example
  10809. // http://spidergl.org/example.php?id=6
  10810. // originally from
  10811. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10812. // see also here:
  10813. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10814. 'depthRGBA': {
  10815. uniforms: {},
  10816. vertexShader: [
  10817. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10818. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10819. "void main() {",
  10820. THREE.ShaderChunk[ "skinbase_vertex" ],
  10821. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10822. THREE.ShaderChunk[ "skinning_vertex" ],
  10823. THREE.ShaderChunk[ "default_vertex" ],
  10824. "}"
  10825. ].join("\n"),
  10826. fragmentShader: [
  10827. "vec4 pack_depth( const in float depth ) {",
  10828. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10829. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10830. "vec4 res = fract( depth * bit_shift );",
  10831. "res -= res.xxyz * bit_mask;",
  10832. "return res;",
  10833. "}",
  10834. "void main() {",
  10835. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10836. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10837. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10838. //"gl_FragData[ 0 ] = pack_depth( z );",
  10839. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10840. "}"
  10841. ].join("\n")
  10842. }
  10843. };
  10844. /**
  10845. * @author supereggbert / http://www.paulbrunt.co.uk/
  10846. * @author mrdoob / http://mrdoob.com/
  10847. * @author alteredq / http://alteredqualia.com/
  10848. * @author szimek / https://github.com/szimek/
  10849. */
  10850. THREE.WebGLRenderer = function ( parameters ) {
  10851. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10852. parameters = parameters || {};
  10853. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10854. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10855. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10856. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10857. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10858. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10859. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10860. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10861. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10862. // public properties
  10863. this.domElement = _canvas;
  10864. this.context = null;
  10865. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10866. ? parameters.devicePixelRatio
  10867. : window.devicePixelRatio !== undefined
  10868. ? window.devicePixelRatio
  10869. : 1;
  10870. // clearing
  10871. this.autoClear = true;
  10872. this.autoClearColor = true;
  10873. this.autoClearDepth = true;
  10874. this.autoClearStencil = true;
  10875. // scene graph
  10876. this.sortObjects = true;
  10877. this.autoUpdateObjects = true;
  10878. this.autoUpdateScene = true;
  10879. // physically based shading
  10880. this.gammaInput = false;
  10881. this.gammaOutput = false;
  10882. this.physicallyBasedShading = false;
  10883. // shadow map
  10884. this.shadowMapEnabled = false;
  10885. this.shadowMapAutoUpdate = true;
  10886. this.shadowMapType = THREE.PCFShadowMap;
  10887. this.shadowMapCullFace = THREE.CullFaceFront;
  10888. this.shadowMapDebug = false;
  10889. this.shadowMapCascade = false;
  10890. // morphs
  10891. this.maxMorphTargets = 8;
  10892. this.maxMorphNormals = 4;
  10893. // flags
  10894. this.autoScaleCubemaps = true;
  10895. // custom render plugins
  10896. this.renderPluginsPre = [];
  10897. this.renderPluginsPost = [];
  10898. // info
  10899. this.info = {
  10900. memory: {
  10901. programs: 0,
  10902. geometries: 0,
  10903. textures: 0
  10904. },
  10905. render: {
  10906. calls: 0,
  10907. vertices: 0,
  10908. faces: 0,
  10909. points: 0
  10910. }
  10911. };
  10912. // internal properties
  10913. var _this = this,
  10914. _programs = [],
  10915. _programs_counter = 0,
  10916. // internal state cache
  10917. _currentProgram = null,
  10918. _currentFramebuffer = null,
  10919. _currentMaterialId = -1,
  10920. _currentGeometryGroupHash = null,
  10921. _currentCamera = null,
  10922. _geometryGroupCounter = 0,
  10923. _usedTextureUnits = 0,
  10924. // GL state cache
  10925. _oldDoubleSided = -1,
  10926. _oldFlipSided = -1,
  10927. _oldBlending = -1,
  10928. _oldBlendEquation = -1,
  10929. _oldBlendSrc = -1,
  10930. _oldBlendDst = -1,
  10931. _oldDepthTest = -1,
  10932. _oldDepthWrite = -1,
  10933. _oldPolygonOffset = null,
  10934. _oldPolygonOffsetFactor = null,
  10935. _oldPolygonOffsetUnits = null,
  10936. _oldLineWidth = null,
  10937. _viewportX = 0,
  10938. _viewportY = 0,
  10939. _viewportWidth = 0,
  10940. _viewportHeight = 0,
  10941. _currentWidth = 0,
  10942. _currentHeight = 0,
  10943. _enabledAttributes = {},
  10944. // frustum
  10945. _frustum = new THREE.Frustum(),
  10946. // camera matrices cache
  10947. _projScreenMatrix = new THREE.Matrix4(),
  10948. _projScreenMatrixPS = new THREE.Matrix4(),
  10949. _vector3 = new THREE.Vector3(),
  10950. // light arrays cache
  10951. _direction = new THREE.Vector3(),
  10952. _lightsNeedUpdate = true,
  10953. _lights = {
  10954. ambient: [ 0, 0, 0 ],
  10955. directional: { length: 0, colors: new Array(), positions: new Array() },
  10956. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10957. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10958. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10959. };
  10960. // initialize
  10961. var _gl;
  10962. var _glExtensionTextureFloat;
  10963. var _glExtensionStandardDerivatives;
  10964. var _glExtensionTextureFilterAnisotropic;
  10965. var _glExtensionCompressedTextureS3TC;
  10966. initGL();
  10967. setDefaultGLState();
  10968. this.context = _gl;
  10969. // GPU capabilities
  10970. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10971. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10972. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10973. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10974. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10975. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10976. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10977. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10978. //
  10979. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10980. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10981. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10982. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10983. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10984. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10985. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10986. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10987. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10988. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10989. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10990. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10991. // clamp precision to maximum available
  10992. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10993. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10994. if ( _precision === "highp" && ! highpAvailable ) {
  10995. if ( mediumpAvailable ) {
  10996. _precision = "mediump";
  10997. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10998. } else {
  10999. _precision = "lowp";
  11000. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11001. }
  11002. }
  11003. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11004. _precision = "lowp";
  11005. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11006. }
  11007. // API
  11008. this.getContext = function () {
  11009. return _gl;
  11010. };
  11011. this.supportsVertexTextures = function () {
  11012. return _supportsVertexTextures;
  11013. };
  11014. this.supportsFloatTextures = function () {
  11015. return _glExtensionTextureFloat;
  11016. };
  11017. this.supportsStandardDerivatives = function () {
  11018. return _glExtensionStandardDerivatives;
  11019. };
  11020. this.supportsCompressedTextureS3TC = function () {
  11021. return _glExtensionCompressedTextureS3TC;
  11022. };
  11023. this.getMaxAnisotropy = function () {
  11024. return _maxAnisotropy;
  11025. };
  11026. this.getPrecision = function () {
  11027. return _precision;
  11028. };
  11029. this.setSize = function ( width, height ) {
  11030. _canvas.width = width * this.devicePixelRatio;
  11031. _canvas.height = height * this.devicePixelRatio;
  11032. _canvas.style.width = width + 'px';
  11033. _canvas.style.height = height + 'px';
  11034. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11035. };
  11036. this.setViewport = function ( x, y, width, height ) {
  11037. _viewportX = x !== undefined ? x : 0;
  11038. _viewportY = y !== undefined ? y : 0;
  11039. _viewportWidth = width !== undefined ? width : _canvas.width;
  11040. _viewportHeight = height !== undefined ? height : _canvas.height;
  11041. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11042. };
  11043. this.setScissor = function ( x, y, width, height ) {
  11044. _gl.scissor( x, y, width, height );
  11045. };
  11046. this.enableScissorTest = function ( enable ) {
  11047. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11048. };
  11049. // Clearing
  11050. this.setClearColorHex = function ( hex, alpha ) {
  11051. _clearColor.setHex( hex );
  11052. _clearAlpha = alpha;
  11053. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11054. };
  11055. this.setClearColor = function ( color, alpha ) {
  11056. _clearColor.copy( color );
  11057. _clearAlpha = alpha;
  11058. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11059. };
  11060. this.getClearColor = function () {
  11061. return _clearColor;
  11062. };
  11063. this.getClearAlpha = function () {
  11064. return _clearAlpha;
  11065. };
  11066. this.clear = function ( color, depth, stencil ) {
  11067. var bits = 0;
  11068. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11069. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11070. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11071. _gl.clear( bits );
  11072. };
  11073. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11074. this.setRenderTarget( renderTarget );
  11075. this.clear( color, depth, stencil );
  11076. };
  11077. // Plugins
  11078. this.addPostPlugin = function ( plugin ) {
  11079. plugin.init( this );
  11080. this.renderPluginsPost.push( plugin );
  11081. };
  11082. this.addPrePlugin = function ( plugin ) {
  11083. plugin.init( this );
  11084. this.renderPluginsPre.push( plugin );
  11085. };
  11086. // Rendering
  11087. this.updateShadowMap = function ( scene, camera ) {
  11088. _currentProgram = null;
  11089. _oldBlending = -1;
  11090. _oldDepthTest = -1;
  11091. _oldDepthWrite = -1;
  11092. _currentGeometryGroupHash = -1;
  11093. _currentMaterialId = -1;
  11094. _lightsNeedUpdate = true;
  11095. _oldDoubleSided = -1;
  11096. _oldFlipSided = -1;
  11097. this.shadowMapPlugin.update( scene, camera );
  11098. };
  11099. // Internal functions
  11100. // Buffer allocation
  11101. function createParticleBuffers ( geometry ) {
  11102. geometry.__webglVertexBuffer = _gl.createBuffer();
  11103. geometry.__webglColorBuffer = _gl.createBuffer();
  11104. _this.info.memory.geometries ++;
  11105. };
  11106. function createLineBuffers ( geometry ) {
  11107. geometry.__webglVertexBuffer = _gl.createBuffer();
  11108. geometry.__webglColorBuffer = _gl.createBuffer();
  11109. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11110. _this.info.memory.geometries ++;
  11111. };
  11112. function createRibbonBuffers ( geometry ) {
  11113. geometry.__webglVertexBuffer = _gl.createBuffer();
  11114. geometry.__webglColorBuffer = _gl.createBuffer();
  11115. geometry.__webglNormalBuffer = _gl.createBuffer();
  11116. _this.info.memory.geometries ++;
  11117. };
  11118. function createMeshBuffers ( geometryGroup ) {
  11119. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11120. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11121. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11122. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11123. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11124. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11125. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11126. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11127. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11128. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11129. var m, ml;
  11130. if ( geometryGroup.numMorphTargets ) {
  11131. geometryGroup.__webglMorphTargetsBuffers = [];
  11132. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11133. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11134. }
  11135. }
  11136. if ( geometryGroup.numMorphNormals ) {
  11137. geometryGroup.__webglMorphNormalsBuffers = [];
  11138. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11139. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11140. }
  11141. }
  11142. _this.info.memory.geometries ++;
  11143. };
  11144. // Events
  11145. var onGeometryDispose = function ( event ) {
  11146. var geometry = event.target;
  11147. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11148. deallocateGeometry( geometry );
  11149. _this.info.memory.geometries --;
  11150. };
  11151. var onTextureDispose = function ( event ) {
  11152. var texture = event.target;
  11153. texture.removeEventListener( 'dispose', onTextureDispose );
  11154. deallocateTexture( texture );
  11155. _this.info.memory.textures --;
  11156. };
  11157. var onRenderTargetDispose = function ( event ) {
  11158. var renderTarget = event.target;
  11159. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11160. deallocateRenderTarget( renderTarget );
  11161. _this.info.memory.textures --;
  11162. };
  11163. var onMaterialDispose = function ( event ) {
  11164. var material = event.target;
  11165. material.removeEventListener( 'dispose', onMaterialDispose );
  11166. deallocateMaterial( material );
  11167. };
  11168. // Buffer deallocation
  11169. var deallocateGeometry = function ( geometry ) {
  11170. geometry.__webglInit = undefined;
  11171. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11172. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11173. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11174. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11175. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11176. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11177. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11178. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11179. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11180. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11181. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11182. // geometry groups
  11183. if ( geometry.geometryGroups !== undefined ) {
  11184. for ( var g in geometry.geometryGroups ) {
  11185. var geometryGroup = geometry.geometryGroups[ g ];
  11186. if ( geometryGroup.numMorphTargets !== undefined ) {
  11187. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11188. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11189. }
  11190. }
  11191. if ( geometryGroup.numMorphNormals !== undefined ) {
  11192. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11193. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11194. }
  11195. }
  11196. deleteCustomAttributesBuffers( geometryGroup );
  11197. }
  11198. }
  11199. deleteCustomAttributesBuffers( geometry );
  11200. };
  11201. var deallocateTexture = function ( texture ) {
  11202. if ( texture.image && texture.image.__webglTextureCube ) {
  11203. // cube texture
  11204. _gl.deleteTexture( texture.image.__webglTextureCube );
  11205. } else {
  11206. // 2D texture
  11207. if ( ! texture.__webglInit ) return;
  11208. texture.__webglInit = false;
  11209. _gl.deleteTexture( texture.__webglTexture );
  11210. }
  11211. };
  11212. var deallocateRenderTarget = function ( renderTarget ) {
  11213. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11214. _gl.deleteTexture( renderTarget.__webglTexture );
  11215. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11216. for ( var i = 0; i < 6; i ++ ) {
  11217. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11218. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11219. }
  11220. } else {
  11221. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11222. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11223. }
  11224. };
  11225. var deallocateMaterial = function ( material ) {
  11226. var program = material.program;
  11227. if ( program === undefined ) return;
  11228. material.program = undefined;
  11229. // only deallocate GL program if this was the last use of shared program
  11230. // assumed there is only single copy of any program in the _programs list
  11231. // (that's how it's constructed)
  11232. var i, il, programInfo;
  11233. var deleteProgram = false;
  11234. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11235. programInfo = _programs[ i ];
  11236. if ( programInfo.program === program ) {
  11237. programInfo.usedTimes --;
  11238. if ( programInfo.usedTimes === 0 ) {
  11239. deleteProgram = true;
  11240. }
  11241. break;
  11242. }
  11243. }
  11244. if ( deleteProgram === true ) {
  11245. // avoid using array.splice, this is costlier than creating new array from scratch
  11246. var newPrograms = [];
  11247. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11248. programInfo = _programs[ i ];
  11249. if ( programInfo.program !== program ) {
  11250. newPrograms.push( programInfo );
  11251. }
  11252. }
  11253. _programs = newPrograms;
  11254. _gl.deleteProgram( program );
  11255. _this.info.memory.programs --;
  11256. }
  11257. };
  11258. //
  11259. /*
  11260. function deleteParticleBuffers ( geometry ) {
  11261. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11262. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11263. deleteCustomAttributesBuffers( geometry );
  11264. _this.info.memory.geometries --;
  11265. };
  11266. function deleteLineBuffers ( geometry ) {
  11267. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11268. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11269. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11270. deleteCustomAttributesBuffers( geometry );
  11271. _this.info.memory.geometries --;
  11272. };
  11273. function deleteRibbonBuffers ( geometry ) {
  11274. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11275. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11276. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11277. deleteCustomAttributesBuffers( geometry );
  11278. _this.info.memory.geometries --;
  11279. };
  11280. function deleteMeshBuffers ( geometryGroup ) {
  11281. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11282. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11283. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11284. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11285. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11286. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11287. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11288. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11289. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11290. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11291. var m, ml;
  11292. if ( geometryGroup.numMorphTargets ) {
  11293. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11294. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11295. }
  11296. }
  11297. if ( geometryGroup.numMorphNormals ) {
  11298. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11299. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11300. }
  11301. }
  11302. deleteCustomAttributesBuffers( geometryGroup );
  11303. _this.info.memory.geometries --;
  11304. };
  11305. */
  11306. function deleteCustomAttributesBuffers( geometry ) {
  11307. if ( geometry.__webglCustomAttributesList ) {
  11308. for ( var id in geometry.__webglCustomAttributesList ) {
  11309. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11310. }
  11311. }
  11312. };
  11313. // Buffer initialization
  11314. function initCustomAttributes ( geometry, object ) {
  11315. var nvertices = geometry.vertices.length;
  11316. var material = object.material;
  11317. if ( material.attributes ) {
  11318. if ( geometry.__webglCustomAttributesList === undefined ) {
  11319. geometry.__webglCustomAttributesList = [];
  11320. }
  11321. for ( var a in material.attributes ) {
  11322. var attribute = material.attributes[ a ];
  11323. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11324. attribute.__webglInitialized = true;
  11325. var size = 1; // "f" and "i"
  11326. if ( attribute.type === "v2" ) size = 2;
  11327. else if ( attribute.type === "v3" ) size = 3;
  11328. else if ( attribute.type === "v4" ) size = 4;
  11329. else if ( attribute.type === "c" ) size = 3;
  11330. attribute.size = size;
  11331. attribute.array = new Float32Array( nvertices * size );
  11332. attribute.buffer = _gl.createBuffer();
  11333. attribute.buffer.belongsToAttribute = a;
  11334. attribute.needsUpdate = true;
  11335. }
  11336. geometry.__webglCustomAttributesList.push( attribute );
  11337. }
  11338. }
  11339. };
  11340. function initParticleBuffers ( geometry, object ) {
  11341. var nvertices = geometry.vertices.length;
  11342. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11343. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11344. geometry.__sortArray = [];
  11345. geometry.__webglParticleCount = nvertices;
  11346. initCustomAttributes ( geometry, object );
  11347. };
  11348. function initLineBuffers ( geometry, object ) {
  11349. var nvertices = geometry.vertices.length;
  11350. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11351. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11352. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11353. geometry.__webglLineCount = nvertices;
  11354. initCustomAttributes ( geometry, object );
  11355. };
  11356. function initRibbonBuffers ( geometry, object ) {
  11357. var nvertices = geometry.vertices.length;
  11358. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11359. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11360. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11361. geometry.__webglVertexCount = nvertices;
  11362. initCustomAttributes ( geometry, object );
  11363. };
  11364. function initMeshBuffers ( geometryGroup, object ) {
  11365. var geometry = object.geometry,
  11366. faces3 = geometryGroup.faces3,
  11367. faces4 = geometryGroup.faces4,
  11368. nvertices = faces3.length * 3 + faces4.length * 4,
  11369. ntris = faces3.length * 1 + faces4.length * 2,
  11370. nlines = faces3.length * 3 + faces4.length * 4,
  11371. material = getBufferMaterial( object, geometryGroup ),
  11372. uvType = bufferGuessUVType( material ),
  11373. normalType = bufferGuessNormalType( material ),
  11374. vertexColorType = bufferGuessVertexColorType( material );
  11375. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11376. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11377. if ( normalType ) {
  11378. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11379. }
  11380. if ( geometry.hasTangents ) {
  11381. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11382. }
  11383. if ( vertexColorType ) {
  11384. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11385. }
  11386. if ( uvType ) {
  11387. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11388. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11389. }
  11390. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11391. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11392. }
  11393. }
  11394. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11395. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11396. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11397. }
  11398. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11399. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11400. var m, ml;
  11401. if ( geometryGroup.numMorphTargets ) {
  11402. geometryGroup.__morphTargetsArrays = [];
  11403. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11404. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11405. }
  11406. }
  11407. if ( geometryGroup.numMorphNormals ) {
  11408. geometryGroup.__morphNormalsArrays = [];
  11409. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11410. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11411. }
  11412. }
  11413. geometryGroup.__webglFaceCount = ntris * 3;
  11414. geometryGroup.__webglLineCount = nlines * 2;
  11415. // custom attributes
  11416. if ( material.attributes ) {
  11417. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11418. geometryGroup.__webglCustomAttributesList = [];
  11419. }
  11420. for ( var a in material.attributes ) {
  11421. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11422. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11423. var originalAttribute = material.attributes[ a ];
  11424. var attribute = {};
  11425. for ( var property in originalAttribute ) {
  11426. attribute[ property ] = originalAttribute[ property ];
  11427. }
  11428. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11429. attribute.__webglInitialized = true;
  11430. var size = 1; // "f" and "i"
  11431. if( attribute.type === "v2" ) size = 2;
  11432. else if( attribute.type === "v3" ) size = 3;
  11433. else if( attribute.type === "v4" ) size = 4;
  11434. else if( attribute.type === "c" ) size = 3;
  11435. attribute.size = size;
  11436. attribute.array = new Float32Array( nvertices * size );
  11437. attribute.buffer = _gl.createBuffer();
  11438. attribute.buffer.belongsToAttribute = a;
  11439. originalAttribute.needsUpdate = true;
  11440. attribute.__original = originalAttribute;
  11441. }
  11442. geometryGroup.__webglCustomAttributesList.push( attribute );
  11443. }
  11444. }
  11445. geometryGroup.__inittedArrays = true;
  11446. };
  11447. function getBufferMaterial( object, geometryGroup ) {
  11448. return object.material instanceof THREE.MeshFaceMaterial
  11449. ? object.material.materials[ geometryGroup.materialIndex ]
  11450. : object.material;
  11451. };
  11452. function materialNeedsSmoothNormals ( material ) {
  11453. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11454. };
  11455. function bufferGuessNormalType ( material ) {
  11456. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11457. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11458. return false;
  11459. }
  11460. if ( materialNeedsSmoothNormals( material ) ) {
  11461. return THREE.SmoothShading;
  11462. } else {
  11463. return THREE.FlatShading;
  11464. }
  11465. };
  11466. function bufferGuessVertexColorType( material ) {
  11467. if ( material.vertexColors ) {
  11468. return material.vertexColors;
  11469. }
  11470. return false;
  11471. };
  11472. function bufferGuessUVType( material ) {
  11473. // material must use some texture to require uvs
  11474. if ( material.map ||
  11475. material.lightMap ||
  11476. material.bumpMap ||
  11477. material.normalMap ||
  11478. material.specularMap ||
  11479. material instanceof THREE.ShaderMaterial ) {
  11480. return true;
  11481. }
  11482. return false;
  11483. };
  11484. //
  11485. function initDirectBuffers( geometry ) {
  11486. var a, attribute, type;
  11487. for ( a in geometry.attributes ) {
  11488. if ( a === "index" ) {
  11489. type = _gl.ELEMENT_ARRAY_BUFFER;
  11490. } else {
  11491. type = _gl.ARRAY_BUFFER;
  11492. }
  11493. attribute = geometry.attributes[ a ];
  11494. attribute.buffer = _gl.createBuffer();
  11495. _gl.bindBuffer( type, attribute.buffer );
  11496. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11497. }
  11498. };
  11499. // Buffer setting
  11500. function setParticleBuffers ( geometry, hint, object ) {
  11501. var v, c, vertex, offset, index, color,
  11502. vertices = geometry.vertices,
  11503. vl = vertices.length,
  11504. colors = geometry.colors,
  11505. cl = colors.length,
  11506. vertexArray = geometry.__vertexArray,
  11507. colorArray = geometry.__colorArray,
  11508. sortArray = geometry.__sortArray,
  11509. dirtyVertices = geometry.verticesNeedUpdate,
  11510. dirtyElements = geometry.elementsNeedUpdate,
  11511. dirtyColors = geometry.colorsNeedUpdate,
  11512. customAttributes = geometry.__webglCustomAttributesList,
  11513. i, il,
  11514. a, ca, cal, value,
  11515. customAttribute;
  11516. if ( object.sortParticles ) {
  11517. _projScreenMatrixPS.copy( _projScreenMatrix );
  11518. _projScreenMatrixPS.multiply( object.matrixWorld );
  11519. for ( v = 0; v < vl; v ++ ) {
  11520. vertex = vertices[ v ];
  11521. _vector3.copy( vertex );
  11522. _vector3.applyProjection( _projScreenMatrixPS );
  11523. sortArray[ v ] = [ _vector3.z, v ];
  11524. }
  11525. sortArray.sort( numericalSort );
  11526. for ( v = 0; v < vl; v ++ ) {
  11527. vertex = vertices[ sortArray[v][1] ];
  11528. offset = v * 3;
  11529. vertexArray[ offset ] = vertex.x;
  11530. vertexArray[ offset + 1 ] = vertex.y;
  11531. vertexArray[ offset + 2 ] = vertex.z;
  11532. }
  11533. for ( c = 0; c < cl; c ++ ) {
  11534. offset = c * 3;
  11535. color = colors[ sortArray[c][1] ];
  11536. colorArray[ offset ] = color.r;
  11537. colorArray[ offset + 1 ] = color.g;
  11538. colorArray[ offset + 2 ] = color.b;
  11539. }
  11540. if ( customAttributes ) {
  11541. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11542. customAttribute = customAttributes[ i ];
  11543. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11544. offset = 0;
  11545. cal = customAttribute.value.length;
  11546. if ( customAttribute.size === 1 ) {
  11547. for ( ca = 0; ca < cal; ca ++ ) {
  11548. index = sortArray[ ca ][ 1 ];
  11549. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11550. }
  11551. } else if ( customAttribute.size === 2 ) {
  11552. for ( ca = 0; ca < cal; ca ++ ) {
  11553. index = sortArray[ ca ][ 1 ];
  11554. value = customAttribute.value[ index ];
  11555. customAttribute.array[ offset ] = value.x;
  11556. customAttribute.array[ offset + 1 ] = value.y;
  11557. offset += 2;
  11558. }
  11559. } else if ( customAttribute.size === 3 ) {
  11560. if ( customAttribute.type === "c" ) {
  11561. for ( ca = 0; ca < cal; ca ++ ) {
  11562. index = sortArray[ ca ][ 1 ];
  11563. value = customAttribute.value[ index ];
  11564. customAttribute.array[ offset ] = value.r;
  11565. customAttribute.array[ offset + 1 ] = value.g;
  11566. customAttribute.array[ offset + 2 ] = value.b;
  11567. offset += 3;
  11568. }
  11569. } else {
  11570. for ( ca = 0; ca < cal; ca ++ ) {
  11571. index = sortArray[ ca ][ 1 ];
  11572. value = customAttribute.value[ index ];
  11573. customAttribute.array[ offset ] = value.x;
  11574. customAttribute.array[ offset + 1 ] = value.y;
  11575. customAttribute.array[ offset + 2 ] = value.z;
  11576. offset += 3;
  11577. }
  11578. }
  11579. } else if ( customAttribute.size === 4 ) {
  11580. for ( ca = 0; ca < cal; ca ++ ) {
  11581. index = sortArray[ ca ][ 1 ];
  11582. value = customAttribute.value[ index ];
  11583. customAttribute.array[ offset ] = value.x;
  11584. customAttribute.array[ offset + 1 ] = value.y;
  11585. customAttribute.array[ offset + 2 ] = value.z;
  11586. customAttribute.array[ offset + 3 ] = value.w;
  11587. offset += 4;
  11588. }
  11589. }
  11590. }
  11591. }
  11592. } else {
  11593. if ( dirtyVertices ) {
  11594. for ( v = 0; v < vl; v ++ ) {
  11595. vertex = vertices[ v ];
  11596. offset = v * 3;
  11597. vertexArray[ offset ] = vertex.x;
  11598. vertexArray[ offset + 1 ] = vertex.y;
  11599. vertexArray[ offset + 2 ] = vertex.z;
  11600. }
  11601. }
  11602. if ( dirtyColors ) {
  11603. for ( c = 0; c < cl; c ++ ) {
  11604. color = colors[ c ];
  11605. offset = c * 3;
  11606. colorArray[ offset ] = color.r;
  11607. colorArray[ offset + 1 ] = color.g;
  11608. colorArray[ offset + 2 ] = color.b;
  11609. }
  11610. }
  11611. if ( customAttributes ) {
  11612. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11613. customAttribute = customAttributes[ i ];
  11614. if ( customAttribute.needsUpdate &&
  11615. ( customAttribute.boundTo === undefined ||
  11616. customAttribute.boundTo === "vertices") ) {
  11617. cal = customAttribute.value.length;
  11618. offset = 0;
  11619. if ( customAttribute.size === 1 ) {
  11620. for ( ca = 0; ca < cal; ca ++ ) {
  11621. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11622. }
  11623. } else if ( customAttribute.size === 2 ) {
  11624. for ( ca = 0; ca < cal; ca ++ ) {
  11625. value = customAttribute.value[ ca ];
  11626. customAttribute.array[ offset ] = value.x;
  11627. customAttribute.array[ offset + 1 ] = value.y;
  11628. offset += 2;
  11629. }
  11630. } else if ( customAttribute.size === 3 ) {
  11631. if ( customAttribute.type === "c" ) {
  11632. for ( ca = 0; ca < cal; ca ++ ) {
  11633. value = customAttribute.value[ ca ];
  11634. customAttribute.array[ offset ] = value.r;
  11635. customAttribute.array[ offset + 1 ] = value.g;
  11636. customAttribute.array[ offset + 2 ] = value.b;
  11637. offset += 3;
  11638. }
  11639. } else {
  11640. for ( ca = 0; ca < cal; ca ++ ) {
  11641. value = customAttribute.value[ ca ];
  11642. customAttribute.array[ offset ] = value.x;
  11643. customAttribute.array[ offset + 1 ] = value.y;
  11644. customAttribute.array[ offset + 2 ] = value.z;
  11645. offset += 3;
  11646. }
  11647. }
  11648. } else if ( customAttribute.size === 4 ) {
  11649. for ( ca = 0; ca < cal; ca ++ ) {
  11650. value = customAttribute.value[ ca ];
  11651. customAttribute.array[ offset ] = value.x;
  11652. customAttribute.array[ offset + 1 ] = value.y;
  11653. customAttribute.array[ offset + 2 ] = value.z;
  11654. customAttribute.array[ offset + 3 ] = value.w;
  11655. offset += 4;
  11656. }
  11657. }
  11658. }
  11659. }
  11660. }
  11661. }
  11662. if ( dirtyVertices || object.sortParticles ) {
  11663. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11664. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11665. }
  11666. if ( dirtyColors || object.sortParticles ) {
  11667. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11668. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11669. }
  11670. if ( customAttributes ) {
  11671. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11672. customAttribute = customAttributes[ i ];
  11673. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11674. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11675. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11676. }
  11677. }
  11678. }
  11679. };
  11680. function setLineBuffers ( geometry, hint ) {
  11681. var v, c, d, vertex, offset, color,
  11682. vertices = geometry.vertices,
  11683. colors = geometry.colors,
  11684. lineDistances = geometry.lineDistances,
  11685. vl = vertices.length,
  11686. cl = colors.length,
  11687. dl = lineDistances.length,
  11688. vertexArray = geometry.__vertexArray,
  11689. colorArray = geometry.__colorArray,
  11690. lineDistanceArray = geometry.__lineDistanceArray,
  11691. dirtyVertices = geometry.verticesNeedUpdate,
  11692. dirtyColors = geometry.colorsNeedUpdate,
  11693. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11694. customAttributes = geometry.__webglCustomAttributesList,
  11695. i, il,
  11696. a, ca, cal, value,
  11697. customAttribute;
  11698. if ( dirtyVertices ) {
  11699. for ( v = 0; v < vl; v ++ ) {
  11700. vertex = vertices[ v ];
  11701. offset = v * 3;
  11702. vertexArray[ offset ] = vertex.x;
  11703. vertexArray[ offset + 1 ] = vertex.y;
  11704. vertexArray[ offset + 2 ] = vertex.z;
  11705. }
  11706. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11707. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11708. }
  11709. if ( dirtyColors ) {
  11710. for ( c = 0; c < cl; c ++ ) {
  11711. color = colors[ c ];
  11712. offset = c * 3;
  11713. colorArray[ offset ] = color.r;
  11714. colorArray[ offset + 1 ] = color.g;
  11715. colorArray[ offset + 2 ] = color.b;
  11716. }
  11717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11718. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11719. }
  11720. if ( dirtyLineDistances ) {
  11721. for ( d = 0; d < dl; d ++ ) {
  11722. lineDistanceArray[ d ] = lineDistances[ d ];
  11723. }
  11724. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11725. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11726. }
  11727. if ( customAttributes ) {
  11728. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11729. customAttribute = customAttributes[ i ];
  11730. if ( customAttribute.needsUpdate &&
  11731. ( customAttribute.boundTo === undefined ||
  11732. customAttribute.boundTo === "vertices" ) ) {
  11733. offset = 0;
  11734. cal = customAttribute.value.length;
  11735. if ( customAttribute.size === 1 ) {
  11736. for ( ca = 0; ca < cal; ca ++ ) {
  11737. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11738. }
  11739. } else if ( customAttribute.size === 2 ) {
  11740. for ( ca = 0; ca < cal; ca ++ ) {
  11741. value = customAttribute.value[ ca ];
  11742. customAttribute.array[ offset ] = value.x;
  11743. customAttribute.array[ offset + 1 ] = value.y;
  11744. offset += 2;
  11745. }
  11746. } else if ( customAttribute.size === 3 ) {
  11747. if ( customAttribute.type === "c" ) {
  11748. for ( ca = 0; ca < cal; ca ++ ) {
  11749. value = customAttribute.value[ ca ];
  11750. customAttribute.array[ offset ] = value.r;
  11751. customAttribute.array[ offset + 1 ] = value.g;
  11752. customAttribute.array[ offset + 2 ] = value.b;
  11753. offset += 3;
  11754. }
  11755. } else {
  11756. for ( ca = 0; ca < cal; ca ++ ) {
  11757. value = customAttribute.value[ ca ];
  11758. customAttribute.array[ offset ] = value.x;
  11759. customAttribute.array[ offset + 1 ] = value.y;
  11760. customAttribute.array[ offset + 2 ] = value.z;
  11761. offset += 3;
  11762. }
  11763. }
  11764. } else if ( customAttribute.size === 4 ) {
  11765. for ( ca = 0; ca < cal; ca ++ ) {
  11766. value = customAttribute.value[ ca ];
  11767. customAttribute.array[ offset ] = value.x;
  11768. customAttribute.array[ offset + 1 ] = value.y;
  11769. customAttribute.array[ offset + 2 ] = value.z;
  11770. customAttribute.array[ offset + 3 ] = value.w;
  11771. offset += 4;
  11772. }
  11773. }
  11774. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11775. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11776. }
  11777. }
  11778. }
  11779. };
  11780. function setRibbonBuffers ( geometry, hint ) {
  11781. var v, c, n, vertex, offset, color, normal,
  11782. i, il, ca, cal, customAttribute, value,
  11783. vertices = geometry.vertices,
  11784. colors = geometry.colors,
  11785. normals = geometry.normals,
  11786. vl = vertices.length,
  11787. cl = colors.length,
  11788. nl = normals.length,
  11789. vertexArray = geometry.__vertexArray,
  11790. colorArray = geometry.__colorArray,
  11791. normalArray = geometry.__normalArray,
  11792. dirtyVertices = geometry.verticesNeedUpdate,
  11793. dirtyColors = geometry.colorsNeedUpdate,
  11794. dirtyNormals = geometry.normalsNeedUpdate,
  11795. customAttributes = geometry.__webglCustomAttributesList;
  11796. if ( dirtyVertices ) {
  11797. for ( v = 0; v < vl; v ++ ) {
  11798. vertex = vertices[ v ];
  11799. offset = v * 3;
  11800. vertexArray[ offset ] = vertex.x;
  11801. vertexArray[ offset + 1 ] = vertex.y;
  11802. vertexArray[ offset + 2 ] = vertex.z;
  11803. }
  11804. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11805. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11806. }
  11807. if ( dirtyColors ) {
  11808. for ( c = 0; c < cl; c ++ ) {
  11809. color = colors[ c ];
  11810. offset = c * 3;
  11811. colorArray[ offset ] = color.r;
  11812. colorArray[ offset + 1 ] = color.g;
  11813. colorArray[ offset + 2 ] = color.b;
  11814. }
  11815. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11816. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11817. }
  11818. if ( dirtyNormals ) {
  11819. for ( n = 0; n < nl; n ++ ) {
  11820. normal = normals[ n ];
  11821. offset = n * 3;
  11822. normalArray[ offset ] = normal.x;
  11823. normalArray[ offset + 1 ] = normal.y;
  11824. normalArray[ offset + 2 ] = normal.z;
  11825. }
  11826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11827. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11828. }
  11829. if ( customAttributes ) {
  11830. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11831. customAttribute = customAttributes[ i ];
  11832. if ( customAttribute.needsUpdate &&
  11833. ( customAttribute.boundTo === undefined ||
  11834. customAttribute.boundTo === "vertices" ) ) {
  11835. offset = 0;
  11836. cal = customAttribute.value.length;
  11837. if ( customAttribute.size === 1 ) {
  11838. for ( ca = 0; ca < cal; ca ++ ) {
  11839. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11840. }
  11841. } else if ( customAttribute.size === 2 ) {
  11842. for ( ca = 0; ca < cal; ca ++ ) {
  11843. value = customAttribute.value[ ca ];
  11844. customAttribute.array[ offset ] = value.x;
  11845. customAttribute.array[ offset + 1 ] = value.y;
  11846. offset += 2;
  11847. }
  11848. } else if ( customAttribute.size === 3 ) {
  11849. if ( customAttribute.type === "c" ) {
  11850. for ( ca = 0; ca < cal; ca ++ ) {
  11851. value = customAttribute.value[ ca ];
  11852. customAttribute.array[ offset ] = value.r;
  11853. customAttribute.array[ offset + 1 ] = value.g;
  11854. customAttribute.array[ offset + 2 ] = value.b;
  11855. offset += 3;
  11856. }
  11857. } else {
  11858. for ( ca = 0; ca < cal; ca ++ ) {
  11859. value = customAttribute.value[ ca ];
  11860. customAttribute.array[ offset ] = value.x;
  11861. customAttribute.array[ offset + 1 ] = value.y;
  11862. customAttribute.array[ offset + 2 ] = value.z;
  11863. offset += 3;
  11864. }
  11865. }
  11866. } else if ( customAttribute.size === 4 ) {
  11867. for ( ca = 0; ca < cal; ca ++ ) {
  11868. value = customAttribute.value[ ca ];
  11869. customAttribute.array[ offset ] = value.x;
  11870. customAttribute.array[ offset + 1 ] = value.y;
  11871. customAttribute.array[ offset + 2 ] = value.z;
  11872. customAttribute.array[ offset + 3 ] = value.w;
  11873. offset += 4;
  11874. }
  11875. }
  11876. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11877. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11878. }
  11879. }
  11880. }
  11881. };
  11882. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11883. if ( ! geometryGroup.__inittedArrays ) {
  11884. return;
  11885. }
  11886. var normalType = bufferGuessNormalType( material ),
  11887. vertexColorType = bufferGuessVertexColorType( material ),
  11888. uvType = bufferGuessUVType( material ),
  11889. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11890. var f, fl, fi, face,
  11891. vertexNormals, faceNormal, normal,
  11892. vertexColors, faceColor,
  11893. vertexTangents,
  11894. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11895. c1, c2, c3, c4,
  11896. sw1, sw2, sw3, sw4,
  11897. si1, si2, si3, si4,
  11898. sa1, sa2, sa3, sa4,
  11899. sb1, sb2, sb3, sb4,
  11900. m, ml, i, il,
  11901. vn, uvi, uv2i,
  11902. vk, vkl, vka,
  11903. nka, chf, faceVertexNormals,
  11904. a,
  11905. vertexIndex = 0,
  11906. offset = 0,
  11907. offset_uv = 0,
  11908. offset_uv2 = 0,
  11909. offset_face = 0,
  11910. offset_normal = 0,
  11911. offset_tangent = 0,
  11912. offset_line = 0,
  11913. offset_color = 0,
  11914. offset_skin = 0,
  11915. offset_morphTarget = 0,
  11916. offset_custom = 0,
  11917. offset_customSrc = 0,
  11918. value,
  11919. vertexArray = geometryGroup.__vertexArray,
  11920. uvArray = geometryGroup.__uvArray,
  11921. uv2Array = geometryGroup.__uv2Array,
  11922. normalArray = geometryGroup.__normalArray,
  11923. tangentArray = geometryGroup.__tangentArray,
  11924. colorArray = geometryGroup.__colorArray,
  11925. skinIndexArray = geometryGroup.__skinIndexArray,
  11926. skinWeightArray = geometryGroup.__skinWeightArray,
  11927. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11928. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11929. customAttributes = geometryGroup.__webglCustomAttributesList,
  11930. customAttribute,
  11931. faceArray = geometryGroup.__faceArray,
  11932. lineArray = geometryGroup.__lineArray,
  11933. geometry = object.geometry, // this is shared for all chunks
  11934. dirtyVertices = geometry.verticesNeedUpdate,
  11935. dirtyElements = geometry.elementsNeedUpdate,
  11936. dirtyUvs = geometry.uvsNeedUpdate,
  11937. dirtyNormals = geometry.normalsNeedUpdate,
  11938. dirtyTangents = geometry.tangentsNeedUpdate,
  11939. dirtyColors = geometry.colorsNeedUpdate,
  11940. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11941. vertices = geometry.vertices,
  11942. chunk_faces3 = geometryGroup.faces3,
  11943. chunk_faces4 = geometryGroup.faces4,
  11944. obj_faces = geometry.faces,
  11945. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11946. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11947. obj_colors = geometry.colors,
  11948. obj_skinIndices = geometry.skinIndices,
  11949. obj_skinWeights = geometry.skinWeights,
  11950. morphTargets = geometry.morphTargets,
  11951. morphNormals = geometry.morphNormals;
  11952. if ( dirtyVertices ) {
  11953. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11954. face = obj_faces[ chunk_faces3[ f ] ];
  11955. v1 = vertices[ face.a ];
  11956. v2 = vertices[ face.b ];
  11957. v3 = vertices[ face.c ];
  11958. vertexArray[ offset ] = v1.x;
  11959. vertexArray[ offset + 1 ] = v1.y;
  11960. vertexArray[ offset + 2 ] = v1.z;
  11961. vertexArray[ offset + 3 ] = v2.x;
  11962. vertexArray[ offset + 4 ] = v2.y;
  11963. vertexArray[ offset + 5 ] = v2.z;
  11964. vertexArray[ offset + 6 ] = v3.x;
  11965. vertexArray[ offset + 7 ] = v3.y;
  11966. vertexArray[ offset + 8 ] = v3.z;
  11967. offset += 9;
  11968. }
  11969. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11970. face = obj_faces[ chunk_faces4[ f ] ];
  11971. v1 = vertices[ face.a ];
  11972. v2 = vertices[ face.b ];
  11973. v3 = vertices[ face.c ];
  11974. v4 = vertices[ face.d ];
  11975. vertexArray[ offset ] = v1.x;
  11976. vertexArray[ offset + 1 ] = v1.y;
  11977. vertexArray[ offset + 2 ] = v1.z;
  11978. vertexArray[ offset + 3 ] = v2.x;
  11979. vertexArray[ offset + 4 ] = v2.y;
  11980. vertexArray[ offset + 5 ] = v2.z;
  11981. vertexArray[ offset + 6 ] = v3.x;
  11982. vertexArray[ offset + 7 ] = v3.y;
  11983. vertexArray[ offset + 8 ] = v3.z;
  11984. vertexArray[ offset + 9 ] = v4.x;
  11985. vertexArray[ offset + 10 ] = v4.y;
  11986. vertexArray[ offset + 11 ] = v4.z;
  11987. offset += 12;
  11988. }
  11989. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11990. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11991. }
  11992. if ( dirtyMorphTargets ) {
  11993. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11994. offset_morphTarget = 0;
  11995. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11996. chf = chunk_faces3[ f ];
  11997. face = obj_faces[ chf ];
  11998. // morph positions
  11999. v1 = morphTargets[ vk ].vertices[ face.a ];
  12000. v2 = morphTargets[ vk ].vertices[ face.b ];
  12001. v3 = morphTargets[ vk ].vertices[ face.c ];
  12002. vka = morphTargetsArrays[ vk ];
  12003. vka[ offset_morphTarget ] = v1.x;
  12004. vka[ offset_morphTarget + 1 ] = v1.y;
  12005. vka[ offset_morphTarget + 2 ] = v1.z;
  12006. vka[ offset_morphTarget + 3 ] = v2.x;
  12007. vka[ offset_morphTarget + 4 ] = v2.y;
  12008. vka[ offset_morphTarget + 5 ] = v2.z;
  12009. vka[ offset_morphTarget + 6 ] = v3.x;
  12010. vka[ offset_morphTarget + 7 ] = v3.y;
  12011. vka[ offset_morphTarget + 8 ] = v3.z;
  12012. // morph normals
  12013. if ( material.morphNormals ) {
  12014. if ( needsSmoothNormals ) {
  12015. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12016. n1 = faceVertexNormals.a;
  12017. n2 = faceVertexNormals.b;
  12018. n3 = faceVertexNormals.c;
  12019. } else {
  12020. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12021. n2 = n1;
  12022. n3 = n1;
  12023. }
  12024. nka = morphNormalsArrays[ vk ];
  12025. nka[ offset_morphTarget ] = n1.x;
  12026. nka[ offset_morphTarget + 1 ] = n1.y;
  12027. nka[ offset_morphTarget + 2 ] = n1.z;
  12028. nka[ offset_morphTarget + 3 ] = n2.x;
  12029. nka[ offset_morphTarget + 4 ] = n2.y;
  12030. nka[ offset_morphTarget + 5 ] = n2.z;
  12031. nka[ offset_morphTarget + 6 ] = n3.x;
  12032. nka[ offset_morphTarget + 7 ] = n3.y;
  12033. nka[ offset_morphTarget + 8 ] = n3.z;
  12034. }
  12035. //
  12036. offset_morphTarget += 9;
  12037. }
  12038. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12039. chf = chunk_faces4[ f ];
  12040. face = obj_faces[ chf ];
  12041. // morph positions
  12042. v1 = morphTargets[ vk ].vertices[ face.a ];
  12043. v2 = morphTargets[ vk ].vertices[ face.b ];
  12044. v3 = morphTargets[ vk ].vertices[ face.c ];
  12045. v4 = morphTargets[ vk ].vertices[ face.d ];
  12046. vka = morphTargetsArrays[ vk ];
  12047. vka[ offset_morphTarget ] = v1.x;
  12048. vka[ offset_morphTarget + 1 ] = v1.y;
  12049. vka[ offset_morphTarget + 2 ] = v1.z;
  12050. vka[ offset_morphTarget + 3 ] = v2.x;
  12051. vka[ offset_morphTarget + 4 ] = v2.y;
  12052. vka[ offset_morphTarget + 5 ] = v2.z;
  12053. vka[ offset_morphTarget + 6 ] = v3.x;
  12054. vka[ offset_morphTarget + 7 ] = v3.y;
  12055. vka[ offset_morphTarget + 8 ] = v3.z;
  12056. vka[ offset_morphTarget + 9 ] = v4.x;
  12057. vka[ offset_morphTarget + 10 ] = v4.y;
  12058. vka[ offset_morphTarget + 11 ] = v4.z;
  12059. // morph normals
  12060. if ( material.morphNormals ) {
  12061. if ( needsSmoothNormals ) {
  12062. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12063. n1 = faceVertexNormals.a;
  12064. n2 = faceVertexNormals.b;
  12065. n3 = faceVertexNormals.c;
  12066. n4 = faceVertexNormals.d;
  12067. } else {
  12068. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12069. n2 = n1;
  12070. n3 = n1;
  12071. n4 = n1;
  12072. }
  12073. nka = morphNormalsArrays[ vk ];
  12074. nka[ offset_morphTarget ] = n1.x;
  12075. nka[ offset_morphTarget + 1 ] = n1.y;
  12076. nka[ offset_morphTarget + 2 ] = n1.z;
  12077. nka[ offset_morphTarget + 3 ] = n2.x;
  12078. nka[ offset_morphTarget + 4 ] = n2.y;
  12079. nka[ offset_morphTarget + 5 ] = n2.z;
  12080. nka[ offset_morphTarget + 6 ] = n3.x;
  12081. nka[ offset_morphTarget + 7 ] = n3.y;
  12082. nka[ offset_morphTarget + 8 ] = n3.z;
  12083. nka[ offset_morphTarget + 9 ] = n4.x;
  12084. nka[ offset_morphTarget + 10 ] = n4.y;
  12085. nka[ offset_morphTarget + 11 ] = n4.z;
  12086. }
  12087. //
  12088. offset_morphTarget += 12;
  12089. }
  12090. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12091. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12092. if ( material.morphNormals ) {
  12093. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12094. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12095. }
  12096. }
  12097. }
  12098. if ( obj_skinWeights.length ) {
  12099. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12100. face = obj_faces[ chunk_faces3[ f ] ];
  12101. // weights
  12102. sw1 = obj_skinWeights[ face.a ];
  12103. sw2 = obj_skinWeights[ face.b ];
  12104. sw3 = obj_skinWeights[ face.c ];
  12105. skinWeightArray[ offset_skin ] = sw1.x;
  12106. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12107. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12108. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12109. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12110. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12111. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12112. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12113. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12114. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12115. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12116. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12117. // indices
  12118. si1 = obj_skinIndices[ face.a ];
  12119. si2 = obj_skinIndices[ face.b ];
  12120. si3 = obj_skinIndices[ face.c ];
  12121. skinIndexArray[ offset_skin ] = si1.x;
  12122. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12123. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12124. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12125. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12126. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12127. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12128. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12129. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12130. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12131. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12132. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12133. offset_skin += 12;
  12134. }
  12135. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12136. face = obj_faces[ chunk_faces4[ f ] ];
  12137. // weights
  12138. sw1 = obj_skinWeights[ face.a ];
  12139. sw2 = obj_skinWeights[ face.b ];
  12140. sw3 = obj_skinWeights[ face.c ];
  12141. sw4 = obj_skinWeights[ face.d ];
  12142. skinWeightArray[ offset_skin ] = sw1.x;
  12143. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12144. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12145. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12146. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12147. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12148. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12149. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12150. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12151. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12152. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12153. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12154. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12155. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12156. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12157. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12158. // indices
  12159. si1 = obj_skinIndices[ face.a ];
  12160. si2 = obj_skinIndices[ face.b ];
  12161. si3 = obj_skinIndices[ face.c ];
  12162. si4 = obj_skinIndices[ face.d ];
  12163. skinIndexArray[ offset_skin ] = si1.x;
  12164. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12165. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12166. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12167. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12168. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12169. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12170. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12171. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12172. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12173. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12174. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12175. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12176. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12177. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12178. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12179. offset_skin += 16;
  12180. }
  12181. if ( offset_skin > 0 ) {
  12182. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12183. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12185. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12186. }
  12187. }
  12188. if ( dirtyColors && vertexColorType ) {
  12189. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12190. face = obj_faces[ chunk_faces3[ f ] ];
  12191. vertexColors = face.vertexColors;
  12192. faceColor = face.color;
  12193. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12194. c1 = vertexColors[ 0 ];
  12195. c2 = vertexColors[ 1 ];
  12196. c3 = vertexColors[ 2 ];
  12197. } else {
  12198. c1 = faceColor;
  12199. c2 = faceColor;
  12200. c3 = faceColor;
  12201. }
  12202. colorArray[ offset_color ] = c1.r;
  12203. colorArray[ offset_color + 1 ] = c1.g;
  12204. colorArray[ offset_color + 2 ] = c1.b;
  12205. colorArray[ offset_color + 3 ] = c2.r;
  12206. colorArray[ offset_color + 4 ] = c2.g;
  12207. colorArray[ offset_color + 5 ] = c2.b;
  12208. colorArray[ offset_color + 6 ] = c3.r;
  12209. colorArray[ offset_color + 7 ] = c3.g;
  12210. colorArray[ offset_color + 8 ] = c3.b;
  12211. offset_color += 9;
  12212. }
  12213. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12214. face = obj_faces[ chunk_faces4[ f ] ];
  12215. vertexColors = face.vertexColors;
  12216. faceColor = face.color;
  12217. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12218. c1 = vertexColors[ 0 ];
  12219. c2 = vertexColors[ 1 ];
  12220. c3 = vertexColors[ 2 ];
  12221. c4 = vertexColors[ 3 ];
  12222. } else {
  12223. c1 = faceColor;
  12224. c2 = faceColor;
  12225. c3 = faceColor;
  12226. c4 = faceColor;
  12227. }
  12228. colorArray[ offset_color ] = c1.r;
  12229. colorArray[ offset_color + 1 ] = c1.g;
  12230. colorArray[ offset_color + 2 ] = c1.b;
  12231. colorArray[ offset_color + 3 ] = c2.r;
  12232. colorArray[ offset_color + 4 ] = c2.g;
  12233. colorArray[ offset_color + 5 ] = c2.b;
  12234. colorArray[ offset_color + 6 ] = c3.r;
  12235. colorArray[ offset_color + 7 ] = c3.g;
  12236. colorArray[ offset_color + 8 ] = c3.b;
  12237. colorArray[ offset_color + 9 ] = c4.r;
  12238. colorArray[ offset_color + 10 ] = c4.g;
  12239. colorArray[ offset_color + 11 ] = c4.b;
  12240. offset_color += 12;
  12241. }
  12242. if ( offset_color > 0 ) {
  12243. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12244. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12245. }
  12246. }
  12247. if ( dirtyTangents && geometry.hasTangents ) {
  12248. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12249. face = obj_faces[ chunk_faces3[ f ] ];
  12250. vertexTangents = face.vertexTangents;
  12251. t1 = vertexTangents[ 0 ];
  12252. t2 = vertexTangents[ 1 ];
  12253. t3 = vertexTangents[ 2 ];
  12254. tangentArray[ offset_tangent ] = t1.x;
  12255. tangentArray[ offset_tangent + 1 ] = t1.y;
  12256. tangentArray[ offset_tangent + 2 ] = t1.z;
  12257. tangentArray[ offset_tangent + 3 ] = t1.w;
  12258. tangentArray[ offset_tangent + 4 ] = t2.x;
  12259. tangentArray[ offset_tangent + 5 ] = t2.y;
  12260. tangentArray[ offset_tangent + 6 ] = t2.z;
  12261. tangentArray[ offset_tangent + 7 ] = t2.w;
  12262. tangentArray[ offset_tangent + 8 ] = t3.x;
  12263. tangentArray[ offset_tangent + 9 ] = t3.y;
  12264. tangentArray[ offset_tangent + 10 ] = t3.z;
  12265. tangentArray[ offset_tangent + 11 ] = t3.w;
  12266. offset_tangent += 12;
  12267. }
  12268. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12269. face = obj_faces[ chunk_faces4[ f ] ];
  12270. vertexTangents = face.vertexTangents;
  12271. t1 = vertexTangents[ 0 ];
  12272. t2 = vertexTangents[ 1 ];
  12273. t3 = vertexTangents[ 2 ];
  12274. t4 = vertexTangents[ 3 ];
  12275. tangentArray[ offset_tangent ] = t1.x;
  12276. tangentArray[ offset_tangent + 1 ] = t1.y;
  12277. tangentArray[ offset_tangent + 2 ] = t1.z;
  12278. tangentArray[ offset_tangent + 3 ] = t1.w;
  12279. tangentArray[ offset_tangent + 4 ] = t2.x;
  12280. tangentArray[ offset_tangent + 5 ] = t2.y;
  12281. tangentArray[ offset_tangent + 6 ] = t2.z;
  12282. tangentArray[ offset_tangent + 7 ] = t2.w;
  12283. tangentArray[ offset_tangent + 8 ] = t3.x;
  12284. tangentArray[ offset_tangent + 9 ] = t3.y;
  12285. tangentArray[ offset_tangent + 10 ] = t3.z;
  12286. tangentArray[ offset_tangent + 11 ] = t3.w;
  12287. tangentArray[ offset_tangent + 12 ] = t4.x;
  12288. tangentArray[ offset_tangent + 13 ] = t4.y;
  12289. tangentArray[ offset_tangent + 14 ] = t4.z;
  12290. tangentArray[ offset_tangent + 15 ] = t4.w;
  12291. offset_tangent += 16;
  12292. }
  12293. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12294. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12295. }
  12296. if ( dirtyNormals && normalType ) {
  12297. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12298. face = obj_faces[ chunk_faces3[ f ] ];
  12299. vertexNormals = face.vertexNormals;
  12300. faceNormal = face.normal;
  12301. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12302. for ( i = 0; i < 3; i ++ ) {
  12303. vn = vertexNormals[ i ];
  12304. normalArray[ offset_normal ] = vn.x;
  12305. normalArray[ offset_normal + 1 ] = vn.y;
  12306. normalArray[ offset_normal + 2 ] = vn.z;
  12307. offset_normal += 3;
  12308. }
  12309. } else {
  12310. for ( i = 0; i < 3; i ++ ) {
  12311. normalArray[ offset_normal ] = faceNormal.x;
  12312. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12313. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12314. offset_normal += 3;
  12315. }
  12316. }
  12317. }
  12318. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12319. face = obj_faces[ chunk_faces4[ f ] ];
  12320. vertexNormals = face.vertexNormals;
  12321. faceNormal = face.normal;
  12322. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12323. for ( i = 0; i < 4; i ++ ) {
  12324. vn = vertexNormals[ i ];
  12325. normalArray[ offset_normal ] = vn.x;
  12326. normalArray[ offset_normal + 1 ] = vn.y;
  12327. normalArray[ offset_normal + 2 ] = vn.z;
  12328. offset_normal += 3;
  12329. }
  12330. } else {
  12331. for ( i = 0; i < 4; i ++ ) {
  12332. normalArray[ offset_normal ] = faceNormal.x;
  12333. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12334. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12335. offset_normal += 3;
  12336. }
  12337. }
  12338. }
  12339. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12340. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12341. }
  12342. if ( dirtyUvs && obj_uvs && uvType ) {
  12343. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12344. fi = chunk_faces3[ f ];
  12345. uv = obj_uvs[ fi ];
  12346. if ( uv === undefined ) continue;
  12347. for ( i = 0; i < 3; i ++ ) {
  12348. uvi = uv[ i ];
  12349. uvArray[ offset_uv ] = uvi.x;
  12350. uvArray[ offset_uv + 1 ] = uvi.y;
  12351. offset_uv += 2;
  12352. }
  12353. }
  12354. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12355. fi = chunk_faces4[ f ];
  12356. uv = obj_uvs[ fi ];
  12357. if ( uv === undefined ) continue;
  12358. for ( i = 0; i < 4; i ++ ) {
  12359. uvi = uv[ i ];
  12360. uvArray[ offset_uv ] = uvi.x;
  12361. uvArray[ offset_uv + 1 ] = uvi.y;
  12362. offset_uv += 2;
  12363. }
  12364. }
  12365. if ( offset_uv > 0 ) {
  12366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12367. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12368. }
  12369. }
  12370. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12371. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12372. fi = chunk_faces3[ f ];
  12373. uv2 = obj_uvs2[ fi ];
  12374. if ( uv2 === undefined ) continue;
  12375. for ( i = 0; i < 3; i ++ ) {
  12376. uv2i = uv2[ i ];
  12377. uv2Array[ offset_uv2 ] = uv2i.x;
  12378. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12379. offset_uv2 += 2;
  12380. }
  12381. }
  12382. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12383. fi = chunk_faces4[ f ];
  12384. uv2 = obj_uvs2[ fi ];
  12385. if ( uv2 === undefined ) continue;
  12386. for ( i = 0; i < 4; i ++ ) {
  12387. uv2i = uv2[ i ];
  12388. uv2Array[ offset_uv2 ] = uv2i.x;
  12389. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12390. offset_uv2 += 2;
  12391. }
  12392. }
  12393. if ( offset_uv2 > 0 ) {
  12394. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12395. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12396. }
  12397. }
  12398. if ( dirtyElements ) {
  12399. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12400. faceArray[ offset_face ] = vertexIndex;
  12401. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12402. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12403. offset_face += 3;
  12404. lineArray[ offset_line ] = vertexIndex;
  12405. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12406. lineArray[ offset_line + 2 ] = vertexIndex;
  12407. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12408. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12409. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12410. offset_line += 6;
  12411. vertexIndex += 3;
  12412. }
  12413. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12414. faceArray[ offset_face ] = vertexIndex;
  12415. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12416. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12417. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12418. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12419. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12420. offset_face += 6;
  12421. lineArray[ offset_line ] = vertexIndex;
  12422. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12423. lineArray[ offset_line + 2 ] = vertexIndex;
  12424. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12425. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12426. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12427. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12428. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12429. offset_line += 8;
  12430. vertexIndex += 4;
  12431. }
  12432. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12433. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12434. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12435. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12436. }
  12437. if ( customAttributes ) {
  12438. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12439. customAttribute = customAttributes[ i ];
  12440. if ( ! customAttribute.__original.needsUpdate ) continue;
  12441. offset_custom = 0;
  12442. offset_customSrc = 0;
  12443. if ( customAttribute.size === 1 ) {
  12444. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12445. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12446. face = obj_faces[ chunk_faces3[ f ] ];
  12447. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12448. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12449. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12450. offset_custom += 3;
  12451. }
  12452. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12453. face = obj_faces[ chunk_faces4[ f ] ];
  12454. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12455. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12456. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12457. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12458. offset_custom += 4;
  12459. }
  12460. } else if ( customAttribute.boundTo === "faces" ) {
  12461. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12462. value = customAttribute.value[ chunk_faces3[ f ] ];
  12463. customAttribute.array[ offset_custom ] = value;
  12464. customAttribute.array[ offset_custom + 1 ] = value;
  12465. customAttribute.array[ offset_custom + 2 ] = value;
  12466. offset_custom += 3;
  12467. }
  12468. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12469. value = customAttribute.value[ chunk_faces4[ f ] ];
  12470. customAttribute.array[ offset_custom ] = value;
  12471. customAttribute.array[ offset_custom + 1 ] = value;
  12472. customAttribute.array[ offset_custom + 2 ] = value;
  12473. customAttribute.array[ offset_custom + 3 ] = value;
  12474. offset_custom += 4;
  12475. }
  12476. }
  12477. } else if ( customAttribute.size === 2 ) {
  12478. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12479. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12480. face = obj_faces[ chunk_faces3[ f ] ];
  12481. v1 = customAttribute.value[ face.a ];
  12482. v2 = customAttribute.value[ face.b ];
  12483. v3 = customAttribute.value[ face.c ];
  12484. customAttribute.array[ offset_custom ] = v1.x;
  12485. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12486. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12487. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12488. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12489. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12490. offset_custom += 6;
  12491. }
  12492. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12493. face = obj_faces[ chunk_faces4[ f ] ];
  12494. v1 = customAttribute.value[ face.a ];
  12495. v2 = customAttribute.value[ face.b ];
  12496. v3 = customAttribute.value[ face.c ];
  12497. v4 = customAttribute.value[ face.d ];
  12498. customAttribute.array[ offset_custom ] = v1.x;
  12499. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12500. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12501. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12502. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12503. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12504. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12505. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12506. offset_custom += 8;
  12507. }
  12508. } else if ( customAttribute.boundTo === "faces" ) {
  12509. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12510. value = customAttribute.value[ chunk_faces3[ f ] ];
  12511. v1 = value;
  12512. v2 = value;
  12513. v3 = value;
  12514. customAttribute.array[ offset_custom ] = v1.x;
  12515. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12516. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12517. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12518. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12519. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12520. offset_custom += 6;
  12521. }
  12522. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12523. value = customAttribute.value[ chunk_faces4[ f ] ];
  12524. v1 = value;
  12525. v2 = value;
  12526. v3 = value;
  12527. v4 = value;
  12528. customAttribute.array[ offset_custom ] = v1.x;
  12529. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12530. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12531. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12532. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12533. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12534. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12535. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12536. offset_custom += 8;
  12537. }
  12538. }
  12539. } else if ( customAttribute.size === 3 ) {
  12540. var pp;
  12541. if ( customAttribute.type === "c" ) {
  12542. pp = [ "r", "g", "b" ];
  12543. } else {
  12544. pp = [ "x", "y", "z" ];
  12545. }
  12546. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12547. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12548. face = obj_faces[ chunk_faces3[ f ] ];
  12549. v1 = customAttribute.value[ face.a ];
  12550. v2 = customAttribute.value[ face.b ];
  12551. v3 = customAttribute.value[ face.c ];
  12552. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12553. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12554. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12555. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12556. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12557. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12558. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12559. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12560. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12561. offset_custom += 9;
  12562. }
  12563. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12564. face = obj_faces[ chunk_faces4[ f ] ];
  12565. v1 = customAttribute.value[ face.a ];
  12566. v2 = customAttribute.value[ face.b ];
  12567. v3 = customAttribute.value[ face.c ];
  12568. v4 = customAttribute.value[ face.d ];
  12569. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12570. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12571. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12572. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12573. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12574. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12575. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12576. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12577. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12578. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12579. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12580. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12581. offset_custom += 12;
  12582. }
  12583. } else if ( customAttribute.boundTo === "faces" ) {
  12584. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12585. value = customAttribute.value[ chunk_faces3[ f ] ];
  12586. v1 = value;
  12587. v2 = value;
  12588. v3 = value;
  12589. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12590. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12591. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12592. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12593. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12594. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12595. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12596. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12597. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12598. offset_custom += 9;
  12599. }
  12600. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12601. value = customAttribute.value[ chunk_faces4[ f ] ];
  12602. v1 = value;
  12603. v2 = value;
  12604. v3 = value;
  12605. v4 = value;
  12606. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12607. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12608. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12609. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12610. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12611. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12612. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12613. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12614. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12615. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12616. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12617. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12618. offset_custom += 12;
  12619. }
  12620. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12621. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12622. value = customAttribute.value[ chunk_faces3[ f ] ];
  12623. v1 = value[ 0 ];
  12624. v2 = value[ 1 ];
  12625. v3 = value[ 2 ];
  12626. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12627. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12628. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12629. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12630. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12631. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12632. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12633. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12634. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12635. offset_custom += 9;
  12636. }
  12637. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12638. value = customAttribute.value[ chunk_faces4[ f ] ];
  12639. v1 = value[ 0 ];
  12640. v2 = value[ 1 ];
  12641. v3 = value[ 2 ];
  12642. v4 = value[ 3 ];
  12643. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12644. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12645. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12646. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12647. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12648. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12649. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12650. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12651. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12652. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12653. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12654. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12655. offset_custom += 12;
  12656. }
  12657. }
  12658. } else if ( customAttribute.size === 4 ) {
  12659. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12660. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12661. face = obj_faces[ chunk_faces3[ f ] ];
  12662. v1 = customAttribute.value[ face.a ];
  12663. v2 = customAttribute.value[ face.b ];
  12664. v3 = customAttribute.value[ face.c ];
  12665. customAttribute.array[ offset_custom ] = v1.x;
  12666. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12667. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12668. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12669. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12670. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12671. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12672. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12673. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12674. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12675. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12676. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12677. offset_custom += 12;
  12678. }
  12679. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12680. face = obj_faces[ chunk_faces4[ f ] ];
  12681. v1 = customAttribute.value[ face.a ];
  12682. v2 = customAttribute.value[ face.b ];
  12683. v3 = customAttribute.value[ face.c ];
  12684. v4 = customAttribute.value[ face.d ];
  12685. customAttribute.array[ offset_custom ] = v1.x;
  12686. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12687. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12688. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12689. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12690. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12691. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12692. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12693. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12694. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12695. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12696. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12697. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12698. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12699. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12700. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12701. offset_custom += 16;
  12702. }
  12703. } else if ( customAttribute.boundTo === "faces" ) {
  12704. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12705. value = customAttribute.value[ chunk_faces3[ f ] ];
  12706. v1 = value;
  12707. v2 = value;
  12708. v3 = value;
  12709. customAttribute.array[ offset_custom ] = v1.x;
  12710. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12711. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12712. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12713. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12714. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12715. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12716. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12717. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12718. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12719. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12720. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12721. offset_custom += 12;
  12722. }
  12723. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12724. value = customAttribute.value[ chunk_faces4[ f ] ];
  12725. v1 = value;
  12726. v2 = value;
  12727. v3 = value;
  12728. v4 = value;
  12729. customAttribute.array[ offset_custom ] = v1.x;
  12730. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12731. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12732. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12733. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12734. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12735. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12736. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12737. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12738. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12739. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12740. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12741. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12742. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12743. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12744. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12745. offset_custom += 16;
  12746. }
  12747. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12748. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12749. value = customAttribute.value[ chunk_faces3[ f ] ];
  12750. v1 = value[ 0 ];
  12751. v2 = value[ 1 ];
  12752. v3 = value[ 2 ];
  12753. customAttribute.array[ offset_custom ] = v1.x;
  12754. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12755. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12756. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12757. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12758. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12759. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12760. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12761. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12762. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12763. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12764. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12765. offset_custom += 12;
  12766. }
  12767. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12768. value = customAttribute.value[ chunk_faces4[ f ] ];
  12769. v1 = value[ 0 ];
  12770. v2 = value[ 1 ];
  12771. v3 = value[ 2 ];
  12772. v4 = value[ 3 ];
  12773. customAttribute.array[ offset_custom ] = v1.x;
  12774. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12775. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12776. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12777. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12778. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12779. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12780. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12781. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12782. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12783. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12784. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12785. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12786. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12787. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12788. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12789. offset_custom += 16;
  12790. }
  12791. }
  12792. }
  12793. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12794. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12795. }
  12796. }
  12797. if ( dispose ) {
  12798. delete geometryGroup.__inittedArrays;
  12799. delete geometryGroup.__colorArray;
  12800. delete geometryGroup.__normalArray;
  12801. delete geometryGroup.__tangentArray;
  12802. delete geometryGroup.__uvArray;
  12803. delete geometryGroup.__uv2Array;
  12804. delete geometryGroup.__faceArray;
  12805. delete geometryGroup.__vertexArray;
  12806. delete geometryGroup.__lineArray;
  12807. delete geometryGroup.__skinIndexArray;
  12808. delete geometryGroup.__skinWeightArray;
  12809. }
  12810. };
  12811. function setDirectBuffers ( geometry, hint, dispose ) {
  12812. var attributes = geometry.attributes;
  12813. var attributeName, attributeItem;
  12814. for ( attributeName in attributes ) {
  12815. attributeItem = attributes[ attributeName ];
  12816. if ( attributeItem.needsUpdate ) {
  12817. if ( attributeName === 'index' ) {
  12818. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12819. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12820. } else {
  12821. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12822. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12823. }
  12824. attributeItem.needsUpdate = false;
  12825. }
  12826. if ( dispose && ! attributeItem.dynamic ) {
  12827. delete attributeItem.array;
  12828. }
  12829. }
  12830. };
  12831. // Buffer rendering
  12832. this.renderBufferImmediate = function ( object, program, material ) {
  12833. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12834. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12835. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12836. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12837. if ( object.hasPositions ) {
  12838. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12839. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12840. _gl.enableVertexAttribArray( program.attributes.position );
  12841. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12842. }
  12843. if ( object.hasNormals ) {
  12844. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12845. if ( material.shading === THREE.FlatShading ) {
  12846. var nx, ny, nz,
  12847. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12848. normalArray,
  12849. i, il = object.count * 3;
  12850. for( i = 0; i < il; i += 9 ) {
  12851. normalArray = object.normalArray;
  12852. nax = normalArray[ i ];
  12853. nay = normalArray[ i + 1 ];
  12854. naz = normalArray[ i + 2 ];
  12855. nbx = normalArray[ i + 3 ];
  12856. nby = normalArray[ i + 4 ];
  12857. nbz = normalArray[ i + 5 ];
  12858. ncx = normalArray[ i + 6 ];
  12859. ncy = normalArray[ i + 7 ];
  12860. ncz = normalArray[ i + 8 ];
  12861. nx = ( nax + nbx + ncx ) / 3;
  12862. ny = ( nay + nby + ncy ) / 3;
  12863. nz = ( naz + nbz + ncz ) / 3;
  12864. normalArray[ i ] = nx;
  12865. normalArray[ i + 1 ] = ny;
  12866. normalArray[ i + 2 ] = nz;
  12867. normalArray[ i + 3 ] = nx;
  12868. normalArray[ i + 4 ] = ny;
  12869. normalArray[ i + 5 ] = nz;
  12870. normalArray[ i + 6 ] = nx;
  12871. normalArray[ i + 7 ] = ny;
  12872. normalArray[ i + 8 ] = nz;
  12873. }
  12874. }
  12875. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12876. _gl.enableVertexAttribArray( program.attributes.normal );
  12877. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12878. }
  12879. if ( object.hasUvs && material.map ) {
  12880. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12881. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12882. _gl.enableVertexAttribArray( program.attributes.uv );
  12883. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12884. }
  12885. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12886. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12887. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12888. _gl.enableVertexAttribArray( program.attributes.color );
  12889. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12890. }
  12891. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12892. object.count = 0;
  12893. };
  12894. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12895. if ( material.visible === false ) return;
  12896. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  12897. var attributeItem, attributeName, attributePointer, attributeSize;
  12898. program = setProgram( camera, lights, fog, material, object );
  12899. programAttributes = program.attributes;
  12900. geometryAttributes = geometry.attributes;
  12901. var updateBuffers = false,
  12902. wireframeBit = material.wireframe ? 1 : 0,
  12903. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12904. if ( geometryHash !== _currentGeometryGroupHash ) {
  12905. _currentGeometryGroupHash = geometryHash;
  12906. updateBuffers = true;
  12907. }
  12908. if ( updateBuffers ) {
  12909. disableAttributes();
  12910. }
  12911. // render mesh
  12912. if ( object instanceof THREE.Mesh ) {
  12913. var index = geometryAttributes[ "index" ];
  12914. // indexed triangles
  12915. if ( index ) {
  12916. var offsets = geometry.offsets;
  12917. // if there is more than 1 chunk
  12918. // must set attribute pointers to use new offsets for each chunk
  12919. // even if geometry and materials didn't change
  12920. if ( offsets.length > 1 ) updateBuffers = true;
  12921. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12922. var startIndex = offsets[ i ].index;
  12923. if ( updateBuffers ) {
  12924. for ( attributeName in geometryAttributes ) {
  12925. if ( attributeName === 'index' ) continue;
  12926. attributePointer = programAttributes[ attributeName ];
  12927. attributeItem = geometryAttributes[ attributeName ];
  12928. attributeSize = attributeItem.itemSize;
  12929. if ( attributePointer >= 0 ) {
  12930. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12931. enableAttribute( attributePointer );
  12932. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  12933. }
  12934. }
  12935. // indices
  12936. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12937. }
  12938. // render indexed triangles
  12939. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12940. _this.info.render.calls ++;
  12941. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12942. _this.info.render.faces += offsets[ i ].count / 3;
  12943. }
  12944. // non-indexed triangles
  12945. } else {
  12946. if ( updateBuffers ) {
  12947. for ( attributeName in geometryAttributes ) {
  12948. if ( attributeName === 'index') continue;
  12949. attributePointer = programAttributes[ attributeName ];
  12950. attributeItem = geometryAttributes[ attributeName ];
  12951. attributeSize = attributeItem.itemSize;
  12952. if ( attributePointer >= 0 ) {
  12953. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12954. enableAttribute( attributePointer );
  12955. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  12956. }
  12957. }
  12958. }
  12959. var position = geometry.attributes[ "position" ];
  12960. // render non-indexed triangles
  12961. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12962. _this.info.render.calls ++;
  12963. _this.info.render.vertices += position.numItems / 3;
  12964. _this.info.render.faces += position.numItems / 3 / 3;
  12965. }
  12966. // render particles
  12967. } else if ( object instanceof THREE.ParticleSystem ) {
  12968. if ( updateBuffers ) {
  12969. for ( attributeName in geometryAttributes ) {
  12970. attributePointer = programAttributes[ attributeName ];
  12971. attributeItem = geometryAttributes[ attributeName ];
  12972. attributeSize = attributeItem.itemSize;
  12973. if ( attributePointer >= 0 ) {
  12974. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12975. enableAttribute( attributePointer );
  12976. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  12977. }
  12978. }
  12979. var position = geometryAttributes[ "position" ];
  12980. // render particles
  12981. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12982. _this.info.render.calls ++;
  12983. _this.info.render.points += position.numItems / 3;
  12984. }
  12985. } else if ( object instanceof THREE.Line ) {
  12986. if ( updateBuffers ) {
  12987. for ( attributeName in geometryAttributes ) {
  12988. attributePointer = programAttributes[ attributeName ];
  12989. attributeItem = geometryAttributes[ attributeName ];
  12990. attributeSize = attributeItem.itemSize;
  12991. if ( attributePointer >= 0 ) {
  12992. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12993. enableAttribute( attributePointer );
  12994. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  12995. }
  12996. }
  12997. // render lines
  12998. setLineWidth( material.linewidth );
  12999. var position = geometryAttributes[ "position" ];
  13000. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  13001. _this.info.render.calls ++;
  13002. _this.info.render.points += position.numItems;
  13003. }
  13004. }
  13005. };
  13006. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13007. if ( material.visible === false ) return;
  13008. var program, attributes, linewidth, primitives, a, attribute, i, il;
  13009. program = setProgram( camera, lights, fog, material, object );
  13010. attributes = program.attributes;
  13011. var updateBuffers = false,
  13012. wireframeBit = material.wireframe ? 1 : 0,
  13013. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13014. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13015. _currentGeometryGroupHash = geometryGroupHash;
  13016. updateBuffers = true;
  13017. }
  13018. if ( updateBuffers ) {
  13019. disableAttributes();
  13020. }
  13021. // vertices
  13022. if ( !material.morphTargets && attributes.position >= 0 ) {
  13023. if ( updateBuffers ) {
  13024. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13025. enableAttribute( attributes.position );
  13026. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13027. }
  13028. } else {
  13029. if ( object.morphTargetBase ) {
  13030. setupMorphTargets( material, geometryGroup, object );
  13031. }
  13032. }
  13033. if ( updateBuffers ) {
  13034. // custom attributes
  13035. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13036. if ( geometryGroup.__webglCustomAttributesList ) {
  13037. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13038. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13039. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13040. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13041. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13042. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13043. }
  13044. }
  13045. }
  13046. // colors
  13047. if ( attributes.color >= 0 ) {
  13048. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13049. enableAttribute( attributes.color );
  13050. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13051. }
  13052. // normals
  13053. if ( attributes.normal >= 0 ) {
  13054. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13055. enableAttribute( attributes.normal );
  13056. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13057. }
  13058. // tangents
  13059. if ( attributes.tangent >= 0 ) {
  13060. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13061. enableAttribute( attributes.tangent );
  13062. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13063. }
  13064. // uvs
  13065. if ( attributes.uv >= 0 ) {
  13066. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13067. enableAttribute( attributes.uv );
  13068. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13069. }
  13070. if ( attributes.uv2 >= 0 ) {
  13071. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13072. enableAttribute( attributes.uv2 );
  13073. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13074. }
  13075. if ( material.skinning &&
  13076. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13077. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13078. enableAttribute( attributes.skinIndex );
  13079. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13080. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13081. enableAttribute( attributes.skinWeight );
  13082. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13083. }
  13084. // line distances
  13085. if ( attributes.lineDistance >= 0 ) {
  13086. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13087. enableAttribute( attributes.lineDistance );
  13088. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13089. }
  13090. }
  13091. // render mesh
  13092. if ( object instanceof THREE.Mesh ) {
  13093. // wireframe
  13094. if ( material.wireframe ) {
  13095. setLineWidth( material.wireframeLinewidth );
  13096. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13097. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13098. // triangles
  13099. } else {
  13100. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13101. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13102. }
  13103. _this.info.render.calls ++;
  13104. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13105. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13106. // render lines
  13107. } else if ( object instanceof THREE.Line ) {
  13108. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13109. setLineWidth( material.linewidth );
  13110. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13111. _this.info.render.calls ++;
  13112. // render particles
  13113. } else if ( object instanceof THREE.ParticleSystem ) {
  13114. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13115. _this.info.render.calls ++;
  13116. _this.info.render.points += geometryGroup.__webglParticleCount;
  13117. // render ribbon
  13118. } else if ( object instanceof THREE.Ribbon ) {
  13119. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13120. _this.info.render.calls ++;
  13121. }
  13122. };
  13123. function enableAttribute( attribute ) {
  13124. if ( ! _enabledAttributes[ attribute ] ) {
  13125. _gl.enableVertexAttribArray( attribute );
  13126. _enabledAttributes[ attribute ] = true;
  13127. }
  13128. };
  13129. function disableAttributes() {
  13130. for ( var attribute in _enabledAttributes ) {
  13131. if ( _enabledAttributes[ attribute ] ) {
  13132. _gl.disableVertexAttribArray( attribute );
  13133. _enabledAttributes[ attribute ] = false;
  13134. }
  13135. }
  13136. };
  13137. function setupMorphTargets ( material, geometryGroup, object ) {
  13138. // set base
  13139. var attributes = material.program.attributes;
  13140. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13141. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13142. enableAttribute( attributes.position );
  13143. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13144. } else if ( attributes.position >= 0 ) {
  13145. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13146. enableAttribute( attributes.position );
  13147. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13148. }
  13149. if ( object.morphTargetForcedOrder.length ) {
  13150. // set forced order
  13151. var m = 0;
  13152. var order = object.morphTargetForcedOrder;
  13153. var influences = object.morphTargetInfluences;
  13154. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13155. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13156. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13157. enableAttribute( attributes[ "morphTarget" + m ] );
  13158. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13159. }
  13160. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13161. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13162. enableAttribute( attributes[ "morphNormal" + m ] );
  13163. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13164. }
  13165. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13166. m ++;
  13167. }
  13168. } else {
  13169. // find the most influencing
  13170. var influence, activeInfluenceIndices = [];
  13171. var influences = object.morphTargetInfluences;
  13172. var i, il = influences.length;
  13173. for ( i = 0; i < il; i ++ ) {
  13174. influence = influences[ i ];
  13175. if ( influence > 0 ) {
  13176. activeInfluenceIndices.push( [ influence, i ] );
  13177. }
  13178. }
  13179. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13180. activeInfluenceIndices.sort( numericalSort );
  13181. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13182. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13183. activeInfluenceIndices.sort( numericalSort );
  13184. } else if ( activeInfluenceIndices.length === 0 ) {
  13185. activeInfluenceIndices.push( [ 0, 0 ] );
  13186. };
  13187. var influenceIndex, m = 0;
  13188. while ( m < material.numSupportedMorphTargets ) {
  13189. if ( activeInfluenceIndices[ m ] ) {
  13190. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13191. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13192. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13193. enableAttribute( attributes[ "morphTarget" + m ] );
  13194. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13195. }
  13196. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13197. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13198. enableAttribute( attributes[ "morphNormal" + m ] );
  13199. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13200. }
  13201. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13202. } else {
  13203. /*
  13204. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13205. if ( material.morphNormals ) {
  13206. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13207. }
  13208. */
  13209. object.__webglMorphTargetInfluences[ m ] = 0;
  13210. }
  13211. m ++;
  13212. }
  13213. }
  13214. // load updated influences uniform
  13215. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13216. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13217. }
  13218. };
  13219. // Sorting
  13220. function painterSortStable ( a, b ) {
  13221. if ( a.z !== b.z ) {
  13222. return b.z - a.z;
  13223. } else {
  13224. return a.id - b.id;
  13225. }
  13226. };
  13227. function numericalSort ( a, b ) {
  13228. return b[ 0 ] - a[ 0 ];
  13229. };
  13230. // Rendering
  13231. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13232. if ( camera instanceof THREE.Camera === false ) {
  13233. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13234. return;
  13235. }
  13236. var i, il,
  13237. webglObject, object,
  13238. renderList,
  13239. lights = scene.__lights,
  13240. fog = scene.fog;
  13241. // reset caching for this frame
  13242. _currentMaterialId = -1;
  13243. _lightsNeedUpdate = true;
  13244. // update scene graph
  13245. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  13246. // update camera matrices and frustum
  13247. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13248. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13249. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13250. _frustum.setFromMatrix( _projScreenMatrix );
  13251. // update WebGL objects
  13252. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13253. // custom render plugins (pre pass)
  13254. renderPlugins( this.renderPluginsPre, scene, camera );
  13255. //
  13256. _this.info.render.calls = 0;
  13257. _this.info.render.vertices = 0;
  13258. _this.info.render.faces = 0;
  13259. _this.info.render.points = 0;
  13260. this.setRenderTarget( renderTarget );
  13261. if ( this.autoClear || forceClear ) {
  13262. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13263. }
  13264. // set matrices for regular objects (frustum culled)
  13265. renderList = scene.__webglObjects;
  13266. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13267. webglObject = renderList[ i ];
  13268. object = webglObject.object;
  13269. webglObject.id = i;
  13270. webglObject.render = false;
  13271. if ( object.visible ) {
  13272. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13273. setupMatrices( object, camera );
  13274. unrollBufferMaterial( webglObject );
  13275. webglObject.render = true;
  13276. if ( this.sortObjects === true ) {
  13277. if ( object.renderDepth !== null ) {
  13278. webglObject.z = object.renderDepth;
  13279. } else {
  13280. _vector3.getPositionFromMatrix( object.matrixWorld );
  13281. _vector3.applyProjection( _projScreenMatrix );
  13282. webglObject.z = _vector3.z;
  13283. }
  13284. }
  13285. }
  13286. }
  13287. }
  13288. if ( this.sortObjects ) {
  13289. renderList.sort( painterSortStable );
  13290. }
  13291. // set matrices for immediate objects
  13292. renderList = scene.__webglObjectsImmediate;
  13293. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13294. webglObject = renderList[ i ];
  13295. object = webglObject.object;
  13296. if ( object.visible ) {
  13297. setupMatrices( object, camera );
  13298. unrollImmediateBufferMaterial( webglObject );
  13299. }
  13300. }
  13301. if ( scene.overrideMaterial ) {
  13302. var material = scene.overrideMaterial;
  13303. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13304. this.setDepthTest( material.depthTest );
  13305. this.setDepthWrite( material.depthWrite );
  13306. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13307. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13308. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13309. } else {
  13310. var material = null;
  13311. // opaque pass (front-to-back order)
  13312. this.setBlending( THREE.NoBlending );
  13313. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13314. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13315. // transparent pass (back-to-front order)
  13316. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13317. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13318. }
  13319. // custom render plugins (post pass)
  13320. renderPlugins( this.renderPluginsPost, scene, camera );
  13321. // Generate mipmap if we're using any kind of mipmap filtering
  13322. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13323. updateRenderTargetMipmap( renderTarget );
  13324. }
  13325. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13326. this.setDepthTest( true );
  13327. this.setDepthWrite( true );
  13328. // _gl.finish();
  13329. };
  13330. function renderPlugins( plugins, scene, camera ) {
  13331. if ( ! plugins.length ) return;
  13332. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13333. // reset state for plugin (to start from clean slate)
  13334. _currentProgram = null;
  13335. _currentCamera = null;
  13336. _oldBlending = -1;
  13337. _oldDepthTest = -1;
  13338. _oldDepthWrite = -1;
  13339. _oldDoubleSided = -1;
  13340. _oldFlipSided = -1;
  13341. _currentGeometryGroupHash = -1;
  13342. _currentMaterialId = -1;
  13343. _lightsNeedUpdate = true;
  13344. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13345. // reset state after plugin (anything could have changed)
  13346. _currentProgram = null;
  13347. _currentCamera = null;
  13348. _oldBlending = -1;
  13349. _oldDepthTest = -1;
  13350. _oldDepthWrite = -1;
  13351. _oldDoubleSided = -1;
  13352. _oldFlipSided = -1;
  13353. _currentGeometryGroupHash = -1;
  13354. _currentMaterialId = -1;
  13355. _lightsNeedUpdate = true;
  13356. }
  13357. };
  13358. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13359. var webglObject, object, buffer, material, start, end, delta;
  13360. if ( reverse ) {
  13361. start = renderList.length - 1;
  13362. end = -1;
  13363. delta = -1;
  13364. } else {
  13365. start = 0;
  13366. end = renderList.length;
  13367. delta = 1;
  13368. }
  13369. for ( var i = start; i !== end; i += delta ) {
  13370. webglObject = renderList[ i ];
  13371. if ( webglObject.render ) {
  13372. object = webglObject.object;
  13373. buffer = webglObject.buffer;
  13374. if ( overrideMaterial ) {
  13375. material = overrideMaterial;
  13376. } else {
  13377. material = webglObject[ materialType ];
  13378. if ( ! material ) continue;
  13379. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13380. _this.setDepthTest( material.depthTest );
  13381. _this.setDepthWrite( material.depthWrite );
  13382. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13383. }
  13384. _this.setMaterialFaces( material );
  13385. if ( buffer instanceof THREE.BufferGeometry ) {
  13386. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13387. } else {
  13388. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13389. }
  13390. }
  13391. }
  13392. };
  13393. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13394. var webglObject, object, material, program;
  13395. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13396. webglObject = renderList[ i ];
  13397. object = webglObject.object;
  13398. if ( object.visible ) {
  13399. if ( overrideMaterial ) {
  13400. material = overrideMaterial;
  13401. } else {
  13402. material = webglObject[ materialType ];
  13403. if ( ! material ) continue;
  13404. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13405. _this.setDepthTest( material.depthTest );
  13406. _this.setDepthWrite( material.depthWrite );
  13407. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13408. }
  13409. _this.renderImmediateObject( camera, lights, fog, material, object );
  13410. }
  13411. }
  13412. };
  13413. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13414. var program = setProgram( camera, lights, fog, material, object );
  13415. _currentGeometryGroupHash = -1;
  13416. _this.setMaterialFaces( material );
  13417. if ( object.immediateRenderCallback ) {
  13418. object.immediateRenderCallback( program, _gl, _frustum );
  13419. } else {
  13420. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13421. }
  13422. };
  13423. function unrollImmediateBufferMaterial ( globject ) {
  13424. var object = globject.object,
  13425. material = object.material;
  13426. if ( material.transparent ) {
  13427. globject.transparent = material;
  13428. globject.opaque = null;
  13429. } else {
  13430. globject.opaque = material;
  13431. globject.transparent = null;
  13432. }
  13433. };
  13434. function unrollBufferMaterial ( globject ) {
  13435. var object = globject.object,
  13436. buffer = globject.buffer,
  13437. material, materialIndex, meshMaterial;
  13438. meshMaterial = object.material;
  13439. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13440. materialIndex = buffer.materialIndex;
  13441. material = meshMaterial.materials[ materialIndex ];
  13442. if ( material.transparent ) {
  13443. globject.transparent = material;
  13444. globject.opaque = null;
  13445. } else {
  13446. globject.opaque = material;
  13447. globject.transparent = null;
  13448. }
  13449. } else {
  13450. material = meshMaterial;
  13451. if ( material ) {
  13452. if ( material.transparent ) {
  13453. globject.transparent = material;
  13454. globject.opaque = null;
  13455. } else {
  13456. globject.opaque = material;
  13457. globject.transparent = null;
  13458. }
  13459. }
  13460. }
  13461. };
  13462. // Geometry splitting
  13463. function sortFacesByMaterial ( geometry, material ) {
  13464. var f, fl, face, materialIndex, vertices,
  13465. groupHash, hash_map = {};
  13466. var numMorphTargets = geometry.morphTargets.length;
  13467. var numMorphNormals = geometry.morphNormals.length;
  13468. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13469. geometry.geometryGroups = {};
  13470. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13471. face = geometry.faces[ f ];
  13472. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13473. if ( hash_map[ materialIndex ] === undefined ) {
  13474. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13475. }
  13476. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13477. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13478. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13479. }
  13480. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13481. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13482. hash_map[ materialIndex ].counter += 1;
  13483. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13484. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13485. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13486. }
  13487. }
  13488. if ( face instanceof THREE.Face3 ) {
  13489. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13490. } else {
  13491. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13492. }
  13493. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13494. }
  13495. geometry.geometryGroupsList = [];
  13496. for ( var g in geometry.geometryGroups ) {
  13497. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13498. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13499. }
  13500. };
  13501. // Objects refresh
  13502. this.initWebGLObjects = function ( scene ) {
  13503. if ( !scene.__webglObjects ) {
  13504. scene.__webglObjects = [];
  13505. scene.__webglObjectsImmediate = [];
  13506. scene.__webglSprites = [];
  13507. scene.__webglFlares = [];
  13508. }
  13509. while ( scene.__objectsAdded.length ) {
  13510. addObject( scene.__objectsAdded[ 0 ], scene );
  13511. scene.__objectsAdded.splice( 0, 1 );
  13512. }
  13513. while ( scene.__objectsRemoved.length ) {
  13514. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13515. scene.__objectsRemoved.splice( 0, 1 );
  13516. }
  13517. // update must be called after objects adding / removal
  13518. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13519. var object = scene.__webglObjects[ o ].object;
  13520. // TODO: Remove this hack (WebGLRenderer refactoring)
  13521. if ( object.__webglInit === undefined ) {
  13522. if ( object.__webglActive !== undefined ) {
  13523. removeObject( object, scene );
  13524. }
  13525. addObject( object, scene );
  13526. }
  13527. updateObject( object );
  13528. }
  13529. };
  13530. // Objects adding
  13531. function addObject( object, scene ) {
  13532. var g, geometry, material, geometryGroup;
  13533. if ( object.__webglInit === undefined ) {
  13534. object.__webglInit = true;
  13535. object._modelViewMatrix = new THREE.Matrix4();
  13536. object._normalMatrix = new THREE.Matrix3();
  13537. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13538. object.geometry.__webglInit = true;
  13539. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13540. }
  13541. geometry = object.geometry;
  13542. if ( geometry === undefined ) {
  13543. // fail silently for now
  13544. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13545. initDirectBuffers( geometry );
  13546. } else if ( object instanceof THREE.Mesh ) {
  13547. material = object.material;
  13548. if ( geometry.geometryGroups === undefined ) {
  13549. sortFacesByMaterial( geometry, material );
  13550. }
  13551. // create separate VBOs per geometry chunk
  13552. for ( g in geometry.geometryGroups ) {
  13553. geometryGroup = geometry.geometryGroups[ g ];
  13554. // initialise VBO on the first access
  13555. if ( ! geometryGroup.__webglVertexBuffer ) {
  13556. createMeshBuffers( geometryGroup );
  13557. initMeshBuffers( geometryGroup, object );
  13558. geometry.verticesNeedUpdate = true;
  13559. geometry.morphTargetsNeedUpdate = true;
  13560. geometry.elementsNeedUpdate = true;
  13561. geometry.uvsNeedUpdate = true;
  13562. geometry.normalsNeedUpdate = true;
  13563. geometry.tangentsNeedUpdate = true;
  13564. geometry.colorsNeedUpdate = true;
  13565. }
  13566. }
  13567. } else if ( object instanceof THREE.Ribbon ) {
  13568. if ( ! geometry.__webglVertexBuffer ) {
  13569. createRibbonBuffers( geometry );
  13570. initRibbonBuffers( geometry, object );
  13571. geometry.verticesNeedUpdate = true;
  13572. geometry.colorsNeedUpdate = true;
  13573. geometry.normalsNeedUpdate = true;
  13574. }
  13575. } else if ( object instanceof THREE.Line ) {
  13576. if ( ! geometry.__webglVertexBuffer ) {
  13577. createLineBuffers( geometry );
  13578. initLineBuffers( geometry, object );
  13579. geometry.verticesNeedUpdate = true;
  13580. geometry.colorsNeedUpdate = true;
  13581. geometry.lineDistancesNeedUpdate = true;
  13582. }
  13583. } else if ( object instanceof THREE.ParticleSystem ) {
  13584. if ( ! geometry.__webglVertexBuffer ) {
  13585. createParticleBuffers( geometry );
  13586. initParticleBuffers( geometry, object );
  13587. geometry.verticesNeedUpdate = true;
  13588. geometry.colorsNeedUpdate = true;
  13589. }
  13590. }
  13591. }
  13592. if ( object.__webglActive === undefined ) {
  13593. if ( object instanceof THREE.Mesh ) {
  13594. geometry = object.geometry;
  13595. if ( geometry instanceof THREE.BufferGeometry ) {
  13596. addBuffer( scene.__webglObjects, geometry, object );
  13597. } else if ( geometry instanceof THREE.Geometry ) {
  13598. for ( g in geometry.geometryGroups ) {
  13599. geometryGroup = geometry.geometryGroups[ g ];
  13600. addBuffer( scene.__webglObjects, geometryGroup, object );
  13601. }
  13602. }
  13603. } else if ( object instanceof THREE.Ribbon ||
  13604. object instanceof THREE.Line ||
  13605. object instanceof THREE.ParticleSystem ) {
  13606. geometry = object.geometry;
  13607. addBuffer( scene.__webglObjects, geometry, object );
  13608. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13609. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13610. } else if ( object instanceof THREE.Sprite ) {
  13611. scene.__webglSprites.push( object );
  13612. } else if ( object instanceof THREE.LensFlare ) {
  13613. scene.__webglFlares.push( object );
  13614. }
  13615. object.__webglActive = true;
  13616. }
  13617. };
  13618. function addBuffer( objlist, buffer, object ) {
  13619. objlist.push(
  13620. {
  13621. buffer: buffer,
  13622. object: object,
  13623. opaque: null,
  13624. transparent: null
  13625. }
  13626. );
  13627. };
  13628. function addBufferImmediate( objlist, object ) {
  13629. objlist.push(
  13630. {
  13631. object: object,
  13632. opaque: null,
  13633. transparent: null
  13634. }
  13635. );
  13636. };
  13637. // Objects updates
  13638. function updateObject( object ) {
  13639. var geometry = object.geometry,
  13640. geometryGroup, customAttributesDirty, material;
  13641. if ( geometry instanceof THREE.BufferGeometry ) {
  13642. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13643. } else if ( object instanceof THREE.Mesh ) {
  13644. // check all geometry groups
  13645. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13646. geometryGroup = geometry.geometryGroupsList[ i ];
  13647. material = getBufferMaterial( object, geometryGroup );
  13648. if ( geometry.buffersNeedUpdate ) {
  13649. initMeshBuffers( geometryGroup, object );
  13650. }
  13651. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13652. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13653. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13654. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13655. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13656. }
  13657. }
  13658. geometry.verticesNeedUpdate = false;
  13659. geometry.morphTargetsNeedUpdate = false;
  13660. geometry.elementsNeedUpdate = false;
  13661. geometry.uvsNeedUpdate = false;
  13662. geometry.normalsNeedUpdate = false;
  13663. geometry.colorsNeedUpdate = false;
  13664. geometry.tangentsNeedUpdate = false;
  13665. geometry.buffersNeedUpdate = false;
  13666. material.attributes && clearCustomAttributes( material );
  13667. } else if ( object instanceof THREE.Ribbon ) {
  13668. material = getBufferMaterial( object, geometry );
  13669. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13670. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13671. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13672. }
  13673. geometry.verticesNeedUpdate = false;
  13674. geometry.colorsNeedUpdate = false;
  13675. geometry.normalsNeedUpdate = false;
  13676. material.attributes && clearCustomAttributes( material );
  13677. } else if ( object instanceof THREE.Line ) {
  13678. material = getBufferMaterial( object, geometry );
  13679. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13680. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13681. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13682. }
  13683. geometry.verticesNeedUpdate = false;
  13684. geometry.colorsNeedUpdate = false;
  13685. geometry.lineDistancesNeedUpdate = false;
  13686. material.attributes && clearCustomAttributes( material );
  13687. } else if ( object instanceof THREE.ParticleSystem ) {
  13688. material = getBufferMaterial( object, geometry );
  13689. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13690. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13691. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13692. }
  13693. geometry.verticesNeedUpdate = false;
  13694. geometry.colorsNeedUpdate = false;
  13695. material.attributes && clearCustomAttributes( material );
  13696. }
  13697. };
  13698. // Objects updates - custom attributes check
  13699. function areCustomAttributesDirty( material ) {
  13700. for ( var a in material.attributes ) {
  13701. if ( material.attributes[ a ].needsUpdate ) return true;
  13702. }
  13703. return false;
  13704. };
  13705. function clearCustomAttributes( material ) {
  13706. for ( var a in material.attributes ) {
  13707. material.attributes[ a ].needsUpdate = false;
  13708. }
  13709. };
  13710. // Objects removal
  13711. function removeObject( object, scene ) {
  13712. if ( object instanceof THREE.Mesh ||
  13713. object instanceof THREE.ParticleSystem ||
  13714. object instanceof THREE.Ribbon ||
  13715. object instanceof THREE.Line ) {
  13716. removeInstances( scene.__webglObjects, object );
  13717. } else if ( object instanceof THREE.Sprite ) {
  13718. removeInstancesDirect( scene.__webglSprites, object );
  13719. } else if ( object instanceof THREE.LensFlare ) {
  13720. removeInstancesDirect( scene.__webglFlares, object );
  13721. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13722. removeInstances( scene.__webglObjectsImmediate, object );
  13723. }
  13724. delete object.__webglActive;
  13725. };
  13726. function removeInstances( objlist, object ) {
  13727. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13728. if ( objlist[ o ].object === object ) {
  13729. objlist.splice( o, 1 );
  13730. }
  13731. }
  13732. };
  13733. function removeInstancesDirect( objlist, object ) {
  13734. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13735. if ( objlist[ o ] === object ) {
  13736. objlist.splice( o, 1 );
  13737. }
  13738. }
  13739. };
  13740. // Materials
  13741. this.initMaterial = function ( material, lights, fog, object ) {
  13742. material.addEventListener( 'dispose', onMaterialDispose );
  13743. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13744. if ( material instanceof THREE.MeshDepthMaterial ) {
  13745. shaderID = 'depth';
  13746. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13747. shaderID = 'normal';
  13748. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13749. shaderID = 'basic';
  13750. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13751. shaderID = 'lambert';
  13752. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13753. shaderID = 'phong';
  13754. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13755. shaderID = 'basic';
  13756. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13757. shaderID = 'dashed';
  13758. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13759. shaderID = 'particle_basic';
  13760. }
  13761. if ( shaderID ) {
  13762. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13763. }
  13764. // heuristics to create shader parameters according to lights in the scene
  13765. // (not to blow over maxLights budget)
  13766. maxLightCount = allocateLights( lights );
  13767. maxShadows = allocateShadows( lights );
  13768. maxBones = allocateBones( object );
  13769. parameters = {
  13770. map: !!material.map,
  13771. envMap: !!material.envMap,
  13772. lightMap: !!material.lightMap,
  13773. bumpMap: !!material.bumpMap,
  13774. normalMap: !!material.normalMap,
  13775. specularMap: !!material.specularMap,
  13776. vertexColors: material.vertexColors,
  13777. fog: fog,
  13778. useFog: material.fog,
  13779. fogExp: fog instanceof THREE.FogExp2,
  13780. sizeAttenuation: material.sizeAttenuation,
  13781. skinning: material.skinning,
  13782. maxBones: maxBones,
  13783. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13784. boneTextureWidth: object && object.boneTextureWidth,
  13785. boneTextureHeight: object && object.boneTextureHeight,
  13786. morphTargets: material.morphTargets,
  13787. morphNormals: material.morphNormals,
  13788. maxMorphTargets: this.maxMorphTargets,
  13789. maxMorphNormals: this.maxMorphNormals,
  13790. maxDirLights: maxLightCount.directional,
  13791. maxPointLights: maxLightCount.point,
  13792. maxSpotLights: maxLightCount.spot,
  13793. maxHemiLights: maxLightCount.hemi,
  13794. maxShadows: maxShadows,
  13795. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13796. shadowMapType: this.shadowMapType,
  13797. shadowMapDebug: this.shadowMapDebug,
  13798. shadowMapCascade: this.shadowMapCascade,
  13799. alphaTest: material.alphaTest,
  13800. metal: material.metal,
  13801. perPixel: material.perPixel,
  13802. wrapAround: material.wrapAround,
  13803. doubleSided: material.side === THREE.DoubleSide,
  13804. flipSided: material.side === THREE.BackSide
  13805. };
  13806. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13807. var attributes = material.program.attributes;
  13808. if ( material.morphTargets ) {
  13809. material.numSupportedMorphTargets = 0;
  13810. var id, base = "morphTarget";
  13811. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13812. id = base + i;
  13813. if ( attributes[ id ] >= 0 ) {
  13814. material.numSupportedMorphTargets ++;
  13815. }
  13816. }
  13817. }
  13818. if ( material.morphNormals ) {
  13819. material.numSupportedMorphNormals = 0;
  13820. var id, base = "morphNormal";
  13821. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13822. id = base + i;
  13823. if ( attributes[ id ] >= 0 ) {
  13824. material.numSupportedMorphNormals ++;
  13825. }
  13826. }
  13827. }
  13828. material.uniformsList = [];
  13829. for ( u in material.uniforms ) {
  13830. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13831. }
  13832. };
  13833. function setMaterialShaders( material, shaders ) {
  13834. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13835. material.vertexShader = shaders.vertexShader;
  13836. material.fragmentShader = shaders.fragmentShader;
  13837. };
  13838. function setProgram( camera, lights, fog, material, object ) {
  13839. _usedTextureUnits = 0;
  13840. if ( material.needsUpdate ) {
  13841. if ( material.program ) deallocateMaterial( material );
  13842. _this.initMaterial( material, lights, fog, object );
  13843. material.needsUpdate = false;
  13844. }
  13845. if ( material.morphTargets ) {
  13846. if ( ! object.__webglMorphTargetInfluences ) {
  13847. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13848. }
  13849. }
  13850. var refreshMaterial = false;
  13851. var program = material.program,
  13852. p_uniforms = program.uniforms,
  13853. m_uniforms = material.uniforms;
  13854. if ( program !== _currentProgram ) {
  13855. _gl.useProgram( program );
  13856. _currentProgram = program;
  13857. refreshMaterial = true;
  13858. }
  13859. if ( material.id !== _currentMaterialId ) {
  13860. _currentMaterialId = material.id;
  13861. refreshMaterial = true;
  13862. }
  13863. if ( refreshMaterial || camera !== _currentCamera ) {
  13864. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13865. if ( camera !== _currentCamera ) _currentCamera = camera;
  13866. }
  13867. // skinning uniforms must be set even if material didn't change
  13868. // auto-setting of texture unit for bone texture must go before other textures
  13869. // not sure why, but otherwise weird things happen
  13870. if ( material.skinning ) {
  13871. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13872. if ( p_uniforms.boneTexture !== null ) {
  13873. var textureUnit = getTextureUnit();
  13874. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13875. _this.setTexture( object.boneTexture, textureUnit );
  13876. }
  13877. } else {
  13878. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13879. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13880. }
  13881. }
  13882. }
  13883. if ( refreshMaterial ) {
  13884. // refresh uniforms common to several materials
  13885. if ( fog && material.fog ) {
  13886. refreshUniformsFog( m_uniforms, fog );
  13887. }
  13888. if ( material instanceof THREE.MeshPhongMaterial ||
  13889. material instanceof THREE.MeshLambertMaterial ||
  13890. material.lights ) {
  13891. if ( _lightsNeedUpdate ) {
  13892. setupLights( program, lights );
  13893. _lightsNeedUpdate = false;
  13894. }
  13895. refreshUniformsLights( m_uniforms, _lights );
  13896. }
  13897. if ( material instanceof THREE.MeshBasicMaterial ||
  13898. material instanceof THREE.MeshLambertMaterial ||
  13899. material instanceof THREE.MeshPhongMaterial ) {
  13900. refreshUniformsCommon( m_uniforms, material );
  13901. }
  13902. // refresh single material specific uniforms
  13903. if ( material instanceof THREE.LineBasicMaterial ) {
  13904. refreshUniformsLine( m_uniforms, material );
  13905. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13906. refreshUniformsLine( m_uniforms, material );
  13907. refreshUniformsDash( m_uniforms, material );
  13908. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13909. refreshUniformsParticle( m_uniforms, material );
  13910. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13911. refreshUniformsPhong( m_uniforms, material );
  13912. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13913. refreshUniformsLambert( m_uniforms, material );
  13914. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13915. m_uniforms.mNear.value = camera.near;
  13916. m_uniforms.mFar.value = camera.far;
  13917. m_uniforms.opacity.value = material.opacity;
  13918. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13919. m_uniforms.opacity.value = material.opacity;
  13920. }
  13921. if ( object.receiveShadow && ! material._shadowPass ) {
  13922. refreshUniformsShadow( m_uniforms, lights );
  13923. }
  13924. // load common uniforms
  13925. loadUniformsGeneric( program, material.uniformsList );
  13926. // load material specific uniforms
  13927. // (shader material also gets them for the sake of genericity)
  13928. if ( material instanceof THREE.ShaderMaterial ||
  13929. material instanceof THREE.MeshPhongMaterial ||
  13930. material.envMap ) {
  13931. if ( p_uniforms.cameraPosition !== null ) {
  13932. _vector3.getPositionFromMatrix( camera.matrixWorld );
  13933. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13934. }
  13935. }
  13936. if ( material instanceof THREE.MeshPhongMaterial ||
  13937. material instanceof THREE.MeshLambertMaterial ||
  13938. material instanceof THREE.ShaderMaterial ||
  13939. material.skinning ) {
  13940. if ( p_uniforms.viewMatrix !== null ) {
  13941. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13942. }
  13943. }
  13944. }
  13945. loadUniformsMatrices( p_uniforms, object );
  13946. if ( p_uniforms.modelMatrix !== null ) {
  13947. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13948. }
  13949. return program;
  13950. };
  13951. // Uniforms (refresh uniforms objects)
  13952. function refreshUniformsCommon ( uniforms, material ) {
  13953. uniforms.opacity.value = material.opacity;
  13954. if ( _this.gammaInput ) {
  13955. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13956. } else {
  13957. uniforms.diffuse.value = material.color;
  13958. }
  13959. uniforms.map.value = material.map;
  13960. uniforms.lightMap.value = material.lightMap;
  13961. uniforms.specularMap.value = material.specularMap;
  13962. if ( material.bumpMap ) {
  13963. uniforms.bumpMap.value = material.bumpMap;
  13964. uniforms.bumpScale.value = material.bumpScale;
  13965. }
  13966. if ( material.normalMap ) {
  13967. uniforms.normalMap.value = material.normalMap;
  13968. uniforms.normalScale.value.copy( material.normalScale );
  13969. }
  13970. // uv repeat and offset setting priorities
  13971. // 1. color map
  13972. // 2. specular map
  13973. // 3. normal map
  13974. // 4. bump map
  13975. var uvScaleMap;
  13976. if ( material.map ) {
  13977. uvScaleMap = material.map;
  13978. } else if ( material.specularMap ) {
  13979. uvScaleMap = material.specularMap;
  13980. } else if ( material.normalMap ) {
  13981. uvScaleMap = material.normalMap;
  13982. } else if ( material.bumpMap ) {
  13983. uvScaleMap = material.bumpMap;
  13984. }
  13985. if ( uvScaleMap !== undefined ) {
  13986. var offset = uvScaleMap.offset;
  13987. var repeat = uvScaleMap.repeat;
  13988. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13989. }
  13990. uniforms.envMap.value = material.envMap;
  13991. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13992. if ( _this.gammaInput ) {
  13993. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13994. uniforms.reflectivity.value = material.reflectivity;
  13995. } else {
  13996. uniforms.reflectivity.value = material.reflectivity;
  13997. }
  13998. uniforms.refractionRatio.value = material.refractionRatio;
  13999. uniforms.combine.value = material.combine;
  14000. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14001. };
  14002. function refreshUniformsLine ( uniforms, material ) {
  14003. uniforms.diffuse.value = material.color;
  14004. uniforms.opacity.value = material.opacity;
  14005. };
  14006. function refreshUniformsDash ( uniforms, material ) {
  14007. uniforms.dashSize.value = material.dashSize;
  14008. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14009. uniforms.scale.value = material.scale;
  14010. };
  14011. function refreshUniformsParticle ( uniforms, material ) {
  14012. uniforms.psColor.value = material.color;
  14013. uniforms.opacity.value = material.opacity;
  14014. uniforms.size.value = material.size;
  14015. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14016. uniforms.map.value = material.map;
  14017. };
  14018. function refreshUniformsFog ( uniforms, fog ) {
  14019. uniforms.fogColor.value = fog.color;
  14020. if ( fog instanceof THREE.Fog ) {
  14021. uniforms.fogNear.value = fog.near;
  14022. uniforms.fogFar.value = fog.far;
  14023. } else if ( fog instanceof THREE.FogExp2 ) {
  14024. uniforms.fogDensity.value = fog.density;
  14025. }
  14026. };
  14027. function refreshUniformsPhong ( uniforms, material ) {
  14028. uniforms.shininess.value = material.shininess;
  14029. if ( _this.gammaInput ) {
  14030. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14031. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14032. uniforms.specular.value.copyGammaToLinear( material.specular );
  14033. } else {
  14034. uniforms.ambient.value = material.ambient;
  14035. uniforms.emissive.value = material.emissive;
  14036. uniforms.specular.value = material.specular;
  14037. }
  14038. if ( material.wrapAround ) {
  14039. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14040. }
  14041. };
  14042. function refreshUniformsLambert ( uniforms, material ) {
  14043. if ( _this.gammaInput ) {
  14044. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14045. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14046. } else {
  14047. uniforms.ambient.value = material.ambient;
  14048. uniforms.emissive.value = material.emissive;
  14049. }
  14050. if ( material.wrapAround ) {
  14051. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14052. }
  14053. };
  14054. function refreshUniformsLights ( uniforms, lights ) {
  14055. uniforms.ambientLightColor.value = lights.ambient;
  14056. uniforms.directionalLightColor.value = lights.directional.colors;
  14057. uniforms.directionalLightDirection.value = lights.directional.positions;
  14058. uniforms.pointLightColor.value = lights.point.colors;
  14059. uniforms.pointLightPosition.value = lights.point.positions;
  14060. uniforms.pointLightDistance.value = lights.point.distances;
  14061. uniforms.spotLightColor.value = lights.spot.colors;
  14062. uniforms.spotLightPosition.value = lights.spot.positions;
  14063. uniforms.spotLightDistance.value = lights.spot.distances;
  14064. uniforms.spotLightDirection.value = lights.spot.directions;
  14065. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14066. uniforms.spotLightExponent.value = lights.spot.exponents;
  14067. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14068. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14069. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14070. };
  14071. function refreshUniformsShadow ( uniforms, lights ) {
  14072. if ( uniforms.shadowMatrix ) {
  14073. var j = 0;
  14074. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14075. var light = lights[ i ];
  14076. if ( ! light.castShadow ) continue;
  14077. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14078. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14079. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14080. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14081. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14082. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14083. j ++;
  14084. }
  14085. }
  14086. }
  14087. };
  14088. // Uniforms (load to GPU)
  14089. function loadUniformsMatrices ( uniforms, object ) {
  14090. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14091. if ( uniforms.normalMatrix ) {
  14092. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14093. }
  14094. };
  14095. function getTextureUnit() {
  14096. var textureUnit = _usedTextureUnits;
  14097. if ( textureUnit >= _maxTextures ) {
  14098. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14099. }
  14100. _usedTextureUnits += 1;
  14101. return textureUnit;
  14102. };
  14103. function loadUniformsGeneric ( program, uniforms ) {
  14104. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14105. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14106. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14107. if ( !location ) continue;
  14108. uniform = uniforms[ j ][ 0 ];
  14109. type = uniform.type;
  14110. value = uniform.value;
  14111. if ( type === "i" ) { // single integer
  14112. _gl.uniform1i( location, value );
  14113. } else if ( type === "f" ) { // single float
  14114. _gl.uniform1f( location, value );
  14115. } else if ( type === "v2" ) { // single THREE.Vector2
  14116. _gl.uniform2f( location, value.x, value.y );
  14117. } else if ( type === "v3" ) { // single THREE.Vector3
  14118. _gl.uniform3f( location, value.x, value.y, value.z );
  14119. } else if ( type === "v4" ) { // single THREE.Vector4
  14120. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14121. } else if ( type === "c" ) { // single THREE.Color
  14122. _gl.uniform3f( location, value.r, value.g, value.b );
  14123. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14124. _gl.uniform1iv( location, value );
  14125. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14126. _gl.uniform3iv( location, value );
  14127. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14128. _gl.uniform1fv( location, value );
  14129. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14130. _gl.uniform3fv( location, value );
  14131. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14132. if ( uniform._array === undefined ) {
  14133. uniform._array = new Float32Array( 2 * value.length );
  14134. }
  14135. for ( i = 0, il = value.length; i < il; i ++ ) {
  14136. offset = i * 2;
  14137. uniform._array[ offset ] = value[ i ].x;
  14138. uniform._array[ offset + 1 ] = value[ i ].y;
  14139. }
  14140. _gl.uniform2fv( location, uniform._array );
  14141. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14142. if ( uniform._array === undefined ) {
  14143. uniform._array = new Float32Array( 3 * value.length );
  14144. }
  14145. for ( i = 0, il = value.length; i < il; i ++ ) {
  14146. offset = i * 3;
  14147. uniform._array[ offset ] = value[ i ].x;
  14148. uniform._array[ offset + 1 ] = value[ i ].y;
  14149. uniform._array[ offset + 2 ] = value[ i ].z;
  14150. }
  14151. _gl.uniform3fv( location, uniform._array );
  14152. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14153. if ( uniform._array === undefined ) {
  14154. uniform._array = new Float32Array( 4 * value.length );
  14155. }
  14156. for ( i = 0, il = value.length; i < il; i ++ ) {
  14157. offset = i * 4;
  14158. uniform._array[ offset ] = value[ i ].x;
  14159. uniform._array[ offset + 1 ] = value[ i ].y;
  14160. uniform._array[ offset + 2 ] = value[ i ].z;
  14161. uniform._array[ offset + 3 ] = value[ i ].w;
  14162. }
  14163. _gl.uniform4fv( location, uniform._array );
  14164. } else if ( type === "m4") { // single THREE.Matrix4
  14165. if ( uniform._array === undefined ) {
  14166. uniform._array = new Float32Array( 16 );
  14167. }
  14168. value.flattenToArray( uniform._array );
  14169. _gl.uniformMatrix4fv( location, false, uniform._array );
  14170. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14171. if ( uniform._array === undefined ) {
  14172. uniform._array = new Float32Array( 16 * value.length );
  14173. }
  14174. for ( i = 0, il = value.length; i < il; i ++ ) {
  14175. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14176. }
  14177. _gl.uniformMatrix4fv( location, false, uniform._array );
  14178. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14179. texture = value;
  14180. textureUnit = getTextureUnit();
  14181. _gl.uniform1i( location, textureUnit );
  14182. if ( !texture ) continue;
  14183. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14184. setCubeTexture( texture, textureUnit );
  14185. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14186. setCubeTextureDynamic( texture, textureUnit );
  14187. } else {
  14188. _this.setTexture( texture, textureUnit );
  14189. }
  14190. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14191. if ( uniform._array === undefined ) {
  14192. uniform._array = [];
  14193. }
  14194. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14195. uniform._array[ i ] = getTextureUnit();
  14196. }
  14197. _gl.uniform1iv( location, uniform._array );
  14198. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14199. texture = uniform.value[ i ];
  14200. textureUnit = uniform._array[ i ];
  14201. if ( !texture ) continue;
  14202. _this.setTexture( texture, textureUnit );
  14203. }
  14204. }
  14205. }
  14206. };
  14207. function setupMatrices ( object, camera ) {
  14208. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14209. object._normalMatrix.getInverse( object._modelViewMatrix );
  14210. object._normalMatrix.transpose();
  14211. };
  14212. //
  14213. function setColorGamma( array, offset, color, intensitySq ) {
  14214. array[ offset ] = color.r * color.r * intensitySq;
  14215. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14216. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14217. };
  14218. function setColorLinear( array, offset, color, intensity ) {
  14219. array[ offset ] = color.r * intensity;
  14220. array[ offset + 1 ] = color.g * intensity;
  14221. array[ offset + 2 ] = color.b * intensity;
  14222. };
  14223. function setupLights ( program, lights ) {
  14224. var l, ll, light, n,
  14225. r = 0, g = 0, b = 0,
  14226. color, skyColor, groundColor,
  14227. intensity, intensitySq,
  14228. position,
  14229. distance,
  14230. zlights = _lights,
  14231. dirColors = zlights.directional.colors,
  14232. dirPositions = zlights.directional.positions,
  14233. pointColors = zlights.point.colors,
  14234. pointPositions = zlights.point.positions,
  14235. pointDistances = zlights.point.distances,
  14236. spotColors = zlights.spot.colors,
  14237. spotPositions = zlights.spot.positions,
  14238. spotDistances = zlights.spot.distances,
  14239. spotDirections = zlights.spot.directions,
  14240. spotAnglesCos = zlights.spot.anglesCos,
  14241. spotExponents = zlights.spot.exponents,
  14242. hemiSkyColors = zlights.hemi.skyColors,
  14243. hemiGroundColors = zlights.hemi.groundColors,
  14244. hemiPositions = zlights.hemi.positions,
  14245. dirLength = 0,
  14246. pointLength = 0,
  14247. spotLength = 0,
  14248. hemiLength = 0,
  14249. dirCount = 0,
  14250. pointCount = 0,
  14251. spotCount = 0,
  14252. hemiCount = 0,
  14253. dirOffset = 0,
  14254. pointOffset = 0,
  14255. spotOffset = 0,
  14256. hemiOffset = 0;
  14257. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14258. light = lights[ l ];
  14259. if ( light.onlyShadow ) continue;
  14260. color = light.color;
  14261. intensity = light.intensity;
  14262. distance = light.distance;
  14263. if ( light instanceof THREE.AmbientLight ) {
  14264. if ( ! light.visible ) continue;
  14265. if ( _this.gammaInput ) {
  14266. r += color.r * color.r;
  14267. g += color.g * color.g;
  14268. b += color.b * color.b;
  14269. } else {
  14270. r += color.r;
  14271. g += color.g;
  14272. b += color.b;
  14273. }
  14274. } else if ( light instanceof THREE.DirectionalLight ) {
  14275. dirCount += 1;
  14276. if ( ! light.visible ) continue;
  14277. _direction.getPositionFromMatrix( light.matrixWorld );
  14278. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14279. _direction.sub( _vector3 );
  14280. _direction.normalize();
  14281. // skip lights with undefined direction
  14282. // these create troubles in OpenGL (making pixel black)
  14283. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14284. dirOffset = dirLength * 3;
  14285. dirPositions[ dirOffset ] = _direction.x;
  14286. dirPositions[ dirOffset + 1 ] = _direction.y;
  14287. dirPositions[ dirOffset + 2 ] = _direction.z;
  14288. if ( _this.gammaInput ) {
  14289. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14290. } else {
  14291. setColorLinear( dirColors, dirOffset, color, intensity );
  14292. }
  14293. dirLength += 1;
  14294. } else if ( light instanceof THREE.PointLight ) {
  14295. pointCount += 1;
  14296. if ( ! light.visible ) continue;
  14297. pointOffset = pointLength * 3;
  14298. if ( _this.gammaInput ) {
  14299. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14300. } else {
  14301. setColorLinear( pointColors, pointOffset, color, intensity );
  14302. }
  14303. _vector3.getPositionFromMatrix( light.matrixWorld );
  14304. pointPositions[ pointOffset ] = _vector3.x;
  14305. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14306. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14307. pointDistances[ pointLength ] = distance;
  14308. pointLength += 1;
  14309. } else if ( light instanceof THREE.SpotLight ) {
  14310. spotCount += 1;
  14311. if ( ! light.visible ) continue;
  14312. spotOffset = spotLength * 3;
  14313. if ( _this.gammaInput ) {
  14314. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14315. } else {
  14316. setColorLinear( spotColors, spotOffset, color, intensity );
  14317. }
  14318. _vector3.getPositionFromMatrix( light.matrixWorld );
  14319. spotPositions[ spotOffset ] = _vector3.x;
  14320. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14321. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14322. spotDistances[ spotLength ] = distance;
  14323. _direction.copy( _vector3 );
  14324. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14325. _direction.sub( _vector3 );
  14326. _direction.normalize();
  14327. spotDirections[ spotOffset ] = _direction.x;
  14328. spotDirections[ spotOffset + 1 ] = _direction.y;
  14329. spotDirections[ spotOffset + 2 ] = _direction.z;
  14330. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14331. spotExponents[ spotLength ] = light.exponent;
  14332. spotLength += 1;
  14333. } else if ( light instanceof THREE.HemisphereLight ) {
  14334. hemiCount += 1;
  14335. if ( ! light.visible ) continue;
  14336. _direction.getPositionFromMatrix( light.matrixWorld );
  14337. _direction.normalize();
  14338. // skip lights with undefined direction
  14339. // these create troubles in OpenGL (making pixel black)
  14340. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14341. hemiOffset = hemiLength * 3;
  14342. hemiPositions[ hemiOffset ] = _direction.x;
  14343. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14344. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14345. skyColor = light.color;
  14346. groundColor = light.groundColor;
  14347. if ( _this.gammaInput ) {
  14348. intensitySq = intensity * intensity;
  14349. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14350. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14351. } else {
  14352. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14353. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14354. }
  14355. hemiLength += 1;
  14356. }
  14357. }
  14358. // null eventual remains from removed lights
  14359. // (this is to avoid if in shader)
  14360. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14361. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14362. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14363. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14364. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14365. zlights.directional.length = dirLength;
  14366. zlights.point.length = pointLength;
  14367. zlights.spot.length = spotLength;
  14368. zlights.hemi.length = hemiLength;
  14369. zlights.ambient[ 0 ] = r;
  14370. zlights.ambient[ 1 ] = g;
  14371. zlights.ambient[ 2 ] = b;
  14372. };
  14373. // GL state setting
  14374. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14375. if ( cullFace === THREE.CullFaceNone ) {
  14376. _gl.disable( _gl.CULL_FACE );
  14377. } else {
  14378. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14379. _gl.frontFace( _gl.CW );
  14380. } else {
  14381. _gl.frontFace( _gl.CCW );
  14382. }
  14383. if ( cullFace === THREE.CullFaceBack ) {
  14384. _gl.cullFace( _gl.BACK );
  14385. } else if ( cullFace === THREE.CullFaceFront ) {
  14386. _gl.cullFace( _gl.FRONT );
  14387. } else {
  14388. _gl.cullFace( _gl.FRONT_AND_BACK );
  14389. }
  14390. _gl.enable( _gl.CULL_FACE );
  14391. }
  14392. };
  14393. this.setMaterialFaces = function ( material ) {
  14394. var doubleSided = material.side === THREE.DoubleSide;
  14395. var flipSided = material.side === THREE.BackSide;
  14396. if ( _oldDoubleSided !== doubleSided ) {
  14397. if ( doubleSided ) {
  14398. _gl.disable( _gl.CULL_FACE );
  14399. } else {
  14400. _gl.enable( _gl.CULL_FACE );
  14401. }
  14402. _oldDoubleSided = doubleSided;
  14403. }
  14404. if ( _oldFlipSided !== flipSided ) {
  14405. if ( flipSided ) {
  14406. _gl.frontFace( _gl.CW );
  14407. } else {
  14408. _gl.frontFace( _gl.CCW );
  14409. }
  14410. _oldFlipSided = flipSided;
  14411. }
  14412. };
  14413. this.setDepthTest = function ( depthTest ) {
  14414. if ( _oldDepthTest !== depthTest ) {
  14415. if ( depthTest ) {
  14416. _gl.enable( _gl.DEPTH_TEST );
  14417. } else {
  14418. _gl.disable( _gl.DEPTH_TEST );
  14419. }
  14420. _oldDepthTest = depthTest;
  14421. }
  14422. };
  14423. this.setDepthWrite = function ( depthWrite ) {
  14424. if ( _oldDepthWrite !== depthWrite ) {
  14425. _gl.depthMask( depthWrite );
  14426. _oldDepthWrite = depthWrite;
  14427. }
  14428. };
  14429. function setLineWidth ( width ) {
  14430. if ( width !== _oldLineWidth ) {
  14431. _gl.lineWidth( width );
  14432. _oldLineWidth = width;
  14433. }
  14434. };
  14435. function setPolygonOffset ( polygonoffset, factor, units ) {
  14436. if ( _oldPolygonOffset !== polygonoffset ) {
  14437. if ( polygonoffset ) {
  14438. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14439. } else {
  14440. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14441. }
  14442. _oldPolygonOffset = polygonoffset;
  14443. }
  14444. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14445. _gl.polygonOffset( factor, units );
  14446. _oldPolygonOffsetFactor = factor;
  14447. _oldPolygonOffsetUnits = units;
  14448. }
  14449. };
  14450. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14451. if ( blending !== _oldBlending ) {
  14452. if ( blending === THREE.NoBlending ) {
  14453. _gl.disable( _gl.BLEND );
  14454. } else if ( blending === THREE.AdditiveBlending ) {
  14455. _gl.enable( _gl.BLEND );
  14456. _gl.blendEquation( _gl.FUNC_ADD );
  14457. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14458. } else if ( blending === THREE.SubtractiveBlending ) {
  14459. // TODO: Find blendFuncSeparate() combination
  14460. _gl.enable( _gl.BLEND );
  14461. _gl.blendEquation( _gl.FUNC_ADD );
  14462. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14463. } else if ( blending === THREE.MultiplyBlending ) {
  14464. // TODO: Find blendFuncSeparate() combination
  14465. _gl.enable( _gl.BLEND );
  14466. _gl.blendEquation( _gl.FUNC_ADD );
  14467. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14468. } else if ( blending === THREE.CustomBlending ) {
  14469. _gl.enable( _gl.BLEND );
  14470. } else {
  14471. _gl.enable( _gl.BLEND );
  14472. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14473. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14474. }
  14475. _oldBlending = blending;
  14476. }
  14477. if ( blending === THREE.CustomBlending ) {
  14478. if ( blendEquation !== _oldBlendEquation ) {
  14479. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14480. _oldBlendEquation = blendEquation;
  14481. }
  14482. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14483. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14484. _oldBlendSrc = blendSrc;
  14485. _oldBlendDst = blendDst;
  14486. }
  14487. } else {
  14488. _oldBlendEquation = null;
  14489. _oldBlendSrc = null;
  14490. _oldBlendDst = null;
  14491. }
  14492. };
  14493. // Defines
  14494. function generateDefines ( defines ) {
  14495. var value, chunk, chunks = [];
  14496. for ( var d in defines ) {
  14497. value = defines[ d ];
  14498. if ( value === false ) continue;
  14499. chunk = "#define " + d + " " + value;
  14500. chunks.push( chunk );
  14501. }
  14502. return chunks.join( "\n" );
  14503. };
  14504. // Shaders
  14505. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14506. var p, pl, d, program, code;
  14507. var chunks = [];
  14508. // Generate code
  14509. if ( shaderID ) {
  14510. chunks.push( shaderID );
  14511. } else {
  14512. chunks.push( fragmentShader );
  14513. chunks.push( vertexShader );
  14514. }
  14515. for ( d in defines ) {
  14516. chunks.push( d );
  14517. chunks.push( defines[ d ] );
  14518. }
  14519. for ( p in parameters ) {
  14520. chunks.push( p );
  14521. chunks.push( parameters[ p ] );
  14522. }
  14523. code = chunks.join();
  14524. // Check if code has been already compiled
  14525. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14526. var programInfo = _programs[ p ];
  14527. if ( programInfo.code === code ) {
  14528. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14529. programInfo.usedTimes ++;
  14530. return programInfo.program;
  14531. }
  14532. }
  14533. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14534. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14535. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14536. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14537. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14538. }
  14539. // console.log( "building new program " );
  14540. //
  14541. var customDefines = generateDefines( defines );
  14542. //
  14543. program = _gl.createProgram();
  14544. var prefix_vertex = [
  14545. "precision " + _precision + " float;",
  14546. customDefines,
  14547. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14548. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14549. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14550. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14551. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14552. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14553. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14554. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14555. "#define MAX_SHADOWS " + parameters.maxShadows,
  14556. "#define MAX_BONES " + parameters.maxBones,
  14557. parameters.map ? "#define USE_MAP" : "",
  14558. parameters.envMap ? "#define USE_ENVMAP" : "",
  14559. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14560. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14561. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14562. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14563. parameters.vertexColors ? "#define USE_COLOR" : "",
  14564. parameters.skinning ? "#define USE_SKINNING" : "",
  14565. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14566. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14567. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14568. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14569. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14570. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14571. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14572. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14573. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14574. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14575. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14576. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14577. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14578. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14579. "uniform mat4 modelMatrix;",
  14580. "uniform mat4 modelViewMatrix;",
  14581. "uniform mat4 projectionMatrix;",
  14582. "uniform mat4 viewMatrix;",
  14583. "uniform mat3 normalMatrix;",
  14584. "uniform vec3 cameraPosition;",
  14585. "attribute vec3 position;",
  14586. "attribute vec3 normal;",
  14587. "attribute vec2 uv;",
  14588. "attribute vec2 uv2;",
  14589. "#ifdef USE_COLOR",
  14590. "attribute vec3 color;",
  14591. "#endif",
  14592. "#ifdef USE_MORPHTARGETS",
  14593. "attribute vec3 morphTarget0;",
  14594. "attribute vec3 morphTarget1;",
  14595. "attribute vec3 morphTarget2;",
  14596. "attribute vec3 morphTarget3;",
  14597. "#ifdef USE_MORPHNORMALS",
  14598. "attribute vec3 morphNormal0;",
  14599. "attribute vec3 morphNormal1;",
  14600. "attribute vec3 morphNormal2;",
  14601. "attribute vec3 morphNormal3;",
  14602. "#else",
  14603. "attribute vec3 morphTarget4;",
  14604. "attribute vec3 morphTarget5;",
  14605. "attribute vec3 morphTarget6;",
  14606. "attribute vec3 morphTarget7;",
  14607. "#endif",
  14608. "#endif",
  14609. "#ifdef USE_SKINNING",
  14610. "attribute vec4 skinIndex;",
  14611. "attribute vec4 skinWeight;",
  14612. "#endif",
  14613. ""
  14614. ].join("\n");
  14615. var prefix_fragment = [
  14616. "precision " + _precision + " float;",
  14617. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14618. customDefines,
  14619. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14620. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14621. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14622. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14623. "#define MAX_SHADOWS " + parameters.maxShadows,
  14624. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14625. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14626. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14627. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14628. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14629. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14630. parameters.map ? "#define USE_MAP" : "",
  14631. parameters.envMap ? "#define USE_ENVMAP" : "",
  14632. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14633. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14634. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14635. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14636. parameters.vertexColors ? "#define USE_COLOR" : "",
  14637. parameters.metal ? "#define METAL" : "",
  14638. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14639. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14640. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14641. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14642. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14643. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14644. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14645. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14646. "uniform mat4 viewMatrix;",
  14647. "uniform vec3 cameraPosition;",
  14648. ""
  14649. ].join("\n");
  14650. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14651. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14652. _gl.attachShader( program, glVertexShader );
  14653. _gl.attachShader( program, glFragmentShader );
  14654. _gl.linkProgram( program );
  14655. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14656. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14657. }
  14658. // clean up
  14659. _gl.deleteShader( glFragmentShader );
  14660. _gl.deleteShader( glVertexShader );
  14661. // console.log( prefix_fragment + fragmentShader );
  14662. // console.log( prefix_vertex + vertexShader );
  14663. program.uniforms = {};
  14664. program.attributes = {};
  14665. var identifiers, u, a, i;
  14666. // cache uniform locations
  14667. identifiers = [
  14668. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14669. 'morphTargetInfluences'
  14670. ];
  14671. if ( parameters.useVertexTexture ) {
  14672. identifiers.push( 'boneTexture' );
  14673. } else {
  14674. identifiers.push( 'boneGlobalMatrices' );
  14675. }
  14676. for ( u in uniforms ) {
  14677. identifiers.push( u );
  14678. }
  14679. cacheUniformLocations( program, identifiers );
  14680. // cache attributes locations
  14681. identifiers = [
  14682. "position", "normal", "uv", "uv2", "tangent", "color",
  14683. "skinIndex", "skinWeight", "lineDistance"
  14684. ];
  14685. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14686. identifiers.push( "morphTarget" + i );
  14687. }
  14688. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14689. identifiers.push( "morphNormal" + i );
  14690. }
  14691. for ( a in attributes ) {
  14692. identifiers.push( a );
  14693. }
  14694. cacheAttributeLocations( program, identifiers );
  14695. program.id = _programs_counter ++;
  14696. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14697. _this.info.memory.programs = _programs.length;
  14698. return program;
  14699. };
  14700. // Shader parameters cache
  14701. function cacheUniformLocations ( program, identifiers ) {
  14702. var i, l, id;
  14703. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14704. id = identifiers[ i ];
  14705. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14706. }
  14707. };
  14708. function cacheAttributeLocations ( program, identifiers ) {
  14709. var i, l, id;
  14710. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14711. id = identifiers[ i ];
  14712. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14713. }
  14714. };
  14715. function addLineNumbers ( string ) {
  14716. var chunks = string.split( "\n" );
  14717. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14718. // Chrome reports shader errors on lines
  14719. // starting counting from 1
  14720. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14721. }
  14722. return chunks.join( "\n" );
  14723. };
  14724. function getShader ( type, string ) {
  14725. var shader;
  14726. if ( type === "fragment" ) {
  14727. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14728. } else if ( type === "vertex" ) {
  14729. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14730. }
  14731. _gl.shaderSource( shader, string );
  14732. _gl.compileShader( shader );
  14733. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14734. console.error( _gl.getShaderInfoLog( shader ) );
  14735. console.error( addLineNumbers( string ) );
  14736. return null;
  14737. }
  14738. return shader;
  14739. };
  14740. // Textures
  14741. function isPowerOfTwo ( value ) {
  14742. return ( value & ( value - 1 ) ) === 0;
  14743. };
  14744. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14745. if ( isImagePowerOfTwo ) {
  14746. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14747. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14748. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14749. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14750. } else {
  14751. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14752. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14753. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14754. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14755. }
  14756. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14757. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14758. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14759. texture.__oldAnisotropy = texture.anisotropy;
  14760. }
  14761. }
  14762. };
  14763. this.setTexture = function ( texture, slot ) {
  14764. if ( texture.needsUpdate ) {
  14765. if ( ! texture.__webglInit ) {
  14766. texture.__webglInit = true;
  14767. texture.addEventListener( 'dispose', onTextureDispose );
  14768. texture.__webglTexture = _gl.createTexture();
  14769. _this.info.memory.textures ++;
  14770. }
  14771. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14772. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14773. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14774. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14775. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14776. var image = texture.image,
  14777. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14778. glFormat = paramThreeToGL( texture.format ),
  14779. glType = paramThreeToGL( texture.type );
  14780. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14781. var mipmap, mipmaps = texture.mipmaps;
  14782. if ( texture instanceof THREE.DataTexture ) {
  14783. // use manually created mipmaps if available
  14784. // if there are no manual mipmaps
  14785. // set 0 level mipmap and then use GL to generate other mipmap levels
  14786. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14787. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14788. mipmap = mipmaps[ i ];
  14789. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14790. }
  14791. texture.generateMipmaps = false;
  14792. } else {
  14793. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14794. }
  14795. } else if ( texture instanceof THREE.CompressedTexture ) {
  14796. // compressed textures can only use manually created mipmaps
  14797. // WebGL can't generate mipmaps for DDS textures
  14798. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14799. mipmap = mipmaps[ i ];
  14800. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14801. }
  14802. } else { // regular Texture (image, video, canvas)
  14803. // use manually created mipmaps if available
  14804. // if there are no manual mipmaps
  14805. // set 0 level mipmap and then use GL to generate other mipmap levels
  14806. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14807. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14808. mipmap = mipmaps[ i ];
  14809. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14810. }
  14811. texture.generateMipmaps = false;
  14812. } else {
  14813. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14814. }
  14815. }
  14816. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14817. texture.needsUpdate = false;
  14818. if ( texture.onUpdate ) texture.onUpdate();
  14819. } else {
  14820. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14821. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14822. }
  14823. };
  14824. function clampToMaxSize ( image, maxSize ) {
  14825. if ( image.width <= maxSize && image.height <= maxSize ) {
  14826. return image;
  14827. }
  14828. // Warning: Scaling through the canvas will only work with images that use
  14829. // premultiplied alpha.
  14830. var maxDimension = Math.max( image.width, image.height );
  14831. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14832. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14833. var canvas = document.createElement( 'canvas' );
  14834. canvas.width = newWidth;
  14835. canvas.height = newHeight;
  14836. var ctx = canvas.getContext( "2d" );
  14837. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14838. return canvas;
  14839. }
  14840. function setCubeTexture ( texture, slot ) {
  14841. if ( texture.image.length === 6 ) {
  14842. if ( texture.needsUpdate ) {
  14843. if ( ! texture.image.__webglTextureCube ) {
  14844. texture.image.__webglTextureCube = _gl.createTexture();
  14845. _this.info.memory.textures ++;
  14846. }
  14847. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14848. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14849. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14850. var isCompressed = texture instanceof THREE.CompressedTexture;
  14851. var cubeImage = [];
  14852. for ( var i = 0; i < 6; i ++ ) {
  14853. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14854. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14855. } else {
  14856. cubeImage[ i ] = texture.image[ i ];
  14857. }
  14858. }
  14859. var image = cubeImage[ 0 ],
  14860. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14861. glFormat = paramThreeToGL( texture.format ),
  14862. glType = paramThreeToGL( texture.type );
  14863. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14864. for ( var i = 0; i < 6; i ++ ) {
  14865. if ( isCompressed ) {
  14866. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14867. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14868. mipmap = mipmaps[ j ];
  14869. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14870. }
  14871. } else {
  14872. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14873. }
  14874. }
  14875. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14876. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14877. }
  14878. texture.needsUpdate = false;
  14879. if ( texture.onUpdate ) texture.onUpdate();
  14880. } else {
  14881. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14882. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14883. }
  14884. }
  14885. };
  14886. function setCubeTextureDynamic ( texture, slot ) {
  14887. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14888. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14889. };
  14890. // Render targets
  14891. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14892. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14893. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14894. };
  14895. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14896. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14897. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14898. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14899. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14900. /* For some reason this is not working. Defaulting to RGBA4.
  14901. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14902. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14903. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14904. */
  14905. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14906. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14907. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14908. } else {
  14909. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14910. }
  14911. };
  14912. this.setRenderTarget = function ( renderTarget ) {
  14913. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14914. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14915. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14916. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14917. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14918. renderTarget.__webglTexture = _gl.createTexture();
  14919. _this.info.memory.textures ++;
  14920. // Setup texture, create render and frame buffers
  14921. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14922. glFormat = paramThreeToGL( renderTarget.format ),
  14923. glType = paramThreeToGL( renderTarget.type );
  14924. if ( isCube ) {
  14925. renderTarget.__webglFramebuffer = [];
  14926. renderTarget.__webglRenderbuffer = [];
  14927. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14928. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14929. for ( var i = 0; i < 6; i ++ ) {
  14930. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14931. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14932. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14933. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14934. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14935. }
  14936. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14937. } else {
  14938. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14939. if ( renderTarget.shareDepthFrom ) {
  14940. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14941. } else {
  14942. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14943. }
  14944. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14945. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14946. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14947. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14948. if ( renderTarget.shareDepthFrom ) {
  14949. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14950. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14951. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14952. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14953. }
  14954. } else {
  14955. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14956. }
  14957. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14958. }
  14959. // Release everything
  14960. if ( isCube ) {
  14961. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14962. } else {
  14963. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14964. }
  14965. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14966. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14967. }
  14968. var framebuffer, width, height, vx, vy;
  14969. if ( renderTarget ) {
  14970. if ( isCube ) {
  14971. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14972. } else {
  14973. framebuffer = renderTarget.__webglFramebuffer;
  14974. }
  14975. width = renderTarget.width;
  14976. height = renderTarget.height;
  14977. vx = 0;
  14978. vy = 0;
  14979. } else {
  14980. framebuffer = null;
  14981. width = _viewportWidth;
  14982. height = _viewportHeight;
  14983. vx = _viewportX;
  14984. vy = _viewportY;
  14985. }
  14986. if ( framebuffer !== _currentFramebuffer ) {
  14987. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14988. _gl.viewport( vx, vy, width, height );
  14989. _currentFramebuffer = framebuffer;
  14990. }
  14991. _currentWidth = width;
  14992. _currentHeight = height;
  14993. };
  14994. function updateRenderTargetMipmap ( renderTarget ) {
  14995. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14996. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14997. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14998. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14999. } else {
  15000. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15001. _gl.generateMipmap( _gl.TEXTURE_2D );
  15002. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15003. }
  15004. };
  15005. // Fallback filters for non-power-of-2 textures
  15006. function filterFallback ( f ) {
  15007. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15008. return _gl.NEAREST;
  15009. }
  15010. return _gl.LINEAR;
  15011. };
  15012. // Map three.js constants to WebGL constants
  15013. function paramThreeToGL ( p ) {
  15014. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15015. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15016. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15017. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15018. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15019. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15020. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15021. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15022. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15023. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15024. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15025. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15026. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15027. if ( p === THREE.ByteType ) return _gl.BYTE;
  15028. if ( p === THREE.ShortType ) return _gl.SHORT;
  15029. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15030. if ( p === THREE.IntType ) return _gl.INT;
  15031. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15032. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15033. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15034. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15035. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15036. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15037. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15038. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15039. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15040. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15041. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15042. if ( p === THREE.OneFactor ) return _gl.ONE;
  15043. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15044. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15045. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15046. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15047. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15048. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15049. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15050. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15051. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15052. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15053. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15054. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15055. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15056. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15057. }
  15058. return 0;
  15059. };
  15060. // Allocations
  15061. function allocateBones ( object ) {
  15062. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15063. return 1024;
  15064. } else {
  15065. // default for when object is not specified
  15066. // ( for example when prebuilding shader
  15067. // to be used with multiple objects )
  15068. //
  15069. // - leave some extra space for other uniforms
  15070. // - limit here is ANGLE's 254 max uniform vectors
  15071. // (up to 54 should be safe)
  15072. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15073. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15074. var maxBones = nVertexMatrices;
  15075. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15076. maxBones = Math.min( object.bones.length, maxBones );
  15077. if ( maxBones < object.bones.length ) {
  15078. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15079. }
  15080. }
  15081. return maxBones;
  15082. }
  15083. };
  15084. function allocateLights ( lights ) {
  15085. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  15086. dirLights = pointLights = spotLights = hemiLights = 0;
  15087. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15088. light = lights[ l ];
  15089. if ( light.onlyShadow ) continue;
  15090. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15091. if ( light instanceof THREE.PointLight ) pointLights ++;
  15092. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15093. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15094. }
  15095. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15096. };
  15097. function allocateShadows ( lights ) {
  15098. var l, ll, light, maxShadows = 0;
  15099. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  15100. light = lights[ l ];
  15101. if ( ! light.castShadow ) continue;
  15102. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15103. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15104. }
  15105. return maxShadows;
  15106. };
  15107. // Initialization
  15108. function initGL () {
  15109. try {
  15110. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15111. throw 'Error creating WebGL context.';
  15112. }
  15113. } catch ( error ) {
  15114. console.error( error );
  15115. }
  15116. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15117. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15118. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15119. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15120. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15121. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15122. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15123. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15124. if ( ! _glExtensionTextureFloat ) {
  15125. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15126. }
  15127. if ( ! _glExtensionStandardDerivatives ) {
  15128. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15129. }
  15130. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15131. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15132. }
  15133. if ( ! _glExtensionCompressedTextureS3TC ) {
  15134. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15135. }
  15136. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15137. _gl.getShaderPrecisionFormat = function() {
  15138. return {
  15139. "rangeMin" : 1,
  15140. "rangeMax" : 1,
  15141. "precision" : 1
  15142. };
  15143. }
  15144. }
  15145. };
  15146. function setDefaultGLState () {
  15147. _gl.clearColor( 0, 0, 0, 1 );
  15148. _gl.clearDepth( 1 );
  15149. _gl.clearStencil( 0 );
  15150. _gl.enable( _gl.DEPTH_TEST );
  15151. _gl.depthFunc( _gl.LEQUAL );
  15152. _gl.frontFace( _gl.CCW );
  15153. _gl.cullFace( _gl.BACK );
  15154. _gl.enable( _gl.CULL_FACE );
  15155. _gl.enable( _gl.BLEND );
  15156. _gl.blendEquation( _gl.FUNC_ADD );
  15157. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15158. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15159. };
  15160. // default plugins (order is important)
  15161. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15162. this.addPrePlugin( this.shadowMapPlugin );
  15163. this.addPostPlugin( new THREE.SpritePlugin() );
  15164. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15165. };
  15166. /**
  15167. * @author szimek / https://github.com/szimek/
  15168. * @author alteredq / http://alteredqualia.com/
  15169. */
  15170. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15171. this.width = width;
  15172. this.height = height;
  15173. options = options || {};
  15174. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15175. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15176. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15177. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15178. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15179. this.offset = new THREE.Vector2( 0, 0 );
  15180. this.repeat = new THREE.Vector2( 1, 1 );
  15181. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15182. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15183. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15184. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15185. this.generateMipmaps = true;
  15186. this.shareDepthFrom = null;
  15187. };
  15188. THREE.WebGLRenderTarget.prototype = {
  15189. constructor: THREE.WebGLRenderTarget,
  15190. clone: function () {
  15191. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15192. tmp.wrapS = this.wrapS;
  15193. tmp.wrapT = this.wrapT;
  15194. tmp.magFilter = this.magFilter;
  15195. tmp.minFilter = this.minFilter;
  15196. tmp.anisotropy = this.anisotropy;
  15197. tmp.offset.copy( this.offset );
  15198. tmp.repeat.copy( this.repeat );
  15199. tmp.format = this.format;
  15200. tmp.type = this.type;
  15201. tmp.depthBuffer = this.depthBuffer;
  15202. tmp.stencilBuffer = this.stencilBuffer;
  15203. tmp.generateMipmaps = this.generateMipmaps;
  15204. tmp.shareDepthFrom = this.shareDepthFrom;
  15205. return tmp;
  15206. },
  15207. dispose: function () {
  15208. this.dispatchEvent( { type: 'dispose' } );
  15209. }
  15210. };
  15211. THREE.extend( THREE.WebGLRenderTarget.prototype, THREE.EventDispatcher.prototype );
  15212. /**
  15213. * @author alteredq / http://alteredqualia.com
  15214. */
  15215. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15216. THREE.WebGLRenderTarget.call( this, width, height, options );
  15217. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15218. };
  15219. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15220. /**
  15221. * @author mrdoob / http://mrdoob.com/
  15222. */
  15223. THREE.RenderableVertex = function () {
  15224. this.positionWorld = new THREE.Vector3();
  15225. this.positionScreen = new THREE.Vector4();
  15226. this.visible = true;
  15227. };
  15228. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15229. this.positionWorld.copy( vertex.positionWorld );
  15230. this.positionScreen.copy( vertex.positionScreen );
  15231. };
  15232. /**
  15233. * @author mrdoob / http://mrdoob.com/
  15234. */
  15235. THREE.RenderableFace3 = function () {
  15236. this.v1 = new THREE.RenderableVertex();
  15237. this.v2 = new THREE.RenderableVertex();
  15238. this.v3 = new THREE.RenderableVertex();
  15239. this.centroidModel = new THREE.Vector3();
  15240. this.normalModel = new THREE.Vector3();
  15241. this.normalModelView = new THREE.Vector3();
  15242. this.vertexNormalsLength = 0;
  15243. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15244. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15245. this.color = null;
  15246. this.material = null;
  15247. this.uvs = [[]];
  15248. this.z = null;
  15249. };
  15250. /**
  15251. * @author mrdoob / http://mrdoob.com/
  15252. */
  15253. THREE.RenderableFace4 = function () {
  15254. this.v1 = new THREE.RenderableVertex();
  15255. this.v2 = new THREE.RenderableVertex();
  15256. this.v3 = new THREE.RenderableVertex();
  15257. this.v4 = new THREE.RenderableVertex();
  15258. this.centroidModel = new THREE.Vector3();
  15259. this.normalModel = new THREE.Vector3();
  15260. this.normalModelView = new THREE.Vector3();
  15261. this.vertexNormalsLength = 0;
  15262. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15263. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15264. this.color = null;
  15265. this.material = null;
  15266. this.uvs = [[]];
  15267. this.z = null;
  15268. };
  15269. /**
  15270. * @author mrdoob / http://mrdoob.com/
  15271. */
  15272. THREE.RenderableObject = function () {
  15273. this.object = null;
  15274. this.z = null;
  15275. };
  15276. /**
  15277. * @author mrdoob / http://mrdoob.com/
  15278. */
  15279. THREE.RenderableParticle = function () {
  15280. this.object = null;
  15281. this.x = null;
  15282. this.y = null;
  15283. this.z = null;
  15284. this.rotation = null;
  15285. this.scale = new THREE.Vector2();
  15286. this.material = null;
  15287. };
  15288. /**
  15289. * @author mrdoob / http://mrdoob.com/
  15290. */
  15291. THREE.RenderableLine = function () {
  15292. this.z = null;
  15293. this.v1 = new THREE.RenderableVertex();
  15294. this.v2 = new THREE.RenderableVertex();
  15295. this.material = null;
  15296. };
  15297. /**
  15298. * @author mrdoob / http://mrdoob.com/
  15299. * @author alteredq / http://alteredqualia.com/
  15300. */
  15301. THREE.GeometryUtils = {
  15302. // Merge two geometries or geometry and geometry from object (using object's transform)
  15303. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15304. var matrix, normalMatrix,
  15305. vertexOffset = geometry1.vertices.length,
  15306. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15307. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15308. vertices1 = geometry1.vertices,
  15309. vertices2 = geometry2.vertices,
  15310. faces1 = geometry1.faces,
  15311. faces2 = geometry2.faces,
  15312. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15313. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15314. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15315. if ( object2 instanceof THREE.Mesh ) {
  15316. object2.matrixAutoUpdate && object2.updateMatrix();
  15317. matrix = object2.matrix;
  15318. normalMatrix = new THREE.Matrix3();
  15319. normalMatrix.getInverse( matrix );
  15320. normalMatrix.transpose();
  15321. }
  15322. // vertices
  15323. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15324. var vertex = vertices2[ i ];
  15325. var vertexCopy = vertex.clone();
  15326. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15327. vertices1.push( vertexCopy );
  15328. }
  15329. // faces
  15330. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15331. var face = faces2[ i ], faceCopy, normal, color,
  15332. faceVertexNormals = face.vertexNormals,
  15333. faceVertexColors = face.vertexColors;
  15334. if ( face instanceof THREE.Face3 ) {
  15335. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15336. } else if ( face instanceof THREE.Face4 ) {
  15337. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15338. }
  15339. faceCopy.normal.copy( face.normal );
  15340. if ( normalMatrix ) {
  15341. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15342. }
  15343. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15344. normal = faceVertexNormals[ j ].clone();
  15345. if ( normalMatrix ) {
  15346. normal.applyMatrix3( normalMatrix ).normalize();
  15347. }
  15348. faceCopy.vertexNormals.push( normal );
  15349. }
  15350. faceCopy.color.copy( face.color );
  15351. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15352. color = faceVertexColors[ j ];
  15353. faceCopy.vertexColors.push( color.clone() );
  15354. }
  15355. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15356. faceCopy.centroid.copy( face.centroid );
  15357. if ( matrix ) {
  15358. faceCopy.centroid.applyMatrix4( matrix );
  15359. }
  15360. faces1.push( faceCopy );
  15361. }
  15362. // uvs
  15363. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15364. var uv = uvs2[ i ], uvCopy = [];
  15365. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15366. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15367. }
  15368. uvs1.push( uvCopy );
  15369. }
  15370. },
  15371. removeMaterials: function ( geometry, materialIndexArray ) {
  15372. var materialIndexMap = {};
  15373. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15374. materialIndexMap[ materialIndexArray[i] ] = true;
  15375. }
  15376. var face, newFaces = [];
  15377. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15378. face = geometry.faces[ i ];
  15379. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15380. }
  15381. geometry.faces = newFaces;
  15382. },
  15383. // Get random point in triangle (via barycentric coordinates)
  15384. // (uniform distribution)
  15385. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15386. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15387. var a, b, c,
  15388. point = new THREE.Vector3(),
  15389. tmp = THREE.GeometryUtils.__v1;
  15390. a = THREE.GeometryUtils.random();
  15391. b = THREE.GeometryUtils.random();
  15392. if ( ( a + b ) > 1 ) {
  15393. a = 1 - a;
  15394. b = 1 - b;
  15395. }
  15396. c = 1 - a - b;
  15397. point.copy( vectorA );
  15398. point.multiplyScalar( a );
  15399. tmp.copy( vectorB );
  15400. tmp.multiplyScalar( b );
  15401. point.add( tmp );
  15402. tmp.copy( vectorC );
  15403. tmp.multiplyScalar( c );
  15404. point.add( tmp );
  15405. return point;
  15406. },
  15407. // Get random point in face (triangle / quad)
  15408. // (uniform distribution)
  15409. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15410. var vA, vB, vC, vD;
  15411. if ( face instanceof THREE.Face3 ) {
  15412. vA = geometry.vertices[ face.a ];
  15413. vB = geometry.vertices[ face.b ];
  15414. vC = geometry.vertices[ face.c ];
  15415. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15416. } else if ( face instanceof THREE.Face4 ) {
  15417. vA = geometry.vertices[ face.a ];
  15418. vB = geometry.vertices[ face.b ];
  15419. vC = geometry.vertices[ face.c ];
  15420. vD = geometry.vertices[ face.d ];
  15421. var area1, area2;
  15422. if ( useCachedAreas ) {
  15423. if ( face._area1 && face._area2 ) {
  15424. area1 = face._area1;
  15425. area2 = face._area2;
  15426. } else {
  15427. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15428. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15429. face._area1 = area1;
  15430. face._area2 = area2;
  15431. }
  15432. } else {
  15433. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15434. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15435. }
  15436. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15437. if ( r < area1 ) {
  15438. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15439. } else {
  15440. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15441. }
  15442. }
  15443. },
  15444. // Get uniformly distributed random points in mesh
  15445. // - create array with cumulative sums of face areas
  15446. // - pick random number from 0 to total area
  15447. // - find corresponding place in area array by binary search
  15448. // - get random point in face
  15449. randomPointsInGeometry: function ( geometry, n ) {
  15450. var face, i,
  15451. faces = geometry.faces,
  15452. vertices = geometry.vertices,
  15453. il = faces.length,
  15454. totalArea = 0,
  15455. cumulativeAreas = [],
  15456. vA, vB, vC, vD;
  15457. // precompute face areas
  15458. for ( i = 0; i < il; i ++ ) {
  15459. face = faces[ i ];
  15460. if ( face instanceof THREE.Face3 ) {
  15461. vA = vertices[ face.a ];
  15462. vB = vertices[ face.b ];
  15463. vC = vertices[ face.c ];
  15464. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15465. } else if ( face instanceof THREE.Face4 ) {
  15466. vA = vertices[ face.a ];
  15467. vB = vertices[ face.b ];
  15468. vC = vertices[ face.c ];
  15469. vD = vertices[ face.d ];
  15470. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15471. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15472. face._area = face._area1 + face._area2;
  15473. }
  15474. totalArea += face._area;
  15475. cumulativeAreas[ i ] = totalArea;
  15476. }
  15477. // binary search cumulative areas array
  15478. function binarySearchIndices( value ) {
  15479. function binarySearch( start, end ) {
  15480. // return closest larger index
  15481. // if exact number is not found
  15482. if ( end < start )
  15483. return start;
  15484. var mid = start + Math.floor( ( end - start ) / 2 );
  15485. if ( cumulativeAreas[ mid ] > value ) {
  15486. return binarySearch( start, mid - 1 );
  15487. } else if ( cumulativeAreas[ mid ] < value ) {
  15488. return binarySearch( mid + 1, end );
  15489. } else {
  15490. return mid;
  15491. }
  15492. }
  15493. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15494. return result;
  15495. }
  15496. // pick random face weighted by face area
  15497. var r, index,
  15498. result = [];
  15499. var stats = {};
  15500. for ( i = 0; i < n; i ++ ) {
  15501. r = THREE.GeometryUtils.random() * totalArea;
  15502. index = binarySearchIndices( r );
  15503. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15504. if ( ! stats[ index ] ) {
  15505. stats[ index ] = 1;
  15506. } else {
  15507. stats[ index ] += 1;
  15508. }
  15509. }
  15510. return result;
  15511. },
  15512. // Get triangle area (half of parallelogram)
  15513. // http://mathworld.wolfram.com/TriangleArea.html
  15514. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15515. var tmp1 = THREE.GeometryUtils.__v1,
  15516. tmp2 = THREE.GeometryUtils.__v2;
  15517. tmp1.subVectors( vectorB, vectorA );
  15518. tmp2.subVectors( vectorC, vectorA );
  15519. tmp1.cross( tmp2 );
  15520. return 0.5 * tmp1.length();
  15521. },
  15522. // Center geometry so that 0,0,0 is in center of bounding box
  15523. center: function ( geometry ) {
  15524. geometry.computeBoundingBox();
  15525. var bb = geometry.boundingBox;
  15526. var offset = new THREE.Vector3();
  15527. offset.addVectors( bb.min, bb.max );
  15528. offset.multiplyScalar( -0.5 );
  15529. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15530. geometry.computeBoundingBox();
  15531. return offset;
  15532. },
  15533. // Normalize UVs to be from <0,1>
  15534. // (for now just the first set of UVs)
  15535. normalizeUVs: function ( geometry ) {
  15536. var uvSet = geometry.faceVertexUvs[ 0 ];
  15537. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15538. var uvs = uvSet[ i ];
  15539. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15540. // texture repeat
  15541. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15542. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15543. }
  15544. }
  15545. },
  15546. triangulateQuads: function ( geometry ) {
  15547. var i, il, j, jl;
  15548. var faces = [];
  15549. var faceUvs = [];
  15550. var faceVertexUvs = [];
  15551. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15552. faceUvs[ i ] = [];
  15553. }
  15554. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15555. faceVertexUvs[ i ] = [];
  15556. }
  15557. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15558. var face = geometry.faces[ i ];
  15559. if ( face instanceof THREE.Face4 ) {
  15560. var a = face.a;
  15561. var b = face.b;
  15562. var c = face.c;
  15563. var d = face.d;
  15564. var triA = new THREE.Face3();
  15565. var triB = new THREE.Face3();
  15566. triA.color.copy( face.color );
  15567. triB.color.copy( face.color );
  15568. triA.materialIndex = face.materialIndex;
  15569. triB.materialIndex = face.materialIndex;
  15570. triA.a = a;
  15571. triA.b = b;
  15572. triA.c = d;
  15573. triB.a = b;
  15574. triB.b = c;
  15575. triB.c = d;
  15576. if ( face.vertexColors.length === 4 ) {
  15577. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15578. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15579. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15580. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15581. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15582. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15583. }
  15584. faces.push( triA, triB );
  15585. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15586. if ( geometry.faceVertexUvs[ j ].length ) {
  15587. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15588. var uvA = uvs[ 0 ];
  15589. var uvB = uvs[ 1 ];
  15590. var uvC = uvs[ 2 ];
  15591. var uvD = uvs[ 3 ];
  15592. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15593. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15594. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15595. }
  15596. }
  15597. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15598. if ( geometry.faceUvs[ j ].length ) {
  15599. var faceUv = geometry.faceUvs[ j ][ i ];
  15600. faceUvs[ j ].push( faceUv, faceUv );
  15601. }
  15602. }
  15603. } else {
  15604. faces.push( face );
  15605. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15606. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15607. }
  15608. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15609. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15610. }
  15611. }
  15612. }
  15613. geometry.faces = faces;
  15614. geometry.faceUvs = faceUvs;
  15615. geometry.faceVertexUvs = faceVertexUvs;
  15616. geometry.computeCentroids();
  15617. geometry.computeFaceNormals();
  15618. geometry.computeVertexNormals();
  15619. if ( geometry.hasTangents ) geometry.computeTangents();
  15620. },
  15621. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15622. var faces = geometry.faces;
  15623. var start = startFace || 0;
  15624. var end = endFace || faces.length - 1;
  15625. for ( var i = start; i <= end; i ++ ) {
  15626. faces[i].materialIndex = index;
  15627. }
  15628. }
  15629. };
  15630. THREE.GeometryUtils.random = THREE.Math.random16;
  15631. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15632. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15633. /**
  15634. * @author alteredq / http://alteredqualia.com/
  15635. * @author mrdoob / http://mrdoob.com/
  15636. */
  15637. THREE.ImageUtils = {
  15638. crossOrigin: 'anonymous',
  15639. loadTexture: function ( url, mapping, onLoad, onError ) {
  15640. var image = new Image();
  15641. var texture = new THREE.Texture( image, mapping );
  15642. var loader = new THREE.ImageLoader();
  15643. loader.addEventListener( 'load', function ( event ) {
  15644. texture.image = event.content;
  15645. texture.needsUpdate = true;
  15646. if ( onLoad ) onLoad( texture );
  15647. } );
  15648. loader.addEventListener( 'error', function ( event ) {
  15649. if ( onError ) onError( event.message );
  15650. } );
  15651. loader.crossOrigin = this.crossOrigin;
  15652. loader.load( url, image );
  15653. texture.sourceFile = url;
  15654. return texture;
  15655. },
  15656. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15657. var texture = new THREE.CompressedTexture();
  15658. texture.mapping = mapping;
  15659. var request = new XMLHttpRequest();
  15660. request.onload = function () {
  15661. var buffer = request.response;
  15662. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15663. texture.format = dds.format;
  15664. texture.mipmaps = dds.mipmaps;
  15665. texture.image.width = dds.width;
  15666. texture.image.height = dds.height;
  15667. // gl.generateMipmap fails for compressed textures
  15668. // mipmaps must be embedded in the DDS file
  15669. // or texture filters must not use mipmapping
  15670. texture.generateMipmaps = false;
  15671. texture.needsUpdate = true;
  15672. if ( onLoad ) onLoad( texture );
  15673. }
  15674. request.onerror = onError;
  15675. request.open( 'GET', url, true );
  15676. request.responseType = "arraybuffer";
  15677. request.send( null );
  15678. return texture;
  15679. },
  15680. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15681. var images = [];
  15682. images.loadCount = 0;
  15683. var texture = new THREE.Texture();
  15684. texture.image = images;
  15685. if ( mapping !== undefined ) texture.mapping = mapping;
  15686. // no flipping needed for cube textures
  15687. texture.flipY = false;
  15688. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15689. var cubeImage = new Image();
  15690. images[ i ] = cubeImage;
  15691. cubeImage.onload = function () {
  15692. images.loadCount += 1;
  15693. if ( images.loadCount === 6 ) {
  15694. texture.needsUpdate = true;
  15695. if ( onLoad ) onLoad( texture );
  15696. }
  15697. };
  15698. cubeImage.onerror = onError;
  15699. cubeImage.crossOrigin = this.crossOrigin;
  15700. cubeImage.src = array[ i ];
  15701. }
  15702. return texture;
  15703. },
  15704. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15705. var images = [];
  15706. images.loadCount = 0;
  15707. var texture = new THREE.CompressedTexture();
  15708. texture.image = images;
  15709. if ( mapping !== undefined ) texture.mapping = mapping;
  15710. // no flipping for cube textures
  15711. // (also flipping doesn't work for compressed textures )
  15712. texture.flipY = false;
  15713. // can't generate mipmaps for compressed textures
  15714. // mips must be embedded in DDS files
  15715. texture.generateMipmaps = false;
  15716. var generateCubeFaceCallback = function ( rq, img ) {
  15717. return function () {
  15718. var buffer = rq.response;
  15719. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15720. img.format = dds.format;
  15721. img.mipmaps = dds.mipmaps;
  15722. img.width = dds.width;
  15723. img.height = dds.height;
  15724. images.loadCount += 1;
  15725. if ( images.loadCount === 6 ) {
  15726. texture.format = dds.format;
  15727. texture.needsUpdate = true;
  15728. if ( onLoad ) onLoad( texture );
  15729. }
  15730. }
  15731. }
  15732. // compressed cubemap textures as 6 separate DDS files
  15733. if ( array instanceof Array ) {
  15734. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15735. var cubeImage = {};
  15736. images[ i ] = cubeImage;
  15737. var request = new XMLHttpRequest();
  15738. request.onload = generateCubeFaceCallback( request, cubeImage );
  15739. request.onerror = onError;
  15740. var url = array[ i ];
  15741. request.open( 'GET', url, true );
  15742. request.responseType = "arraybuffer";
  15743. request.send( null );
  15744. }
  15745. // compressed cubemap texture stored in a single DDS file
  15746. } else {
  15747. var url = array;
  15748. var request = new XMLHttpRequest();
  15749. request.onload = function( ) {
  15750. var buffer = request.response;
  15751. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15752. if ( dds.isCubemap ) {
  15753. var faces = dds.mipmaps.length / dds.mipmapCount;
  15754. for ( var f = 0; f < faces; f ++ ) {
  15755. images[ f ] = { mipmaps : [] };
  15756. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15757. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15758. images[ f ].format = dds.format;
  15759. images[ f ].width = dds.width;
  15760. images[ f ].height = dds.height;
  15761. }
  15762. }
  15763. texture.format = dds.format;
  15764. texture.needsUpdate = true;
  15765. if ( onLoad ) onLoad( texture );
  15766. }
  15767. }
  15768. request.onerror = onError;
  15769. request.open( 'GET', url, true );
  15770. request.responseType = "arraybuffer";
  15771. request.send( null );
  15772. }
  15773. return texture;
  15774. },
  15775. parseDDS: function ( buffer, loadMipmaps ) {
  15776. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15777. // Adapted from @toji's DDS utils
  15778. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15779. // All values and structures referenced from:
  15780. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15781. var DDS_MAGIC = 0x20534444;
  15782. var DDSD_CAPS = 0x1,
  15783. DDSD_HEIGHT = 0x2,
  15784. DDSD_WIDTH = 0x4,
  15785. DDSD_PITCH = 0x8,
  15786. DDSD_PIXELFORMAT = 0x1000,
  15787. DDSD_MIPMAPCOUNT = 0x20000,
  15788. DDSD_LINEARSIZE = 0x80000,
  15789. DDSD_DEPTH = 0x800000;
  15790. var DDSCAPS_COMPLEX = 0x8,
  15791. DDSCAPS_MIPMAP = 0x400000,
  15792. DDSCAPS_TEXTURE = 0x1000;
  15793. var DDSCAPS2_CUBEMAP = 0x200,
  15794. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15795. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15796. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15797. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15798. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15799. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15800. DDSCAPS2_VOLUME = 0x200000;
  15801. var DDPF_ALPHAPIXELS = 0x1,
  15802. DDPF_ALPHA = 0x2,
  15803. DDPF_FOURCC = 0x4,
  15804. DDPF_RGB = 0x40,
  15805. DDPF_YUV = 0x200,
  15806. DDPF_LUMINANCE = 0x20000;
  15807. function fourCCToInt32( value ) {
  15808. return value.charCodeAt(0) +
  15809. (value.charCodeAt(1) << 8) +
  15810. (value.charCodeAt(2) << 16) +
  15811. (value.charCodeAt(3) << 24);
  15812. }
  15813. function int32ToFourCC( value ) {
  15814. return String.fromCharCode(
  15815. value & 0xff,
  15816. (value >> 8) & 0xff,
  15817. (value >> 16) & 0xff,
  15818. (value >> 24) & 0xff
  15819. );
  15820. }
  15821. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15822. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15823. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15824. var headerLengthInt = 31; // The header length in 32 bit ints
  15825. // Offsets into the header array
  15826. var off_magic = 0;
  15827. var off_size = 1;
  15828. var off_flags = 2;
  15829. var off_height = 3;
  15830. var off_width = 4;
  15831. var off_mipmapCount = 7;
  15832. var off_pfFlags = 20;
  15833. var off_pfFourCC = 21;
  15834. var off_caps = 27;
  15835. var off_caps2 = 28;
  15836. var off_caps3 = 29;
  15837. var off_caps4 = 30;
  15838. // Parse header
  15839. var header = new Int32Array( buffer, 0, headerLengthInt );
  15840. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15841. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15842. return dds;
  15843. }
  15844. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15845. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15846. return dds;
  15847. }
  15848. var blockBytes;
  15849. var fourCC = header[ off_pfFourCC ];
  15850. switch ( fourCC ) {
  15851. case FOURCC_DXT1:
  15852. blockBytes = 8;
  15853. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15854. break;
  15855. case FOURCC_DXT3:
  15856. blockBytes = 16;
  15857. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15858. break;
  15859. case FOURCC_DXT5:
  15860. blockBytes = 16;
  15861. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15862. break;
  15863. default:
  15864. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15865. return dds;
  15866. }
  15867. dds.mipmapCount = 1;
  15868. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15869. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15870. }
  15871. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15872. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15873. dds.width = header[ off_width ];
  15874. dds.height = header[ off_height ];
  15875. var dataOffset = header[ off_size ] + 4;
  15876. // Extract mipmaps buffers
  15877. var width = dds.width;
  15878. var height = dds.height;
  15879. var faces = dds.isCubemap ? 6 : 1;
  15880. for ( var face = 0; face < faces; face ++ ) {
  15881. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15882. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15883. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15884. var mipmap = { "data": byteArray, "width": width, "height": height };
  15885. dds.mipmaps.push( mipmap );
  15886. dataOffset += dataLength;
  15887. width = Math.max( width * 0.5, 1 );
  15888. height = Math.max( height * 0.5, 1 );
  15889. }
  15890. width = dds.width;
  15891. height = dds.height;
  15892. }
  15893. return dds;
  15894. },
  15895. getNormalMap: function ( image, depth ) {
  15896. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15897. var cross = function ( a, b ) {
  15898. 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 ] ];
  15899. }
  15900. var subtract = function ( a, b ) {
  15901. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15902. }
  15903. var normalize = function ( a ) {
  15904. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15905. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15906. }
  15907. depth = depth | 1;
  15908. var width = image.width;
  15909. var height = image.height;
  15910. var canvas = document.createElement( 'canvas' );
  15911. canvas.width = width;
  15912. canvas.height = height;
  15913. var context = canvas.getContext( '2d' );
  15914. context.drawImage( image, 0, 0 );
  15915. var data = context.getImageData( 0, 0, width, height ).data;
  15916. var imageData = context.createImageData( width, height );
  15917. var output = imageData.data;
  15918. for ( var x = 0; x < width; x ++ ) {
  15919. for ( var y = 0; y < height; y ++ ) {
  15920. var ly = y - 1 < 0 ? 0 : y - 1;
  15921. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15922. var lx = x - 1 < 0 ? 0 : x - 1;
  15923. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15924. var points = [];
  15925. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15926. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15927. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15928. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15929. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15930. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15931. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15932. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15933. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15934. var normals = [];
  15935. var num_points = points.length;
  15936. for ( var i = 0; i < num_points; i ++ ) {
  15937. var v1 = points[ i ];
  15938. var v2 = points[ ( i + 1 ) % num_points ];
  15939. v1 = subtract( v1, origin );
  15940. v2 = subtract( v2, origin );
  15941. normals.push( normalize( cross( v1, v2 ) ) );
  15942. }
  15943. var normal = [ 0, 0, 0 ];
  15944. for ( var i = 0; i < normals.length; i ++ ) {
  15945. normal[ 0 ] += normals[ i ][ 0 ];
  15946. normal[ 1 ] += normals[ i ][ 1 ];
  15947. normal[ 2 ] += normals[ i ][ 2 ];
  15948. }
  15949. normal[ 0 ] /= normals.length;
  15950. normal[ 1 ] /= normals.length;
  15951. normal[ 2 ] /= normals.length;
  15952. var idx = ( y * width + x ) * 4;
  15953. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15954. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15955. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15956. output[ idx + 3 ] = 255;
  15957. }
  15958. }
  15959. context.putImageData( imageData, 0, 0 );
  15960. return canvas;
  15961. },
  15962. generateDataTexture: function ( width, height, color ) {
  15963. var size = width * height;
  15964. var data = new Uint8Array( 3 * size );
  15965. var r = Math.floor( color.r * 255 );
  15966. var g = Math.floor( color.g * 255 );
  15967. var b = Math.floor( color.b * 255 );
  15968. for ( var i = 0; i < size; i ++ ) {
  15969. data[ i * 3 ] = r;
  15970. data[ i * 3 + 1 ] = g;
  15971. data[ i * 3 + 2 ] = b;
  15972. }
  15973. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15974. texture.needsUpdate = true;
  15975. return texture;
  15976. }
  15977. };
  15978. /**
  15979. * @author alteredq / http://alteredqualia.com/
  15980. */
  15981. THREE.SceneUtils = {
  15982. createMultiMaterialObject: function ( geometry, materials ) {
  15983. var group = new THREE.Object3D();
  15984. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15985. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15986. }
  15987. return group;
  15988. },
  15989. detach : function ( child, parent, scene ) {
  15990. child.applyMatrix( parent.matrixWorld );
  15991. parent.remove( child );
  15992. scene.add( child );
  15993. },
  15994. attach: function ( child, scene, parent ) {
  15995. var matrixWorldInverse = new THREE.Matrix4();
  15996. matrixWorldInverse.getInverse( parent.matrixWorld );
  15997. child.applyMatrix( matrixWorldInverse );
  15998. scene.remove( child );
  15999. parent.add( child );
  16000. }
  16001. };
  16002. /**
  16003. * @author zz85 / http://www.lab4games.net/zz85/blog
  16004. * @author alteredq / http://alteredqualia.com/
  16005. *
  16006. * For Text operations in three.js (See TextGeometry)
  16007. *
  16008. * It uses techniques used in:
  16009. *
  16010. * typeface.js and canvastext
  16011. * For converting fonts and rendering with javascript
  16012. * http://typeface.neocracy.org
  16013. *
  16014. * Triangulation ported from AS3
  16015. * Simple Polygon Triangulation
  16016. * http://actionsnippet.com/?p=1462
  16017. *
  16018. * A Method to triangulate shapes with holes
  16019. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16020. *
  16021. */
  16022. THREE.FontUtils = {
  16023. faces : {},
  16024. // Just for now. face[weight][style]
  16025. face : "helvetiker",
  16026. weight: "normal",
  16027. style : "normal",
  16028. size : 150,
  16029. divisions : 10,
  16030. getFace : function() {
  16031. return this.faces[ this.face ][ this.weight ][ this.style ];
  16032. },
  16033. loadFace : function( data ) {
  16034. var family = data.familyName.toLowerCase();
  16035. var ThreeFont = this;
  16036. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16037. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16038. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16039. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16040. return data;
  16041. },
  16042. drawText : function( text ) {
  16043. var characterPts = [], allPts = [];
  16044. // RenderText
  16045. var i, p,
  16046. face = this.getFace(),
  16047. scale = this.size / face.resolution,
  16048. offset = 0,
  16049. chars = String( text ).split( '' ),
  16050. length = chars.length;
  16051. var fontPaths = [];
  16052. for ( i = 0; i < length; i ++ ) {
  16053. var path = new THREE.Path();
  16054. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16055. offset += ret.offset;
  16056. fontPaths.push( ret.path );
  16057. }
  16058. // get the width
  16059. var width = offset / 2;
  16060. //
  16061. // for ( p = 0; p < allPts.length; p++ ) {
  16062. //
  16063. // allPts[ p ].x -= width;
  16064. //
  16065. // }
  16066. //var extract = this.extractPoints( allPts, characterPts );
  16067. //extract.contour = allPts;
  16068. //extract.paths = fontPaths;
  16069. //extract.offset = width;
  16070. return { paths : fontPaths, offset : width };
  16071. },
  16072. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16073. var pts = [];
  16074. var i, i2, divisions,
  16075. outline, action, length,
  16076. scaleX, scaleY,
  16077. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16078. laste,
  16079. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16080. if ( !glyph ) return;
  16081. if ( glyph.o ) {
  16082. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16083. length = outline.length;
  16084. scaleX = scale;
  16085. scaleY = scale;
  16086. for ( i = 0; i < length; ) {
  16087. action = outline[ i ++ ];
  16088. //console.log( action );
  16089. switch( action ) {
  16090. case 'm':
  16091. // Move To
  16092. x = outline[ i++ ] * scaleX + offset;
  16093. y = outline[ i++ ] * scaleY;
  16094. path.moveTo( x, y );
  16095. break;
  16096. case 'l':
  16097. // Line To
  16098. x = outline[ i++ ] * scaleX + offset;
  16099. y = outline[ i++ ] * scaleY;
  16100. path.lineTo(x,y);
  16101. break;
  16102. case 'q':
  16103. // QuadraticCurveTo
  16104. cpx = outline[ i++ ] * scaleX + offset;
  16105. cpy = outline[ i++ ] * scaleY;
  16106. cpx1 = outline[ i++ ] * scaleX + offset;
  16107. cpy1 = outline[ i++ ] * scaleY;
  16108. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16109. laste = pts[ pts.length - 1 ];
  16110. if ( laste ) {
  16111. cpx0 = laste.x;
  16112. cpy0 = laste.y;
  16113. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16114. var t = i2 / divisions;
  16115. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16116. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16117. }
  16118. }
  16119. break;
  16120. case 'b':
  16121. // Cubic Bezier Curve
  16122. cpx = outline[ i++ ] * scaleX + offset;
  16123. cpy = outline[ i++ ] * scaleY;
  16124. cpx1 = outline[ i++ ] * scaleX + offset;
  16125. cpy1 = outline[ i++ ] * -scaleY;
  16126. cpx2 = outline[ i++ ] * scaleX + offset;
  16127. cpy2 = outline[ i++ ] * -scaleY;
  16128. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16129. laste = pts[ pts.length - 1 ];
  16130. if ( laste ) {
  16131. cpx0 = laste.x;
  16132. cpy0 = laste.y;
  16133. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16134. var t = i2 / divisions;
  16135. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16136. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16137. }
  16138. }
  16139. break;
  16140. }
  16141. }
  16142. }
  16143. return { offset: glyph.ha*scale, path:path};
  16144. }
  16145. };
  16146. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16147. // Parameters
  16148. parameters = parameters || {};
  16149. var size = parameters.size !== undefined ? parameters.size : 100;
  16150. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16151. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16152. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16153. var style = parameters.style !== undefined ? parameters.style : "normal";
  16154. THREE.FontUtils.size = size;
  16155. THREE.FontUtils.divisions = curveSegments;
  16156. THREE.FontUtils.face = font;
  16157. THREE.FontUtils.weight = weight;
  16158. THREE.FontUtils.style = style;
  16159. // Get a Font data json object
  16160. var data = THREE.FontUtils.drawText( text );
  16161. var paths = data.paths;
  16162. var shapes = [];
  16163. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16164. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16165. }
  16166. return shapes;
  16167. };
  16168. /**
  16169. * This code is a quick port of code written in C++ which was submitted to
  16170. * flipcode.com by John W. Ratcliff // July 22, 2000
  16171. * See original code and more information here:
  16172. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16173. *
  16174. * ported to actionscript by Zevan Rosser
  16175. * www.actionsnippet.com
  16176. *
  16177. * ported to javascript by Joshua Koo
  16178. * http://www.lab4games.net/zz85/blog
  16179. *
  16180. */
  16181. ( function( namespace ) {
  16182. var EPSILON = 0.0000000001;
  16183. // takes in an contour array and returns
  16184. var process = function( contour, indices ) {
  16185. var n = contour.length;
  16186. if ( n < 3 ) return null;
  16187. var result = [],
  16188. verts = [],
  16189. vertIndices = [];
  16190. /* we want a counter-clockwise polygon in verts */
  16191. var u, v, w;
  16192. if ( area( contour ) > 0.0 ) {
  16193. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16194. } else {
  16195. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16196. }
  16197. var nv = n;
  16198. /* remove nv - 2 vertices, creating 1 triangle every time */
  16199. var count = 2 * nv; /* error detection */
  16200. for( v = nv - 1; nv > 2; ) {
  16201. /* if we loop, it is probably a non-simple polygon */
  16202. if ( ( count-- ) <= 0 ) {
  16203. //** Triangulate: ERROR - probable bad polygon!
  16204. //throw ( "Warning, unable to triangulate polygon!" );
  16205. //return null;
  16206. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16207. console.log( "Warning, unable to triangulate polygon!" );
  16208. if ( indices ) return vertIndices;
  16209. return result;
  16210. }
  16211. /* three consecutive vertices in current polygon, <u,v,w> */
  16212. u = v; if ( nv <= u ) u = 0; /* previous */
  16213. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16214. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16215. if ( snip( contour, u, v, w, nv, verts ) ) {
  16216. var a, b, c, s, t;
  16217. /* true names of the vertices */
  16218. a = verts[ u ];
  16219. b = verts[ v ];
  16220. c = verts[ w ];
  16221. /* output Triangle */
  16222. result.push( [ contour[ a ],
  16223. contour[ b ],
  16224. contour[ c ] ] );
  16225. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16226. /* remove v from the remaining polygon */
  16227. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16228. verts[ s ] = verts[ t ];
  16229. }
  16230. nv--;
  16231. /* reset error detection counter */
  16232. count = 2 * nv;
  16233. }
  16234. }
  16235. if ( indices ) return vertIndices;
  16236. return result;
  16237. };
  16238. // calculate area of the contour polygon
  16239. var area = function ( contour ) {
  16240. var n = contour.length;
  16241. var a = 0.0;
  16242. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16243. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16244. }
  16245. return a * 0.5;
  16246. };
  16247. var snip = function ( contour, u, v, w, n, verts ) {
  16248. var p;
  16249. var ax, ay, bx, by;
  16250. var cx, cy, px, py;
  16251. ax = contour[ verts[ u ] ].x;
  16252. ay = contour[ verts[ u ] ].y;
  16253. bx = contour[ verts[ v ] ].x;
  16254. by = contour[ verts[ v ] ].y;
  16255. cx = contour[ verts[ w ] ].x;
  16256. cy = contour[ verts[ w ] ].y;
  16257. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16258. var aX, aY, bX, bY, cX, cY;
  16259. var apx, apy, bpx, bpy, cpx, cpy;
  16260. var cCROSSap, bCROSScp, aCROSSbp;
  16261. aX = cx - bx; aY = cy - by;
  16262. bX = ax - cx; bY = ay - cy;
  16263. cX = bx - ax; cY = by - ay;
  16264. for ( p = 0; p < n; p++ ) {
  16265. if( (p === u) || (p === v) || (p === w) ) continue;
  16266. px = contour[ verts[ p ] ].x
  16267. py = contour[ verts[ p ] ].y
  16268. apx = px - ax; apy = py - ay;
  16269. bpx = px - bx; bpy = py - by;
  16270. cpx = px - cx; cpy = py - cy;
  16271. // see if p is inside triangle abc
  16272. aCROSSbp = aX*bpy - aY*bpx;
  16273. cCROSSap = cX*apy - cY*apx;
  16274. bCROSScp = bX*cpy - bY*cpx;
  16275. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16276. }
  16277. return true;
  16278. };
  16279. namespace.Triangulate = process;
  16280. namespace.Triangulate.area = area;
  16281. return namespace;
  16282. })(THREE.FontUtils);
  16283. // To use the typeface.js face files, hook up the API
  16284. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16285. * @author zz85 / http://www.lab4games.net/zz85/blog
  16286. * Extensible curve object
  16287. *
  16288. * Some common of Curve methods
  16289. * .getPoint(t), getTangent(t)
  16290. * .getPointAt(u), getTagentAt(u)
  16291. * .getPoints(), .getSpacedPoints()
  16292. * .getLength()
  16293. * .updateArcLengths()
  16294. *
  16295. * This file contains following classes:
  16296. *
  16297. * -- 2d classes --
  16298. * THREE.Curve
  16299. * THREE.LineCurve
  16300. * THREE.QuadraticBezierCurve
  16301. * THREE.CubicBezierCurve
  16302. * THREE.SplineCurve
  16303. * THREE.ArcCurve
  16304. * THREE.EllipseCurve
  16305. *
  16306. * -- 3d classes --
  16307. * THREE.LineCurve3
  16308. * THREE.QuadraticBezierCurve3
  16309. * THREE.CubicBezierCurve3
  16310. * THREE.SplineCurve3
  16311. * THREE.ClosedSplineCurve3
  16312. *
  16313. * A series of curves can be represented as a THREE.CurvePath
  16314. *
  16315. **/
  16316. /**************************************************************
  16317. * Abstract Curve base class
  16318. **************************************************************/
  16319. THREE.Curve = function () {
  16320. };
  16321. // Virtual base class method to overwrite and implement in subclasses
  16322. // - t [0 .. 1]
  16323. THREE.Curve.prototype.getPoint = function ( t ) {
  16324. console.log( "Warning, getPoint() not implemented!" );
  16325. return null;
  16326. };
  16327. // Get point at relative position in curve according to arc length
  16328. // - u [0 .. 1]
  16329. THREE.Curve.prototype.getPointAt = function ( u ) {
  16330. var t = this.getUtoTmapping( u );
  16331. return this.getPoint( t );
  16332. };
  16333. // Get sequence of points using getPoint( t )
  16334. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16335. if ( !divisions ) divisions = 5;
  16336. var d, pts = [];
  16337. for ( d = 0; d <= divisions; d ++ ) {
  16338. pts.push( this.getPoint( d / divisions ) );
  16339. }
  16340. return pts;
  16341. };
  16342. // Get sequence of points using getPointAt( u )
  16343. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16344. if ( !divisions ) divisions = 5;
  16345. var d, pts = [];
  16346. for ( d = 0; d <= divisions; d ++ ) {
  16347. pts.push( this.getPointAt( d / divisions ) );
  16348. }
  16349. return pts;
  16350. };
  16351. // Get total curve arc length
  16352. THREE.Curve.prototype.getLength = function () {
  16353. var lengths = this.getLengths();
  16354. return lengths[ lengths.length - 1 ];
  16355. };
  16356. // Get list of cumulative segment lengths
  16357. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16358. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16359. if ( this.cacheArcLengths
  16360. && ( this.cacheArcLengths.length == divisions + 1 )
  16361. && !this.needsUpdate) {
  16362. //console.log( "cached", this.cacheArcLengths );
  16363. return this.cacheArcLengths;
  16364. }
  16365. this.needsUpdate = false;
  16366. var cache = [];
  16367. var current, last = this.getPoint( 0 );
  16368. var p, sum = 0;
  16369. cache.push( 0 );
  16370. for ( p = 1; p <= divisions; p ++ ) {
  16371. current = this.getPoint ( p / divisions );
  16372. sum += current.distanceTo( last );
  16373. cache.push( sum );
  16374. last = current;
  16375. }
  16376. this.cacheArcLengths = cache;
  16377. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16378. };
  16379. THREE.Curve.prototype.updateArcLengths = function() {
  16380. this.needsUpdate = true;
  16381. this.getLengths();
  16382. };
  16383. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16384. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16385. var arcLengths = this.getLengths();
  16386. var i = 0, il = arcLengths.length;
  16387. var targetArcLength; // The targeted u distance value to get
  16388. if ( distance ) {
  16389. targetArcLength = distance;
  16390. } else {
  16391. targetArcLength = u * arcLengths[ il - 1 ];
  16392. }
  16393. //var time = Date.now();
  16394. // binary search for the index with largest value smaller than target u distance
  16395. var low = 0, high = il - 1, comparison;
  16396. while ( low <= high ) {
  16397. 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
  16398. comparison = arcLengths[ i ] - targetArcLength;
  16399. if ( comparison < 0 ) {
  16400. low = i + 1;
  16401. continue;
  16402. } else if ( comparison > 0 ) {
  16403. high = i - 1;
  16404. continue;
  16405. } else {
  16406. high = i;
  16407. break;
  16408. // DONE
  16409. }
  16410. }
  16411. i = high;
  16412. //console.log('b' , i, low, high, Date.now()- time);
  16413. if ( arcLengths[ i ] == targetArcLength ) {
  16414. var t = i / ( il - 1 );
  16415. return t;
  16416. }
  16417. // we could get finer grain at lengths, or use simple interpolatation between two points
  16418. var lengthBefore = arcLengths[ i ];
  16419. var lengthAfter = arcLengths[ i + 1 ];
  16420. var segmentLength = lengthAfter - lengthBefore;
  16421. // determine where we are between the 'before' and 'after' points
  16422. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16423. // add that fractional amount to t
  16424. var t = ( i + segmentFraction ) / ( il -1 );
  16425. return t;
  16426. };
  16427. // Returns a unit vector tangent at t
  16428. // In case any sub curve does not implement its tangent derivation,
  16429. // 2 points a small delta apart will be used to find its gradient
  16430. // which seems to give a reasonable approximation
  16431. THREE.Curve.prototype.getTangent = function( t ) {
  16432. var delta = 0.0001;
  16433. var t1 = t - delta;
  16434. var t2 = t + delta;
  16435. // Capping in case of danger
  16436. if ( t1 < 0 ) t1 = 0;
  16437. if ( t2 > 1 ) t2 = 1;
  16438. var pt1 = this.getPoint( t1 );
  16439. var pt2 = this.getPoint( t2 );
  16440. var vec = pt2.clone().sub(pt1);
  16441. return vec.normalize();
  16442. };
  16443. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16444. var t = this.getUtoTmapping( u );
  16445. return this.getTangent( t );
  16446. };
  16447. /**************************************************************
  16448. * Line
  16449. **************************************************************/
  16450. THREE.LineCurve = function ( v1, v2 ) {
  16451. this.v1 = v1;
  16452. this.v2 = v2;
  16453. };
  16454. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16455. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16456. var point = this.v2.clone().sub(this.v1);
  16457. point.multiplyScalar( t ).add( this.v1 );
  16458. return point;
  16459. };
  16460. // Line curve is linear, so we can overwrite default getPointAt
  16461. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16462. return this.getPoint( u );
  16463. };
  16464. THREE.LineCurve.prototype.getTangent = function( t ) {
  16465. var tangent = this.v2.clone().sub(this.v1);
  16466. return tangent.normalize();
  16467. };
  16468. /**************************************************************
  16469. * Quadratic Bezier curve
  16470. **************************************************************/
  16471. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16472. this.v0 = v0;
  16473. this.v1 = v1;
  16474. this.v2 = v2;
  16475. };
  16476. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16477. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16478. var tx, ty;
  16479. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16480. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16481. return new THREE.Vector2( tx, ty );
  16482. };
  16483. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16484. var tx, ty;
  16485. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16486. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16487. // returns unit vector
  16488. var tangent = new THREE.Vector2( tx, ty );
  16489. tangent.normalize();
  16490. return tangent;
  16491. };
  16492. /**************************************************************
  16493. * Cubic Bezier curve
  16494. **************************************************************/
  16495. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16496. this.v0 = v0;
  16497. this.v1 = v1;
  16498. this.v2 = v2;
  16499. this.v3 = v3;
  16500. };
  16501. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16502. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16503. var tx, ty;
  16504. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16505. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16506. return new THREE.Vector2( tx, ty );
  16507. };
  16508. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16509. var tx, ty;
  16510. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16511. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16512. var tangent = new THREE.Vector2( tx, ty );
  16513. tangent.normalize();
  16514. return tangent;
  16515. };
  16516. /**************************************************************
  16517. * Spline curve
  16518. **************************************************************/
  16519. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16520. this.points = (points == undefined) ? [] : points;
  16521. };
  16522. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16523. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16524. var v = new THREE.Vector2();
  16525. var c = [];
  16526. var points = this.points, point, intPoint, weight;
  16527. point = ( points.length - 1 ) * t;
  16528. intPoint = Math.floor( point );
  16529. weight = point - intPoint;
  16530. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16531. c[ 1 ] = intPoint;
  16532. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16533. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16534. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16535. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16536. return v;
  16537. };
  16538. /**************************************************************
  16539. * Ellipse curve
  16540. **************************************************************/
  16541. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16542. aStartAngle, aEndAngle,
  16543. aClockwise ) {
  16544. this.aX = aX;
  16545. this.aY = aY;
  16546. this.xRadius = xRadius;
  16547. this.yRadius = yRadius;
  16548. this.aStartAngle = aStartAngle;
  16549. this.aEndAngle = aEndAngle;
  16550. this.aClockwise = aClockwise;
  16551. };
  16552. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16553. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16554. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16555. if ( !this.aClockwise ) {
  16556. t = 1 - t;
  16557. }
  16558. var angle = this.aStartAngle + t * deltaAngle;
  16559. var tx = this.aX + this.xRadius * Math.cos( angle );
  16560. var ty = this.aY + this.yRadius * Math.sin( angle );
  16561. return new THREE.Vector2( tx, ty );
  16562. };
  16563. /**************************************************************
  16564. * Arc curve
  16565. **************************************************************/
  16566. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16567. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16568. };
  16569. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16570. /**************************************************************
  16571. * Utils
  16572. **************************************************************/
  16573. THREE.Curve.Utils = {
  16574. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16575. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16576. },
  16577. // Puay Bing, thanks for helping with this derivative!
  16578. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16579. return -3 * p0 * (1 - t) * (1 - t) +
  16580. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16581. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16582. 3 * t * t * p3;
  16583. },
  16584. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16585. // To check if my formulas are correct
  16586. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16587. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16588. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16589. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16590. return h00 + h10 + h01 + h11;
  16591. },
  16592. // Catmull-Rom
  16593. interpolate: function( p0, p1, p2, p3, t ) {
  16594. var v0 = ( p2 - p0 ) * 0.5;
  16595. var v1 = ( p3 - p1 ) * 0.5;
  16596. var t2 = t * t;
  16597. var t3 = t * t2;
  16598. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16599. }
  16600. };
  16601. // TODO: Transformation for Curves?
  16602. /**************************************************************
  16603. * 3D Curves
  16604. **************************************************************/
  16605. // A Factory method for creating new curve subclasses
  16606. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16607. constructor.prototype = Object.create( THREE.Curve.prototype );
  16608. constructor.prototype.getPoint = getPointFunc;
  16609. return constructor;
  16610. };
  16611. /**************************************************************
  16612. * Line3D
  16613. **************************************************************/
  16614. THREE.LineCurve3 = THREE.Curve.create(
  16615. function ( v1, v2 ) {
  16616. this.v1 = v1;
  16617. this.v2 = v2;
  16618. },
  16619. function ( t ) {
  16620. var r = new THREE.Vector3();
  16621. r.subVectors( this.v2, this.v1 ); // diff
  16622. r.multiplyScalar( t );
  16623. r.add( this.v1 );
  16624. return r;
  16625. }
  16626. );
  16627. /**************************************************************
  16628. * Quadratic Bezier 3D curve
  16629. **************************************************************/
  16630. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16631. function ( v0, v1, v2 ) {
  16632. this.v0 = v0;
  16633. this.v1 = v1;
  16634. this.v2 = v2;
  16635. },
  16636. function ( t ) {
  16637. var tx, ty, tz;
  16638. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16639. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16640. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16641. return new THREE.Vector3( tx, ty, tz );
  16642. }
  16643. );
  16644. /**************************************************************
  16645. * Cubic Bezier 3D curve
  16646. **************************************************************/
  16647. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16648. function ( v0, v1, v2, v3 ) {
  16649. this.v0 = v0;
  16650. this.v1 = v1;
  16651. this.v2 = v2;
  16652. this.v3 = v3;
  16653. },
  16654. function ( t ) {
  16655. var tx, ty, tz;
  16656. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16657. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16658. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16659. return new THREE.Vector3( tx, ty, tz );
  16660. }
  16661. );
  16662. /**************************************************************
  16663. * Spline 3D curve
  16664. **************************************************************/
  16665. THREE.SplineCurve3 = THREE.Curve.create(
  16666. function ( points /* array of Vector3 */) {
  16667. this.points = (points == undefined) ? [] : points;
  16668. },
  16669. function ( t ) {
  16670. var v = new THREE.Vector3();
  16671. var c = [];
  16672. var points = this.points, point, intPoint, weight;
  16673. point = ( points.length - 1 ) * t;
  16674. intPoint = Math.floor( point );
  16675. weight = point - intPoint;
  16676. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16677. c[ 1 ] = intPoint;
  16678. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16679. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16680. var pt0 = points[ c[0] ],
  16681. pt1 = points[ c[1] ],
  16682. pt2 = points[ c[2] ],
  16683. pt3 = points[ c[3] ];
  16684. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16685. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16686. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16687. return v;
  16688. }
  16689. );
  16690. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16691. // var v = new THREE.Vector3();
  16692. // var c = [];
  16693. // var points = this.points, point, intPoint, weight;
  16694. // point = ( points.length - 1 ) * t;
  16695. // intPoint = Math.floor( point );
  16696. // weight = point - intPoint;
  16697. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16698. // c[ 1 ] = intPoint;
  16699. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16700. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16701. // var pt0 = points[ c[0] ],
  16702. // pt1 = points[ c[1] ],
  16703. // pt2 = points[ c[2] ],
  16704. // pt3 = points[ c[3] ];
  16705. // // t = weight;
  16706. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16707. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16708. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16709. // return v;
  16710. // }
  16711. /**************************************************************
  16712. * Closed Spline 3D curve
  16713. **************************************************************/
  16714. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16715. function ( points /* array of Vector3 */) {
  16716. this.points = (points == undefined) ? [] : points;
  16717. },
  16718. function ( t ) {
  16719. var v = new THREE.Vector3();
  16720. var c = [];
  16721. var points = this.points, point, intPoint, weight;
  16722. point = ( points.length - 0 ) * t;
  16723. // This needs to be from 0-length +1
  16724. intPoint = Math.floor( point );
  16725. weight = point - intPoint;
  16726. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16727. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16728. c[ 1 ] = ( intPoint ) % points.length;
  16729. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16730. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16731. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16732. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16733. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16734. return v;
  16735. }
  16736. );
  16737. /**
  16738. * @author zz85 / http://www.lab4games.net/zz85/blog
  16739. *
  16740. **/
  16741. /**************************************************************
  16742. * Curved Path - a curve path is simply a array of connected
  16743. * curves, but retains the api of a curve
  16744. **************************************************************/
  16745. THREE.CurvePath = function () {
  16746. this.curves = [];
  16747. this.bends = [];
  16748. this.autoClose = false; // Automatically closes the path
  16749. };
  16750. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16751. THREE.CurvePath.prototype.add = function ( curve ) {
  16752. this.curves.push( curve );
  16753. };
  16754. THREE.CurvePath.prototype.checkConnection = function() {
  16755. // TODO
  16756. // If the ending of curve is not connected to the starting
  16757. // or the next curve, then, this is not a real path
  16758. };
  16759. THREE.CurvePath.prototype.closePath = function() {
  16760. // TODO Test
  16761. // and verify for vector3 (needs to implement equals)
  16762. // Add a line curve if start and end of lines are not connected
  16763. var startPoint = this.curves[0].getPoint(0);
  16764. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16765. if (!startPoint.equals(endPoint)) {
  16766. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16767. }
  16768. };
  16769. // To get accurate point with reference to
  16770. // entire path distance at time t,
  16771. // following has to be done:
  16772. // 1. Length of each sub path have to be known
  16773. // 2. Locate and identify type of curve
  16774. // 3. Get t for the curve
  16775. // 4. Return curve.getPointAt(t')
  16776. THREE.CurvePath.prototype.getPoint = function( t ) {
  16777. var d = t * this.getLength();
  16778. var curveLengths = this.getCurveLengths();
  16779. var i = 0, diff, curve;
  16780. // To think about boundaries points.
  16781. while ( i < curveLengths.length ) {
  16782. if ( curveLengths[ i ] >= d ) {
  16783. diff = curveLengths[ i ] - d;
  16784. curve = this.curves[ i ];
  16785. var u = 1 - diff / curve.getLength();
  16786. return curve.getPointAt( u );
  16787. break;
  16788. }
  16789. i ++;
  16790. }
  16791. return null;
  16792. // loop where sum != 0, sum > d , sum+1 <d
  16793. };
  16794. /*
  16795. THREE.CurvePath.prototype.getTangent = function( t ) {
  16796. };*/
  16797. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16798. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16799. // getPoint() depends on getLength
  16800. THREE.CurvePath.prototype.getLength = function() {
  16801. var lens = this.getCurveLengths();
  16802. return lens[ lens.length - 1 ];
  16803. };
  16804. // Compute lengths and cache them
  16805. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16806. THREE.CurvePath.prototype.getCurveLengths = function() {
  16807. // We use cache values if curves and cache array are same length
  16808. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16809. return this.cacheLengths;
  16810. };
  16811. // Get length of subsurve
  16812. // Push sums into cached array
  16813. var lengths = [], sums = 0;
  16814. var i, il = this.curves.length;
  16815. for ( i = 0; i < il; i ++ ) {
  16816. sums += this.curves[ i ].getLength();
  16817. lengths.push( sums );
  16818. }
  16819. this.cacheLengths = lengths;
  16820. return lengths;
  16821. };
  16822. // Returns min and max coordinates, as well as centroid
  16823. THREE.CurvePath.prototype.getBoundingBox = function () {
  16824. var points = this.getPoints();
  16825. var maxX, maxY, maxZ;
  16826. var minX, minY, minZ;
  16827. maxX = maxY = Number.NEGATIVE_INFINITY;
  16828. minX = minY = Number.POSITIVE_INFINITY;
  16829. var p, i, il, sum;
  16830. var v3 = points[0] instanceof THREE.Vector3;
  16831. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16832. for ( i = 0, il = points.length; i < il; i ++ ) {
  16833. p = points[ i ];
  16834. if ( p.x > maxX ) maxX = p.x;
  16835. else if ( p.x < minX ) minX = p.x;
  16836. if ( p.y > maxY ) maxY = p.y;
  16837. else if ( p.y < minY ) minY = p.y;
  16838. if ( v3 ) {
  16839. if ( p.z > maxZ ) maxZ = p.z;
  16840. else if ( p.z < minZ ) minZ = p.z;
  16841. }
  16842. sum.add( p );
  16843. }
  16844. var ret = {
  16845. minX: minX,
  16846. minY: minY,
  16847. maxX: maxX,
  16848. maxY: maxY,
  16849. centroid: sum.divideScalar( il )
  16850. };
  16851. if ( v3 ) {
  16852. ret.maxZ = maxZ;
  16853. ret.minZ = minZ;
  16854. }
  16855. return ret;
  16856. };
  16857. /**************************************************************
  16858. * Create Geometries Helpers
  16859. **************************************************************/
  16860. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16861. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16862. var pts = this.getPoints( divisions, true );
  16863. return this.createGeometry( pts );
  16864. };
  16865. // Generate geometry from equidistance sampling along the path
  16866. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16867. var pts = this.getSpacedPoints( divisions, true );
  16868. return this.createGeometry( pts );
  16869. };
  16870. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16871. var geometry = new THREE.Geometry();
  16872. for ( var i = 0; i < points.length; i ++ ) {
  16873. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16874. }
  16875. return geometry;
  16876. };
  16877. /**************************************************************
  16878. * Bend / Wrap Helper Methods
  16879. **************************************************************/
  16880. // Wrap path / Bend modifiers?
  16881. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16882. this.bends.push( bendpath );
  16883. };
  16884. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16885. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16886. var i, il;
  16887. if ( !bends ) {
  16888. bends = this.bends;
  16889. }
  16890. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16891. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16892. }
  16893. return oldPts;
  16894. };
  16895. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16896. var oldPts = this.getSpacedPoints( segments );
  16897. var i, il;
  16898. if ( !bends ) {
  16899. bends = this.bends;
  16900. }
  16901. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16902. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16903. }
  16904. return oldPts;
  16905. };
  16906. // This returns getPoints() bend/wrapped around the contour of a path.
  16907. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16908. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16909. var bounds = this.getBoundingBox();
  16910. var i, il, p, oldX, oldY, xNorm;
  16911. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16912. p = oldPts[ i ];
  16913. oldX = p.x;
  16914. oldY = p.y;
  16915. xNorm = oldX / bounds.maxX;
  16916. // If using actual distance, for length > path, requires line extrusions
  16917. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16918. xNorm = path.getUtoTmapping( xNorm, oldX );
  16919. // check for out of bounds?
  16920. var pathPt = path.getPoint( xNorm );
  16921. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16922. p.x = pathPt.x + normal.x;
  16923. p.y = pathPt.y + normal.y;
  16924. }
  16925. return oldPts;
  16926. };
  16927. /**
  16928. * @author alteredq / http://alteredqualia.com/
  16929. */
  16930. THREE.Gyroscope = function () {
  16931. THREE.Object3D.call( this );
  16932. };
  16933. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16934. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16935. this.matrixAutoUpdate && this.updateMatrix();
  16936. // update matrixWorld
  16937. if ( this.matrixWorldNeedsUpdate || force ) {
  16938. if ( this.parent ) {
  16939. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16940. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16941. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16942. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16943. } else {
  16944. this.matrixWorld.copy( this.matrix );
  16945. }
  16946. this.matrixWorldNeedsUpdate = false;
  16947. force = true;
  16948. }
  16949. // update children
  16950. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16951. this.children[ i ].updateMatrixWorld( force );
  16952. }
  16953. };
  16954. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16955. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16956. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16957. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16958. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16959. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16960. /**
  16961. * @author zz85 / http://www.lab4games.net/zz85/blog
  16962. * Creates free form 2d path using series of points, lines or curves.
  16963. *
  16964. **/
  16965. THREE.Path = function ( points ) {
  16966. THREE.CurvePath.call(this);
  16967. this.actions = [];
  16968. if ( points ) {
  16969. this.fromPoints( points );
  16970. }
  16971. };
  16972. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16973. THREE.PathActions = {
  16974. MOVE_TO: 'moveTo',
  16975. LINE_TO: 'lineTo',
  16976. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16977. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16978. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16979. ARC: 'arc', // Circle
  16980. ELLIPSE: 'ellipse'
  16981. };
  16982. // TODO Clean up PATH API
  16983. // Create path using straight lines to connect all points
  16984. // - vectors: array of Vector2
  16985. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16986. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16987. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16988. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16989. };
  16990. };
  16991. // startPath() endPath()?
  16992. THREE.Path.prototype.moveTo = function ( x, y ) {
  16993. var args = Array.prototype.slice.call( arguments );
  16994. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16995. };
  16996. THREE.Path.prototype.lineTo = function ( x, y ) {
  16997. var args = Array.prototype.slice.call( arguments );
  16998. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16999. var x0 = lastargs[ lastargs.length - 2 ];
  17000. var y0 = lastargs[ lastargs.length - 1 ];
  17001. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17002. this.curves.push( curve );
  17003. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17004. };
  17005. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17006. var args = Array.prototype.slice.call( arguments );
  17007. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17008. var x0 = lastargs[ lastargs.length - 2 ];
  17009. var y0 = lastargs[ lastargs.length - 1 ];
  17010. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17011. new THREE.Vector2( aCPx, aCPy ),
  17012. new THREE.Vector2( aX, aY ) );
  17013. this.curves.push( curve );
  17014. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17015. };
  17016. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17017. aCP2x, aCP2y,
  17018. aX, aY ) {
  17019. var args = Array.prototype.slice.call( arguments );
  17020. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17021. var x0 = lastargs[ lastargs.length - 2 ];
  17022. var y0 = lastargs[ lastargs.length - 1 ];
  17023. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17024. new THREE.Vector2( aCP1x, aCP1y ),
  17025. new THREE.Vector2( aCP2x, aCP2y ),
  17026. new THREE.Vector2( aX, aY ) );
  17027. this.curves.push( curve );
  17028. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17029. };
  17030. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17031. var args = Array.prototype.slice.call( arguments );
  17032. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17033. var x0 = lastargs[ lastargs.length - 2 ];
  17034. var y0 = lastargs[ lastargs.length - 1 ];
  17035. //---
  17036. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17037. Array.prototype.push.apply( npts, pts );
  17038. var curve = new THREE.SplineCurve( npts );
  17039. this.curves.push( curve );
  17040. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17041. };
  17042. // FUTURE: Change the API or follow canvas API?
  17043. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17044. aStartAngle, aEndAngle, aClockwise ) {
  17045. var lastargs = this.actions[ this.actions.length - 1].args;
  17046. var x0 = lastargs[ lastargs.length - 2 ];
  17047. var y0 = lastargs[ lastargs.length - 1 ];
  17048. this.absarc(aX + x0, aY + y0, aRadius,
  17049. aStartAngle, aEndAngle, aClockwise );
  17050. };
  17051. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17052. aStartAngle, aEndAngle, aClockwise ) {
  17053. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17054. };
  17055. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17056. aStartAngle, aEndAngle, aClockwise ) {
  17057. var lastargs = this.actions[ this.actions.length - 1].args;
  17058. var x0 = lastargs[ lastargs.length - 2 ];
  17059. var y0 = lastargs[ lastargs.length - 1 ];
  17060. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17061. aStartAngle, aEndAngle, aClockwise );
  17062. };
  17063. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17064. aStartAngle, aEndAngle, aClockwise ) {
  17065. var args = Array.prototype.slice.call( arguments );
  17066. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17067. aStartAngle, aEndAngle, aClockwise );
  17068. this.curves.push( curve );
  17069. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17070. args.push(lastPoint.x);
  17071. args.push(lastPoint.y);
  17072. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17073. };
  17074. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17075. if ( ! divisions ) divisions = 40;
  17076. var points = [];
  17077. for ( var i = 0; i < divisions; i ++ ) {
  17078. points.push( this.getPoint( i / divisions ) );
  17079. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17080. }
  17081. // if ( closedPath ) {
  17082. //
  17083. // points.push( points[ 0 ] );
  17084. //
  17085. // }
  17086. return points;
  17087. };
  17088. /* Return an array of vectors based on contour of the path */
  17089. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17090. if (this.useSpacedPoints) {
  17091. console.log('tata');
  17092. return this.getSpacedPoints( divisions, closedPath );
  17093. }
  17094. divisions = divisions || 12;
  17095. var points = [];
  17096. var i, il, item, action, args;
  17097. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17098. laste, j,
  17099. t, tx, ty;
  17100. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17101. item = this.actions[ i ];
  17102. action = item.action;
  17103. args = item.args;
  17104. switch( action ) {
  17105. case THREE.PathActions.MOVE_TO:
  17106. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17107. break;
  17108. case THREE.PathActions.LINE_TO:
  17109. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17110. break;
  17111. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17112. cpx = args[ 2 ];
  17113. cpy = args[ 3 ];
  17114. cpx1 = args[ 0 ];
  17115. cpy1 = args[ 1 ];
  17116. if ( points.length > 0 ) {
  17117. laste = points[ points.length - 1 ];
  17118. cpx0 = laste.x;
  17119. cpy0 = laste.y;
  17120. } else {
  17121. laste = this.actions[ i - 1 ].args;
  17122. cpx0 = laste[ laste.length - 2 ];
  17123. cpy0 = laste[ laste.length - 1 ];
  17124. }
  17125. for ( j = 1; j <= divisions; j ++ ) {
  17126. t = j / divisions;
  17127. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17128. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17129. points.push( new THREE.Vector2( tx, ty ) );
  17130. }
  17131. break;
  17132. case THREE.PathActions.BEZIER_CURVE_TO:
  17133. cpx = args[ 4 ];
  17134. cpy = args[ 5 ];
  17135. cpx1 = args[ 0 ];
  17136. cpy1 = args[ 1 ];
  17137. cpx2 = args[ 2 ];
  17138. cpy2 = args[ 3 ];
  17139. if ( points.length > 0 ) {
  17140. laste = points[ points.length - 1 ];
  17141. cpx0 = laste.x;
  17142. cpy0 = laste.y;
  17143. } else {
  17144. laste = this.actions[ i - 1 ].args;
  17145. cpx0 = laste[ laste.length - 2 ];
  17146. cpy0 = laste[ laste.length - 1 ];
  17147. }
  17148. for ( j = 1; j <= divisions; j ++ ) {
  17149. t = j / divisions;
  17150. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17151. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17152. points.push( new THREE.Vector2( tx, ty ) );
  17153. }
  17154. break;
  17155. case THREE.PathActions.CSPLINE_THRU:
  17156. laste = this.actions[ i - 1 ].args;
  17157. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17158. var spts = [ last ];
  17159. var n = divisions * args[ 0 ].length;
  17160. spts = spts.concat( args[ 0 ] );
  17161. var spline = new THREE.SplineCurve( spts );
  17162. for ( j = 1; j <= n; j ++ ) {
  17163. points.push( spline.getPointAt( j / n ) ) ;
  17164. }
  17165. break;
  17166. case THREE.PathActions.ARC:
  17167. var aX = args[ 0 ], aY = args[ 1 ],
  17168. aRadius = args[ 2 ],
  17169. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17170. aClockwise = !!args[ 5 ];
  17171. var deltaAngle = aEndAngle - aStartAngle;
  17172. var angle;
  17173. var tdivisions = divisions * 2;
  17174. for ( j = 1; j <= tdivisions; j ++ ) {
  17175. t = j / tdivisions;
  17176. if ( ! aClockwise ) {
  17177. t = 1 - t;
  17178. }
  17179. angle = aStartAngle + t * deltaAngle;
  17180. tx = aX + aRadius * Math.cos( angle );
  17181. ty = aY + aRadius * Math.sin( angle );
  17182. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17183. points.push( new THREE.Vector2( tx, ty ) );
  17184. }
  17185. //console.log(points);
  17186. break;
  17187. case THREE.PathActions.ELLIPSE:
  17188. var aX = args[ 0 ], aY = args[ 1 ],
  17189. xRadius = args[ 2 ],
  17190. yRadius = args[ 3 ],
  17191. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17192. aClockwise = !!args[ 6 ];
  17193. var deltaAngle = aEndAngle - aStartAngle;
  17194. var angle;
  17195. var tdivisions = divisions * 2;
  17196. for ( j = 1; j <= tdivisions; j ++ ) {
  17197. t = j / tdivisions;
  17198. if ( ! aClockwise ) {
  17199. t = 1 - t;
  17200. }
  17201. angle = aStartAngle + t * deltaAngle;
  17202. tx = aX + xRadius * Math.cos( angle );
  17203. ty = aY + yRadius * Math.sin( angle );
  17204. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17205. points.push( new THREE.Vector2( tx, ty ) );
  17206. }
  17207. //console.log(points);
  17208. break;
  17209. } // end switch
  17210. }
  17211. // Normalize to remove the closing point by default.
  17212. var lastPoint = points[ points.length - 1];
  17213. var EPSILON = 0.0000000001;
  17214. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17215. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17216. points.splice( points.length - 1, 1);
  17217. if ( closedPath ) {
  17218. points.push( points[ 0 ] );
  17219. }
  17220. return points;
  17221. };
  17222. // Breaks path into shapes
  17223. THREE.Path.prototype.toShapes = function() {
  17224. var i, il, item, action, args;
  17225. var subPaths = [], lastPath = new THREE.Path();
  17226. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17227. item = this.actions[ i ];
  17228. args = item.args;
  17229. action = item.action;
  17230. if ( action == THREE.PathActions.MOVE_TO ) {
  17231. if ( lastPath.actions.length != 0 ) {
  17232. subPaths.push( lastPath );
  17233. lastPath = new THREE.Path();
  17234. }
  17235. }
  17236. lastPath[ action ].apply( lastPath, args );
  17237. }
  17238. if ( lastPath.actions.length != 0 ) {
  17239. subPaths.push( lastPath );
  17240. }
  17241. // console.log(subPaths);
  17242. if ( subPaths.length == 0 ) return [];
  17243. var tmpPath, tmpShape, shapes = [];
  17244. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17245. // console.log("Holes first", holesFirst);
  17246. if ( subPaths.length == 1) {
  17247. tmpPath = subPaths[0];
  17248. tmpShape = new THREE.Shape();
  17249. tmpShape.actions = tmpPath.actions;
  17250. tmpShape.curves = tmpPath.curves;
  17251. shapes.push( tmpShape );
  17252. return shapes;
  17253. };
  17254. if ( holesFirst ) {
  17255. tmpShape = new THREE.Shape();
  17256. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17257. tmpPath = subPaths[ i ];
  17258. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17259. tmpShape.actions = tmpPath.actions;
  17260. tmpShape.curves = tmpPath.curves;
  17261. shapes.push( tmpShape );
  17262. tmpShape = new THREE.Shape();
  17263. //console.log('cw', i);
  17264. } else {
  17265. tmpShape.holes.push( tmpPath );
  17266. //console.log('ccw', i);
  17267. }
  17268. }
  17269. } else {
  17270. // Shapes first
  17271. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17272. tmpPath = subPaths[ i ];
  17273. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17274. if ( tmpShape ) shapes.push( tmpShape );
  17275. tmpShape = new THREE.Shape();
  17276. tmpShape.actions = tmpPath.actions;
  17277. tmpShape.curves = tmpPath.curves;
  17278. } else {
  17279. tmpShape.holes.push( tmpPath );
  17280. }
  17281. }
  17282. shapes.push( tmpShape );
  17283. }
  17284. //console.log("shape", shapes);
  17285. return shapes;
  17286. };
  17287. /**
  17288. * @author zz85 / http://www.lab4games.net/zz85/blog
  17289. * Defines a 2d shape plane using paths.
  17290. **/
  17291. // STEP 1 Create a path.
  17292. // STEP 2 Turn path into shape.
  17293. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17294. // STEP 3a - Extract points from each shape, turn to vertices
  17295. // STEP 3b - Triangulate each shape, add faces.
  17296. THREE.Shape = function () {
  17297. THREE.Path.apply( this, arguments );
  17298. this.holes = [];
  17299. };
  17300. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17301. // Convenience method to return ExtrudeGeometry
  17302. THREE.Shape.prototype.extrude = function ( options ) {
  17303. var extruded = new THREE.ExtrudeGeometry( this, options );
  17304. return extruded;
  17305. };
  17306. // Convenience method to return ShapeGeometry
  17307. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17308. var geometry = new THREE.ShapeGeometry( this, options );
  17309. return geometry;
  17310. };
  17311. // Get points of holes
  17312. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17313. var i, il = this.holes.length, holesPts = [];
  17314. for ( i = 0; i < il; i ++ ) {
  17315. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17316. }
  17317. return holesPts;
  17318. };
  17319. // Get points of holes (spaced by regular distance)
  17320. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17321. var i, il = this.holes.length, holesPts = [];
  17322. for ( i = 0; i < il; i ++ ) {
  17323. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17324. }
  17325. return holesPts;
  17326. };
  17327. // Get points of shape and holes (keypoints based on segments parameter)
  17328. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17329. return {
  17330. shape: this.getTransformedPoints( divisions ),
  17331. holes: this.getPointsHoles( divisions )
  17332. };
  17333. };
  17334. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17335. if (this.useSpacedPoints) {
  17336. return this.extractAllSpacedPoints(divisions);
  17337. }
  17338. return this.extractAllPoints(divisions);
  17339. };
  17340. //
  17341. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17342. //
  17343. // return {
  17344. //
  17345. // shape: this.transform( bend, divisions ),
  17346. // holes: this.getPointsHoles( divisions, bend )
  17347. //
  17348. // };
  17349. //
  17350. // };
  17351. // Get points of shape and holes (spaced by regular distance)
  17352. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17353. return {
  17354. shape: this.getTransformedSpacedPoints( divisions ),
  17355. holes: this.getSpacedPointsHoles( divisions )
  17356. };
  17357. };
  17358. /**************************************************************
  17359. * Utils
  17360. **************************************************************/
  17361. THREE.Shape.Utils = {
  17362. /*
  17363. contour - array of vector2 for contour
  17364. holes - array of array of vector2
  17365. */
  17366. removeHoles: function ( contour, holes ) {
  17367. var shape = contour.concat(); // work on this shape
  17368. var allpoints = shape.concat();
  17369. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17370. var prevShapeVert, nextShapeVert,
  17371. prevHoleVert, nextHoleVert,
  17372. holeIndex, shapeIndex,
  17373. shapeId, shapeGroup,
  17374. h, h2,
  17375. hole, shortest, d,
  17376. p, pts1, pts2,
  17377. tmpShape1, tmpShape2,
  17378. tmpHole1, tmpHole2,
  17379. verts = [];
  17380. for ( h = 0; h < holes.length; h ++ ) {
  17381. hole = holes[ h ];
  17382. /*
  17383. shapeholes[ h ].concat(); // preserves original
  17384. holes.push( hole );
  17385. */
  17386. Array.prototype.push.apply( allpoints, hole );
  17387. shortest = Number.POSITIVE_INFINITY;
  17388. // Find the shortest pair of pts between shape and hole
  17389. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17390. // Using distanceToSquared() intead of distanceTo() should speed a little
  17391. // since running square roots operations are reduced.
  17392. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17393. pts1 = hole[ h2 ];
  17394. var dist = [];
  17395. for ( p = 0; p < shape.length; p++ ) {
  17396. pts2 = shape[ p ];
  17397. d = pts1.distanceToSquared( pts2 );
  17398. dist.push( d );
  17399. if ( d < shortest ) {
  17400. shortest = d;
  17401. holeIndex = h2;
  17402. shapeIndex = p;
  17403. }
  17404. }
  17405. }
  17406. //console.log("shortest", shortest, dist);
  17407. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17408. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17409. var areaapts = [
  17410. hole[ holeIndex ],
  17411. shape[ shapeIndex ],
  17412. shape[ prevShapeVert ]
  17413. ];
  17414. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17415. var areabpts = [
  17416. hole[ holeIndex ],
  17417. hole[ prevHoleVert ],
  17418. shape[ shapeIndex ]
  17419. ];
  17420. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17421. var shapeOffset = 1;
  17422. var holeOffset = -1;
  17423. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17424. shapeIndex += shapeOffset;
  17425. holeIndex += holeOffset;
  17426. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17427. shapeIndex %= shape.length;
  17428. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17429. holeIndex %= hole.length;
  17430. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17431. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17432. areaapts = [
  17433. hole[ holeIndex ],
  17434. shape[ shapeIndex ],
  17435. shape[ prevShapeVert ]
  17436. ];
  17437. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17438. areabpts = [
  17439. hole[ holeIndex ],
  17440. hole[ prevHoleVert ],
  17441. shape[ shapeIndex ]
  17442. ];
  17443. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17444. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17445. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17446. // In case areas are not correct.
  17447. //console.log("USE THIS");
  17448. shapeIndex = oldShapeIndex;
  17449. holeIndex = oldHoleIndex ;
  17450. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17451. shapeIndex %= shape.length;
  17452. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17453. holeIndex %= hole.length;
  17454. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17455. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17456. } else {
  17457. //console.log("USE THAT ")
  17458. }
  17459. tmpShape1 = shape.slice( 0, shapeIndex );
  17460. tmpShape2 = shape.slice( shapeIndex );
  17461. tmpHole1 = hole.slice( holeIndex );
  17462. tmpHole2 = hole.slice( 0, holeIndex );
  17463. // Should check orders here again?
  17464. var trianglea = [
  17465. hole[ holeIndex ],
  17466. shape[ shapeIndex ],
  17467. shape[ prevShapeVert ]
  17468. ];
  17469. var triangleb = [
  17470. hole[ holeIndex ] ,
  17471. hole[ prevHoleVert ],
  17472. shape[ shapeIndex ]
  17473. ];
  17474. verts.push( trianglea );
  17475. verts.push( triangleb );
  17476. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17477. }
  17478. return {
  17479. shape:shape, /* shape with no holes */
  17480. isolatedPts: verts, /* isolated faces */
  17481. allpoints: allpoints
  17482. }
  17483. },
  17484. triangulateShape: function ( contour, holes ) {
  17485. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17486. var shape = shapeWithoutHoles.shape,
  17487. allpoints = shapeWithoutHoles.allpoints,
  17488. isolatedPts = shapeWithoutHoles.isolatedPts;
  17489. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17490. // 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.
  17491. //console.log( "triangles",triangles, triangles.length );
  17492. //console.log( "allpoints",allpoints, allpoints.length );
  17493. var i, il, f, face,
  17494. key, index,
  17495. allPointsMap = {},
  17496. isolatedPointsMap = {};
  17497. // prepare all points map
  17498. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17499. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17500. if ( allPointsMap[ key ] !== undefined ) {
  17501. console.log( "Duplicate point", key );
  17502. }
  17503. allPointsMap[ key ] = i;
  17504. }
  17505. // check all face vertices against all points map
  17506. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17507. face = triangles[ i ];
  17508. for ( f = 0; f < 3; f ++ ) {
  17509. key = face[ f ].x + ":" + face[ f ].y;
  17510. index = allPointsMap[ key ];
  17511. if ( index !== undefined ) {
  17512. face[ f ] = index;
  17513. }
  17514. }
  17515. }
  17516. // check isolated points vertices against all points map
  17517. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17518. face = isolatedPts[ i ];
  17519. for ( f = 0; f < 3; f ++ ) {
  17520. key = face[ f ].x + ":" + face[ f ].y;
  17521. index = allPointsMap[ key ];
  17522. if ( index !== undefined ) {
  17523. face[ f ] = index;
  17524. }
  17525. }
  17526. }
  17527. return triangles.concat( isolatedPts );
  17528. }, // end triangulate shapes
  17529. /*
  17530. triangulate2 : function( pts, holes ) {
  17531. // For use with Poly2Tri.js
  17532. var allpts = pts.concat();
  17533. var shape = [];
  17534. for (var p in pts) {
  17535. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17536. }
  17537. var swctx = new js.poly2tri.SweepContext(shape);
  17538. for (var h in holes) {
  17539. var aHole = holes[h];
  17540. var newHole = []
  17541. for (i in aHole) {
  17542. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17543. allpts.push(aHole[i]);
  17544. }
  17545. swctx.AddHole(newHole);
  17546. }
  17547. var find;
  17548. var findIndexForPt = function (pt) {
  17549. find = new THREE.Vector2(pt.x, pt.y);
  17550. var p;
  17551. for (p=0, pl = allpts.length; p<pl; p++) {
  17552. if (allpts[p].equals(find)) return p;
  17553. }
  17554. return -1;
  17555. };
  17556. // triangulate
  17557. js.poly2tri.sweep.Triangulate(swctx);
  17558. var triangles = swctx.GetTriangles();
  17559. var tr ;
  17560. var facesPts = [];
  17561. for (var t in triangles) {
  17562. tr = triangles[t];
  17563. facesPts.push([
  17564. findIndexForPt(tr.GetPoint(0)),
  17565. findIndexForPt(tr.GetPoint(1)),
  17566. findIndexForPt(tr.GetPoint(2))
  17567. ]);
  17568. }
  17569. // console.log(facesPts);
  17570. // console.log("triangles", triangles.length, triangles);
  17571. // Returns array of faces with 3 element each
  17572. return facesPts;
  17573. },
  17574. */
  17575. isClockWise: function ( pts ) {
  17576. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17577. },
  17578. // Bezier Curves formulas obtained from
  17579. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17580. // Quad Bezier Functions
  17581. b2p0: function ( t, p ) {
  17582. var k = 1 - t;
  17583. return k * k * p;
  17584. },
  17585. b2p1: function ( t, p ) {
  17586. return 2 * ( 1 - t ) * t * p;
  17587. },
  17588. b2p2: function ( t, p ) {
  17589. return t * t * p;
  17590. },
  17591. b2: function ( t, p0, p1, p2 ) {
  17592. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17593. },
  17594. // Cubic Bezier Functions
  17595. b3p0: function ( t, p ) {
  17596. var k = 1 - t;
  17597. return k * k * k * p;
  17598. },
  17599. b3p1: function ( t, p ) {
  17600. var k = 1 - t;
  17601. return 3 * k * k * t * p;
  17602. },
  17603. b3p2: function ( t, p ) {
  17604. var k = 1 - t;
  17605. return 3 * k * t * t * p;
  17606. },
  17607. b3p3: function ( t, p ) {
  17608. return t * t * t * p;
  17609. },
  17610. b3: function ( t, p0, p1, p2, p3 ) {
  17611. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17612. }
  17613. };
  17614. /**
  17615. * @author mikael emtinger / http://gomo.se/
  17616. */
  17617. THREE.AnimationHandler = (function() {
  17618. var playing = [];
  17619. var library = {};
  17620. var that = {};
  17621. //--- update ---
  17622. that.update = function( deltaTimeMS ) {
  17623. for( var i = 0; i < playing.length; i ++ )
  17624. playing[ i ].update( deltaTimeMS );
  17625. };
  17626. //--- add ---
  17627. that.addToUpdate = function( animation ) {
  17628. if ( playing.indexOf( animation ) === -1 )
  17629. playing.push( animation );
  17630. };
  17631. //--- remove ---
  17632. that.removeFromUpdate = function( animation ) {
  17633. var index = playing.indexOf( animation );
  17634. if( index !== -1 )
  17635. playing.splice( index, 1 );
  17636. };
  17637. //--- add ---
  17638. that.add = function( data ) {
  17639. if ( library[ data.name ] !== undefined )
  17640. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17641. library[ data.name ] = data;
  17642. initData( data );
  17643. };
  17644. //--- get ---
  17645. that.get = function( name ) {
  17646. if ( typeof name === "string" ) {
  17647. if ( library[ name ] ) {
  17648. return library[ name ];
  17649. } else {
  17650. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17651. return null;
  17652. }
  17653. } else {
  17654. // todo: add simple tween library
  17655. }
  17656. };
  17657. //--- parse ---
  17658. that.parse = function( root ) {
  17659. // setup hierarchy
  17660. var hierarchy = [];
  17661. if ( root instanceof THREE.SkinnedMesh ) {
  17662. for( var b = 0; b < root.bones.length; b++ ) {
  17663. hierarchy.push( root.bones[ b ] );
  17664. }
  17665. } else {
  17666. parseRecurseHierarchy( root, hierarchy );
  17667. }
  17668. return hierarchy;
  17669. };
  17670. var parseRecurseHierarchy = function( root, hierarchy ) {
  17671. hierarchy.push( root );
  17672. for( var c = 0; c < root.children.length; c++ )
  17673. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17674. }
  17675. //--- init data ---
  17676. var initData = function( data ) {
  17677. if( data.initialized === true )
  17678. return;
  17679. // loop through all keys
  17680. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17681. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17682. // remove minus times
  17683. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17684. data.hierarchy[ h ].keys[ k ].time = 0;
  17685. // create quaternions
  17686. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17687. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17688. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17689. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17690. }
  17691. }
  17692. // prepare morph target keys
  17693. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17694. // get all used
  17695. var usedMorphTargets = {};
  17696. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17697. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17698. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17699. usedMorphTargets[ morphTargetName ] = -1;
  17700. }
  17701. }
  17702. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17703. // set all used on all frames
  17704. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17705. var influences = {};
  17706. for ( var morphTargetName in usedMorphTargets ) {
  17707. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17708. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17709. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17710. break;
  17711. }
  17712. }
  17713. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17714. influences[ morphTargetName ] = 0;
  17715. }
  17716. }
  17717. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17718. }
  17719. }
  17720. // remove all keys that are on the same time
  17721. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17722. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17723. data.hierarchy[ h ].keys.splice( k, 1 );
  17724. k --;
  17725. }
  17726. }
  17727. // set index
  17728. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17729. data.hierarchy[ h ].keys[ k ].index = k;
  17730. }
  17731. }
  17732. // JIT
  17733. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17734. data.JIT = {};
  17735. data.JIT.hierarchy = [];
  17736. for( var h = 0; h < data.hierarchy.length; h ++ )
  17737. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17738. // done
  17739. data.initialized = true;
  17740. };
  17741. // interpolation types
  17742. that.LINEAR = 0;
  17743. that.CATMULLROM = 1;
  17744. that.CATMULLROM_FORWARD = 2;
  17745. return that;
  17746. }());
  17747. /**
  17748. * @author mikael emtinger / http://gomo.se/
  17749. * @author mrdoob / http://mrdoob.com/
  17750. * @author alteredq / http://alteredqualia.com/
  17751. */
  17752. THREE.Animation = function ( root, name, interpolationType ) {
  17753. this.root = root;
  17754. this.data = THREE.AnimationHandler.get( name );
  17755. this.hierarchy = THREE.AnimationHandler.parse( root );
  17756. this.currentTime = 0;
  17757. this.timeScale = 1;
  17758. this.isPlaying = false;
  17759. this.isPaused = true;
  17760. this.loop = true;
  17761. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17762. this.points = [];
  17763. this.target = new THREE.Vector3();
  17764. };
  17765. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17766. if ( this.isPlaying === false ) {
  17767. this.isPlaying = true;
  17768. this.loop = loop !== undefined ? loop : true;
  17769. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17770. // reset key cache
  17771. var h, hl = this.hierarchy.length,
  17772. object;
  17773. for ( h = 0; h < hl; h ++ ) {
  17774. object = this.hierarchy[ h ];
  17775. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17776. object.useQuaternion = true;
  17777. }
  17778. object.matrixAutoUpdate = true;
  17779. if ( object.animationCache === undefined ) {
  17780. object.animationCache = {};
  17781. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17782. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17783. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17784. }
  17785. var prevKey = object.animationCache.prevKey;
  17786. var nextKey = object.animationCache.nextKey;
  17787. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17788. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17789. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17790. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17791. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17792. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17793. }
  17794. this.update( 0 );
  17795. }
  17796. this.isPaused = false;
  17797. THREE.AnimationHandler.addToUpdate( this );
  17798. };
  17799. THREE.Animation.prototype.pause = function() {
  17800. if ( this.isPaused === true ) {
  17801. THREE.AnimationHandler.addToUpdate( this );
  17802. } else {
  17803. THREE.AnimationHandler.removeFromUpdate( this );
  17804. }
  17805. this.isPaused = !this.isPaused;
  17806. };
  17807. THREE.Animation.prototype.stop = function() {
  17808. this.isPlaying = false;
  17809. this.isPaused = false;
  17810. THREE.AnimationHandler.removeFromUpdate( this );
  17811. };
  17812. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17813. // early out
  17814. if ( this.isPlaying === false ) return;
  17815. // vars
  17816. var types = [ "pos", "rot", "scl" ];
  17817. var type;
  17818. var scale;
  17819. var vector;
  17820. var prevXYZ, nextXYZ;
  17821. var prevKey, nextKey;
  17822. var object;
  17823. var animationCache;
  17824. var frame;
  17825. var JIThierarchy = this.data.JIT.hierarchy;
  17826. var currentTime, unloopedCurrentTime;
  17827. var currentPoint, forwardPoint, angle;
  17828. this.currentTime += deltaTimeMS * this.timeScale;
  17829. unloopedCurrentTime = this.currentTime;
  17830. currentTime = this.currentTime = this.currentTime % this.data.length;
  17831. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17832. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17833. object = this.hierarchy[ h ];
  17834. animationCache = object.animationCache;
  17835. // loop through pos/rot/scl
  17836. for ( var t = 0; t < 3; t ++ ) {
  17837. // get keys
  17838. type = types[ t ];
  17839. prevKey = animationCache.prevKey[ type ];
  17840. nextKey = animationCache.nextKey[ type ];
  17841. // switch keys?
  17842. if ( nextKey.time <= unloopedCurrentTime ) {
  17843. // did we loop?
  17844. if ( currentTime < unloopedCurrentTime ) {
  17845. if ( this.loop ) {
  17846. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17847. nextKey = this.getNextKeyWith( type, h, 1 );
  17848. while( nextKey.time < currentTime ) {
  17849. prevKey = nextKey;
  17850. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17851. }
  17852. } else {
  17853. this.stop();
  17854. return;
  17855. }
  17856. } else {
  17857. do {
  17858. prevKey = nextKey;
  17859. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17860. } while( nextKey.time < currentTime )
  17861. }
  17862. animationCache.prevKey[ type ] = prevKey;
  17863. animationCache.nextKey[ type ] = nextKey;
  17864. }
  17865. object.matrixAutoUpdate = true;
  17866. object.matrixWorldNeedsUpdate = true;
  17867. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17868. prevXYZ = prevKey[ type ];
  17869. nextXYZ = nextKey[ type ];
  17870. // check scale error
  17871. if ( scale < 0 || scale > 1 ) {
  17872. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17873. scale = scale < 0 ? 0 : 1;
  17874. }
  17875. // interpolate
  17876. if ( type === "pos" ) {
  17877. vector = object.position;
  17878. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17879. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17880. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17881. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17882. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17883. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17884. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17885. this.points[ 1 ] = prevXYZ;
  17886. this.points[ 2 ] = nextXYZ;
  17887. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17888. scale = scale * 0.33 + 0.33;
  17889. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17890. vector.x = currentPoint[ 0 ];
  17891. vector.y = currentPoint[ 1 ];
  17892. vector.z = currentPoint[ 2 ];
  17893. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17894. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17895. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17896. this.target.sub( vector );
  17897. this.target.y = 0;
  17898. this.target.normalize();
  17899. angle = Math.atan2( this.target.x, this.target.z );
  17900. object.rotation.set( 0, angle, 0 );
  17901. }
  17902. }
  17903. } else if ( type === "rot" ) {
  17904. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17905. } else if ( type === "scl" ) {
  17906. vector = object.scale;
  17907. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17908. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17909. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17910. }
  17911. }
  17912. }
  17913. };
  17914. // Catmull-Rom spline
  17915. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17916. var c = [], v3 = [],
  17917. point, intPoint, weight, w2, w3,
  17918. pa, pb, pc, pd;
  17919. point = ( points.length - 1 ) * scale;
  17920. intPoint = Math.floor( point );
  17921. weight = point - intPoint;
  17922. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17923. c[ 1 ] = intPoint;
  17924. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17925. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17926. pa = points[ c[ 0 ] ];
  17927. pb = points[ c[ 1 ] ];
  17928. pc = points[ c[ 2 ] ];
  17929. pd = points[ c[ 3 ] ];
  17930. w2 = weight * weight;
  17931. w3 = weight * w2;
  17932. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17933. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17934. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17935. return v3;
  17936. };
  17937. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17938. var v0 = ( p2 - p0 ) * 0.5,
  17939. v1 = ( p3 - p1 ) * 0.5;
  17940. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17941. };
  17942. // Get next key with
  17943. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17944. var keys = this.data.hierarchy[ h ].keys;
  17945. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17946. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17947. key = key < keys.length - 1 ? key : keys.length - 1;
  17948. } else {
  17949. key = key % keys.length;
  17950. }
  17951. for ( ; key < keys.length; key++ ) {
  17952. if ( keys[ key ][ type ] !== undefined ) {
  17953. return keys[ key ];
  17954. }
  17955. }
  17956. return this.data.hierarchy[ h ].keys[ 0 ];
  17957. };
  17958. // Get previous key with
  17959. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17960. var keys = this.data.hierarchy[ h ].keys;
  17961. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17962. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17963. key = key > 0 ? key : 0;
  17964. } else {
  17965. key = key >= 0 ? key : key + keys.length;
  17966. }
  17967. for ( ; key >= 0; key -- ) {
  17968. if ( keys[ key ][ type ] !== undefined ) {
  17969. return keys[ key ];
  17970. }
  17971. }
  17972. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17973. };
  17974. /**
  17975. * @author mikael emtinger / http://gomo.se/
  17976. * @author mrdoob / http://mrdoob.com/
  17977. * @author alteredq / http://alteredqualia.com/
  17978. * @author khang duong
  17979. * @author erik kitson
  17980. */
  17981. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17982. this.root = root;
  17983. this.data = THREE.AnimationHandler.get( data );
  17984. this.hierarchy = THREE.AnimationHandler.parse( root );
  17985. this.currentTime = 0;
  17986. this.timeScale = 0.001;
  17987. this.isPlaying = false;
  17988. this.isPaused = true;
  17989. this.loop = true;
  17990. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17991. // initialize to first keyframes
  17992. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17993. var keys = this.data.hierarchy[h].keys,
  17994. sids = this.data.hierarchy[h].sids,
  17995. obj = this.hierarchy[h];
  17996. if ( keys.length && sids ) {
  17997. for ( var s = 0; s < sids.length; s++ ) {
  17998. var sid = sids[ s ],
  17999. next = this.getNextKeyWith( sid, h, 0 );
  18000. if ( next ) {
  18001. next.apply( sid );
  18002. }
  18003. }
  18004. obj.matrixAutoUpdate = false;
  18005. this.data.hierarchy[h].node.updateMatrix();
  18006. obj.matrixWorldNeedsUpdate = true;
  18007. }
  18008. }
  18009. };
  18010. // Play
  18011. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18012. if( !this.isPlaying ) {
  18013. this.isPlaying = true;
  18014. this.loop = loop !== undefined ? loop : true;
  18015. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18016. this.startTimeMs = startTimeMS;
  18017. this.startTime = 10000000;
  18018. this.endTime = -this.startTime;
  18019. // reset key cache
  18020. var h, hl = this.hierarchy.length,
  18021. object,
  18022. node;
  18023. for ( h = 0; h < hl; h++ ) {
  18024. object = this.hierarchy[ h ];
  18025. node = this.data.hierarchy[ h ];
  18026. object.useQuaternion = true;
  18027. if ( node.animationCache === undefined ) {
  18028. node.animationCache = {};
  18029. node.animationCache.prevKey = null;
  18030. node.animationCache.nextKey = null;
  18031. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18032. }
  18033. var keys = this.data.hierarchy[h].keys;
  18034. if (keys.length) {
  18035. node.animationCache.prevKey = keys[ 0 ];
  18036. node.animationCache.nextKey = keys[ 1 ];
  18037. this.startTime = Math.min( keys[0].time, this.startTime );
  18038. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18039. }
  18040. }
  18041. this.update( 0 );
  18042. }
  18043. this.isPaused = false;
  18044. THREE.AnimationHandler.addToUpdate( this );
  18045. };
  18046. // Pause
  18047. THREE.KeyFrameAnimation.prototype.pause = function() {
  18048. if( this.isPaused ) {
  18049. THREE.AnimationHandler.addToUpdate( this );
  18050. } else {
  18051. THREE.AnimationHandler.removeFromUpdate( this );
  18052. }
  18053. this.isPaused = !this.isPaused;
  18054. };
  18055. // Stop
  18056. THREE.KeyFrameAnimation.prototype.stop = function() {
  18057. this.isPlaying = false;
  18058. this.isPaused = false;
  18059. THREE.AnimationHandler.removeFromUpdate( this );
  18060. // reset JIT matrix and remove cache
  18061. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18062. var obj = this.hierarchy[ h ];
  18063. var node = this.data.hierarchy[ h ];
  18064. if ( node.animationCache !== undefined ) {
  18065. var original = node.animationCache.originalMatrix;
  18066. if( obj instanceof THREE.Bone ) {
  18067. original.copy( obj.skinMatrix );
  18068. obj.skinMatrix = original;
  18069. } else {
  18070. original.copy( obj.matrix );
  18071. obj.matrix = original;
  18072. }
  18073. delete node.animationCache;
  18074. }
  18075. }
  18076. };
  18077. // Update
  18078. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18079. // early out
  18080. if( !this.isPlaying ) return;
  18081. // vars
  18082. var prevKey, nextKey;
  18083. var object;
  18084. var node;
  18085. var frame;
  18086. var JIThierarchy = this.data.JIT.hierarchy;
  18087. var currentTime, unloopedCurrentTime;
  18088. var looped;
  18089. // update
  18090. this.currentTime += deltaTimeMS * this.timeScale;
  18091. unloopedCurrentTime = this.currentTime;
  18092. currentTime = this.currentTime = this.currentTime % this.data.length;
  18093. // if looped around, the current time should be based on the startTime
  18094. if ( currentTime < this.startTimeMs ) {
  18095. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18096. }
  18097. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18098. looped = currentTime < unloopedCurrentTime;
  18099. if ( looped && !this.loop ) {
  18100. // Set the animation to the last keyframes and stop
  18101. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18102. var keys = this.data.hierarchy[h].keys,
  18103. sids = this.data.hierarchy[h].sids,
  18104. end = keys.length-1,
  18105. obj = this.hierarchy[h];
  18106. if ( keys.length ) {
  18107. for ( var s = 0; s < sids.length; s++ ) {
  18108. var sid = sids[ s ],
  18109. prev = this.getPrevKeyWith( sid, h, end );
  18110. if ( prev ) {
  18111. prev.apply( sid );
  18112. }
  18113. }
  18114. this.data.hierarchy[h].node.updateMatrix();
  18115. obj.matrixWorldNeedsUpdate = true;
  18116. }
  18117. }
  18118. this.stop();
  18119. return;
  18120. }
  18121. // check pre-infinity
  18122. if ( currentTime < this.startTime ) {
  18123. return;
  18124. }
  18125. // update
  18126. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18127. object = this.hierarchy[ h ];
  18128. node = this.data.hierarchy[ h ];
  18129. var keys = node.keys,
  18130. animationCache = node.animationCache;
  18131. // use JIT?
  18132. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18133. if( object instanceof THREE.Bone ) {
  18134. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18135. object.matrixWorldNeedsUpdate = false;
  18136. } else {
  18137. object.matrix = JIThierarchy[ h ][ frame ];
  18138. object.matrixWorldNeedsUpdate = true;
  18139. }
  18140. // use interpolation
  18141. } else if ( keys.length ) {
  18142. // make sure so original matrix and not JIT matrix is set
  18143. if ( this.JITCompile && animationCache ) {
  18144. if( object instanceof THREE.Bone ) {
  18145. object.skinMatrix = animationCache.originalMatrix;
  18146. } else {
  18147. object.matrix = animationCache.originalMatrix;
  18148. }
  18149. }
  18150. prevKey = animationCache.prevKey;
  18151. nextKey = animationCache.nextKey;
  18152. if ( prevKey && nextKey ) {
  18153. // switch keys?
  18154. if ( nextKey.time <= unloopedCurrentTime ) {
  18155. // did we loop?
  18156. if ( looped && this.loop ) {
  18157. prevKey = keys[ 0 ];
  18158. nextKey = keys[ 1 ];
  18159. while ( nextKey.time < currentTime ) {
  18160. prevKey = nextKey;
  18161. nextKey = keys[ prevKey.index + 1 ];
  18162. }
  18163. } else if ( !looped ) {
  18164. var lastIndex = keys.length - 1;
  18165. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18166. prevKey = nextKey;
  18167. nextKey = keys[ prevKey.index + 1 ];
  18168. }
  18169. }
  18170. animationCache.prevKey = prevKey;
  18171. animationCache.nextKey = nextKey;
  18172. }
  18173. if(nextKey.time >= currentTime)
  18174. prevKey.interpolate( nextKey, currentTime );
  18175. else
  18176. prevKey.interpolate( nextKey, nextKey.time);
  18177. }
  18178. this.data.hierarchy[h].node.updateMatrix();
  18179. object.matrixWorldNeedsUpdate = true;
  18180. }
  18181. }
  18182. // update JIT?
  18183. if ( this.JITCompile ) {
  18184. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18185. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18186. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18187. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18188. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18189. } else {
  18190. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18191. }
  18192. }
  18193. }
  18194. }
  18195. };
  18196. // Get next key with
  18197. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18198. var keys = this.data.hierarchy[ h ].keys;
  18199. key = key % keys.length;
  18200. for ( ; key < keys.length; key++ ) {
  18201. if ( keys[ key ].hasTarget( sid ) ) {
  18202. return keys[ key ];
  18203. }
  18204. }
  18205. return keys[ 0 ];
  18206. };
  18207. // Get previous key with
  18208. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18209. var keys = this.data.hierarchy[ h ].keys;
  18210. key = key >= 0 ? key : key + keys.length;
  18211. for ( ; key >= 0; key-- ) {
  18212. if ( keys[ key ].hasTarget( sid ) ) {
  18213. return keys[ key ];
  18214. }
  18215. }
  18216. return keys[ keys.length - 1 ];
  18217. };
  18218. /**
  18219. * Camera for rendering cube maps
  18220. * - renders scene into axis-aligned cube
  18221. *
  18222. * @author alteredq / http://alteredqualia.com/
  18223. */
  18224. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18225. THREE.Object3D.call( this );
  18226. var fov = 90, aspect = 1;
  18227. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18228. cameraPX.up.set( 0, -1, 0 );
  18229. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18230. this.add( cameraPX );
  18231. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18232. cameraNX.up.set( 0, -1, 0 );
  18233. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18234. this.add( cameraNX );
  18235. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18236. cameraPY.up.set( 0, 0, 1 );
  18237. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18238. this.add( cameraPY );
  18239. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18240. cameraNY.up.set( 0, 0, -1 );
  18241. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18242. this.add( cameraNY );
  18243. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18244. cameraPZ.up.set( 0, -1, 0 );
  18245. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18246. this.add( cameraPZ );
  18247. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18248. cameraNZ.up.set( 0, -1, 0 );
  18249. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18250. this.add( cameraNZ );
  18251. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18252. this.updateCubeMap = function ( renderer, scene ) {
  18253. var renderTarget = this.renderTarget;
  18254. var generateMipmaps = renderTarget.generateMipmaps;
  18255. renderTarget.generateMipmaps = false;
  18256. renderTarget.activeCubeFace = 0;
  18257. renderer.render( scene, cameraPX, renderTarget );
  18258. renderTarget.activeCubeFace = 1;
  18259. renderer.render( scene, cameraNX, renderTarget );
  18260. renderTarget.activeCubeFace = 2;
  18261. renderer.render( scene, cameraPY, renderTarget );
  18262. renderTarget.activeCubeFace = 3;
  18263. renderer.render( scene, cameraNY, renderTarget );
  18264. renderTarget.activeCubeFace = 4;
  18265. renderer.render( scene, cameraPZ, renderTarget );
  18266. renderTarget.generateMipmaps = generateMipmaps;
  18267. renderTarget.activeCubeFace = 5;
  18268. renderer.render( scene, cameraNZ, renderTarget );
  18269. };
  18270. };
  18271. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18272. /*
  18273. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18274. *
  18275. * A general perpose camera, for setting FOV, Lens Focal Length,
  18276. * and switching between perspective and orthographic views easily.
  18277. * Use this only if you do not wish to manage
  18278. * both a Orthographic and Perspective Camera
  18279. *
  18280. */
  18281. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18282. THREE.Camera.call( this );
  18283. this.fov = fov;
  18284. this.left = -width / 2;
  18285. this.right = width / 2
  18286. this.top = height / 2;
  18287. this.bottom = -height / 2;
  18288. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18289. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18290. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18291. this.zoom = 1;
  18292. this.toPerspective();
  18293. var aspect = width/height;
  18294. };
  18295. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18296. THREE.CombinedCamera.prototype.toPerspective = function () {
  18297. // Switches to the Perspective Camera
  18298. this.near = this.cameraP.near;
  18299. this.far = this.cameraP.far;
  18300. this.cameraP.fov = this.fov / this.zoom ;
  18301. this.cameraP.updateProjectionMatrix();
  18302. this.projectionMatrix = this.cameraP.projectionMatrix;
  18303. this.inPerspectiveMode = true;
  18304. this.inOrthographicMode = false;
  18305. };
  18306. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18307. // Switches to the Orthographic camera estimating viewport from Perspective
  18308. var fov = this.fov;
  18309. var aspect = this.cameraP.aspect;
  18310. var near = this.cameraP.near;
  18311. var far = this.cameraP.far;
  18312. // The size that we set is the mid plane of the viewing frustum
  18313. var hyperfocus = ( near + far ) / 2;
  18314. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18315. var planeHeight = 2 * halfHeight;
  18316. var planeWidth = planeHeight * aspect;
  18317. var halfWidth = planeWidth / 2;
  18318. halfHeight /= this.zoom;
  18319. halfWidth /= this.zoom;
  18320. this.cameraO.left = -halfWidth;
  18321. this.cameraO.right = halfWidth;
  18322. this.cameraO.top = halfHeight;
  18323. this.cameraO.bottom = -halfHeight;
  18324. // this.cameraO.left = -farHalfWidth;
  18325. // this.cameraO.right = farHalfWidth;
  18326. // this.cameraO.top = farHalfHeight;
  18327. // this.cameraO.bottom = -farHalfHeight;
  18328. // this.cameraO.left = this.left / this.zoom;
  18329. // this.cameraO.right = this.right / this.zoom;
  18330. // this.cameraO.top = this.top / this.zoom;
  18331. // this.cameraO.bottom = this.bottom / this.zoom;
  18332. this.cameraO.updateProjectionMatrix();
  18333. this.near = this.cameraO.near;
  18334. this.far = this.cameraO.far;
  18335. this.projectionMatrix = this.cameraO.projectionMatrix;
  18336. this.inPerspectiveMode = false;
  18337. this.inOrthographicMode = true;
  18338. };
  18339. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18340. this.cameraP.aspect = width / height;
  18341. this.left = -width / 2;
  18342. this.right = width / 2
  18343. this.top = height / 2;
  18344. this.bottom = -height / 2;
  18345. };
  18346. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18347. this.fov = fov;
  18348. if ( this.inPerspectiveMode ) {
  18349. this.toPerspective();
  18350. } else {
  18351. this.toOrthographic();
  18352. }
  18353. };
  18354. // For mantaining similar API with PerspectiveCamera
  18355. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18356. if ( this.inPerspectiveMode ) {
  18357. this.toPerspective();
  18358. } else {
  18359. this.toPerspective();
  18360. this.toOrthographic();
  18361. }
  18362. };
  18363. /*
  18364. * Uses Focal Length (in mm) to estimate and set FOV
  18365. * 35mm (fullframe) camera is used if frame size is not specified;
  18366. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18367. */
  18368. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18369. if ( frameHeight === undefined ) frameHeight = 24;
  18370. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18371. this.setFov( fov );
  18372. return fov;
  18373. };
  18374. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18375. this.zoom = zoom;
  18376. if ( this.inPerspectiveMode ) {
  18377. this.toPerspective();
  18378. } else {
  18379. this.toOrthographic();
  18380. }
  18381. };
  18382. THREE.CombinedCamera.prototype.toFrontView = function() {
  18383. this.rotation.x = 0;
  18384. this.rotation.y = 0;
  18385. this.rotation.z = 0;
  18386. // should we be modifing the matrix instead?
  18387. this.rotationAutoUpdate = false;
  18388. };
  18389. THREE.CombinedCamera.prototype.toBackView = function() {
  18390. this.rotation.x = 0;
  18391. this.rotation.y = Math.PI;
  18392. this.rotation.z = 0;
  18393. this.rotationAutoUpdate = false;
  18394. };
  18395. THREE.CombinedCamera.prototype.toLeftView = function() {
  18396. this.rotation.x = 0;
  18397. this.rotation.y = - Math.PI / 2;
  18398. this.rotation.z = 0;
  18399. this.rotationAutoUpdate = false;
  18400. };
  18401. THREE.CombinedCamera.prototype.toRightView = function() {
  18402. this.rotation.x = 0;
  18403. this.rotation.y = Math.PI / 2;
  18404. this.rotation.z = 0;
  18405. this.rotationAutoUpdate = false;
  18406. };
  18407. THREE.CombinedCamera.prototype.toTopView = function() {
  18408. this.rotation.x = - Math.PI / 2;
  18409. this.rotation.y = 0;
  18410. this.rotation.z = 0;
  18411. this.rotationAutoUpdate = false;
  18412. };
  18413. THREE.CombinedCamera.prototype.toBottomView = function() {
  18414. this.rotation.x = Math.PI / 2;
  18415. this.rotation.y = 0;
  18416. this.rotation.z = 0;
  18417. this.rotationAutoUpdate = false;
  18418. };
  18419. /**
  18420. * @author hughes
  18421. */
  18422. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18423. THREE.Geometry.call( this );
  18424. radius = radius || 50;
  18425. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18426. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18427. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18428. var i, uvs = [],
  18429. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18430. this.vertices.push(center);
  18431. uvs.push( centerUV );
  18432. for ( i = 0; i <= segments; i ++ ) {
  18433. var vertex = new THREE.Vector3();
  18434. var segment = thetaStart + i / segments * thetaLength;
  18435. vertex.x = radius * Math.cos( segment );
  18436. vertex.y = radius * Math.sin( segment );
  18437. this.vertices.push( vertex );
  18438. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18439. }
  18440. var n = new THREE.Vector3( 0, 0, -1 );
  18441. for ( i = 1; i <= segments; i ++ ) {
  18442. var v1 = i;
  18443. var v2 = i + 1 ;
  18444. var v3 = 0;
  18445. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18446. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18447. }
  18448. this.computeCentroids();
  18449. this.computeFaceNormals();
  18450. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18451. };
  18452. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18453. /**
  18454. * @author mrdoob / http://mrdoob.com/
  18455. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18456. */
  18457. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18458. THREE.Geometry.call( this );
  18459. var scope = this;
  18460. this.width = width;
  18461. this.height = height;
  18462. this.depth = depth;
  18463. this.widthSegments = widthSegments || 1;
  18464. this.heightSegments = heightSegments || 1;
  18465. this.depthSegments = depthSegments || 1;
  18466. var width_half = this.width / 2;
  18467. var height_half = this.height / 2;
  18468. var depth_half = this.depth / 2;
  18469. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18470. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18471. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18472. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18473. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18474. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18475. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18476. var w, ix, iy,
  18477. gridX = scope.widthSegments,
  18478. gridY = scope.heightSegments,
  18479. width_half = width / 2,
  18480. height_half = height / 2,
  18481. offset = scope.vertices.length;
  18482. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18483. w = 'z';
  18484. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18485. w = 'y';
  18486. gridY = scope.depthSegments;
  18487. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18488. w = 'x';
  18489. gridX = scope.depthSegments;
  18490. }
  18491. var gridX1 = gridX + 1,
  18492. gridY1 = gridY + 1,
  18493. segment_width = width / gridX,
  18494. segment_height = height / gridY,
  18495. normal = new THREE.Vector3();
  18496. normal[ w ] = depth > 0 ? 1 : - 1;
  18497. for ( iy = 0; iy < gridY1; iy ++ ) {
  18498. for ( ix = 0; ix < gridX1; ix ++ ) {
  18499. var vector = new THREE.Vector3();
  18500. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18501. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18502. vector[ w ] = depth;
  18503. scope.vertices.push( vector );
  18504. }
  18505. }
  18506. for ( iy = 0; iy < gridY; iy++ ) {
  18507. for ( ix = 0; ix < gridX; ix++ ) {
  18508. var a = ix + gridX1 * iy;
  18509. var b = ix + gridX1 * ( iy + 1 );
  18510. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18511. var d = ( ix + 1 ) + gridX1 * iy;
  18512. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18513. face.normal.copy( normal );
  18514. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18515. face.materialIndex = materialIndex;
  18516. scope.faces.push( face );
  18517. scope.faceVertexUvs[ 0 ].push( [
  18518. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18519. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18520. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18521. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18522. ] );
  18523. }
  18524. }
  18525. }
  18526. this.computeCentroids();
  18527. this.mergeVertices();
  18528. };
  18529. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18530. /**
  18531. * @author mrdoob / http://mrdoob.com/
  18532. */
  18533. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18534. THREE.Geometry.call( this );
  18535. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18536. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18537. this.height = height = height !== undefined ? height : 100;
  18538. this.radiusSegments = radiusSegments = radiusSegments || 8;
  18539. this.heightSegments = heightSegments = heightSegments || 1;
  18540. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18541. var heightHalf = height / 2;
  18542. var x, y, vertices = [], uvs = [];
  18543. for ( y = 0; y <= heightSegments; y ++ ) {
  18544. var verticesRow = [];
  18545. var uvsRow = [];
  18546. var v = y / heightSegments;
  18547. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18548. for ( x = 0; x <= radiusSegments; x ++ ) {
  18549. var u = x / radiusSegments;
  18550. var vertex = new THREE.Vector3();
  18551. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18552. vertex.y = - v * height + heightHalf;
  18553. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18554. this.vertices.push( vertex );
  18555. verticesRow.push( this.vertices.length - 1 );
  18556. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18557. }
  18558. vertices.push( verticesRow );
  18559. uvs.push( uvsRow );
  18560. }
  18561. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18562. var na, nb;
  18563. for ( x = 0; x < radiusSegments; x ++ ) {
  18564. if ( radiusTop !== 0 ) {
  18565. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18566. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18567. } else {
  18568. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18569. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18570. }
  18571. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18572. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18573. for ( y = 0; y < heightSegments; y ++ ) {
  18574. var v1 = vertices[ y ][ x ];
  18575. var v2 = vertices[ y + 1 ][ x ];
  18576. var v3 = vertices[ y + 1 ][ x + 1 ];
  18577. var v4 = vertices[ y ][ x + 1 ];
  18578. var n1 = na.clone();
  18579. var n2 = na.clone();
  18580. var n3 = nb.clone();
  18581. var n4 = nb.clone();
  18582. var uv1 = uvs[ y ][ x ].clone();
  18583. var uv2 = uvs[ y + 1 ][ x ].clone();
  18584. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18585. var uv4 = uvs[ y ][ x + 1 ].clone();
  18586. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18587. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18588. }
  18589. }
  18590. // top cap
  18591. if ( openEnded === false && radiusTop > 0 ) {
  18592. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18593. for ( x = 0; x < radiusSegments; x ++ ) {
  18594. var v1 = vertices[ 0 ][ x ];
  18595. var v2 = vertices[ 0 ][ x + 1 ];
  18596. var v3 = this.vertices.length - 1;
  18597. var n1 = new THREE.Vector3( 0, 1, 0 );
  18598. var n2 = new THREE.Vector3( 0, 1, 0 );
  18599. var n3 = new THREE.Vector3( 0, 1, 0 );
  18600. var uv1 = uvs[ 0 ][ x ].clone();
  18601. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18602. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18603. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18604. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18605. }
  18606. }
  18607. // bottom cap
  18608. if ( openEnded === false && radiusBottom > 0 ) {
  18609. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18610. for ( x = 0; x < radiusSegments; x ++ ) {
  18611. var v1 = vertices[ y ][ x + 1 ];
  18612. var v2 = vertices[ y ][ x ];
  18613. var v3 = this.vertices.length - 1;
  18614. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18615. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18616. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18617. var uv1 = uvs[ y ][ x + 1 ].clone();
  18618. var uv2 = uvs[ y ][ x ].clone();
  18619. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18620. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18621. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18622. }
  18623. }
  18624. this.computeCentroids();
  18625. this.computeFaceNormals();
  18626. }
  18627. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18628. /**
  18629. * @author zz85 / http://www.lab4games.net/zz85/blog
  18630. *
  18631. * Creates extruded geometry from a path shape.
  18632. *
  18633. * parameters = {
  18634. *
  18635. * size: <float>, // size of the text
  18636. * height: <float>, // thickness to extrude text
  18637. * curveSegments: <int>, // number of points on the curves
  18638. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18639. * amount: <int>, // Amount
  18640. *
  18641. * bevelEnabled: <bool>, // turn on bevel
  18642. * bevelThickness: <float>, // how deep into text bevel goes
  18643. * bevelSize: <float>, // how far from text outline is bevel
  18644. * bevelSegments: <int>, // number of bevel layers
  18645. *
  18646. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18647. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18648. *
  18649. * material: <int> // material index for front and back faces
  18650. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18651. * uvGenerator: <Object> // object that provides UV generator functions
  18652. *
  18653. * }
  18654. **/
  18655. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18656. if ( typeof( shapes ) === "undefined" ) {
  18657. shapes = [];
  18658. return;
  18659. }
  18660. THREE.Geometry.call( this );
  18661. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18662. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18663. this.addShapeList( shapes, options );
  18664. this.computeCentroids();
  18665. this.computeFaceNormals();
  18666. // can't really use automatic vertex normals
  18667. // as then front and back sides get smoothed too
  18668. // should do separate smoothing just for sides
  18669. //this.computeVertexNormals();
  18670. //console.log( "took", ( Date.now() - startTime ) );
  18671. };
  18672. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18673. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18674. var sl = shapes.length;
  18675. for ( var s = 0; s < sl; s ++ ) {
  18676. var shape = shapes[ s ];
  18677. this.addShape( shape, options );
  18678. }
  18679. };
  18680. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18681. var amount = options.amount !== undefined ? options.amount : 100;
  18682. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18683. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18684. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18685. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18686. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18687. var steps = options.steps !== undefined ? options.steps : 1;
  18688. var extrudePath = options.extrudePath;
  18689. var extrudePts, extrudeByPath = false;
  18690. var material = options.material;
  18691. var extrudeMaterial = options.extrudeMaterial;
  18692. // Use default WorldUVGenerator if no UV generators are specified.
  18693. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18694. var shapebb = this.shapebb;
  18695. //shapebb = shape.getBoundingBox();
  18696. var splineTube, binormal, normal, position2;
  18697. if ( extrudePath ) {
  18698. extrudePts = extrudePath.getSpacedPoints( steps );
  18699. extrudeByPath = true;
  18700. bevelEnabled = false; // bevels not supported for path extrusion
  18701. // SETUP TNB variables
  18702. // Reuse TNB from TubeGeomtry for now.
  18703. // TODO1 - have a .isClosed in spline?
  18704. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18705. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18706. binormal = new THREE.Vector3();
  18707. normal = new THREE.Vector3();
  18708. position2 = new THREE.Vector3();
  18709. }
  18710. // Safeguards if bevels are not enabled
  18711. if ( ! bevelEnabled ) {
  18712. bevelSegments = 0;
  18713. bevelThickness = 0;
  18714. bevelSize = 0;
  18715. }
  18716. // Variables initalization
  18717. var ahole, h, hl; // looping of holes
  18718. var scope = this;
  18719. var bevelPoints = [];
  18720. var shapesOffset = this.vertices.length;
  18721. var shapePoints = shape.extractPoints( curveSegments );
  18722. var vertices = shapePoints.shape;
  18723. var holes = shapePoints.holes;
  18724. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18725. if ( reverse ) {
  18726. vertices = vertices.reverse();
  18727. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18728. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18729. ahole = holes[ h ];
  18730. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18731. holes[ h ] = ahole.reverse();
  18732. }
  18733. }
  18734. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18735. }
  18736. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18737. /* Vertices */
  18738. var contour = vertices; // vertices has all points but contour has only points of circumference
  18739. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18740. ahole = holes[ h ];
  18741. vertices = vertices.concat( ahole );
  18742. }
  18743. function scalePt2 ( pt, vec, size ) {
  18744. if ( !vec ) console.log( "die" );
  18745. return vec.clone().multiplyScalar( size ).add( pt );
  18746. }
  18747. var b, bs, t, z,
  18748. vert, vlen = vertices.length,
  18749. face, flen = faces.length,
  18750. cont, clen = contour.length;
  18751. // Find directions for point movement
  18752. var RAD_TO_DEGREES = 180 / Math.PI;
  18753. function getBevelVec( pt_i, pt_j, pt_k ) {
  18754. // Algorithm 2
  18755. return getBevelVec2( pt_i, pt_j, pt_k );
  18756. }
  18757. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18758. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18759. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18760. if ( anglea > angleb ) {
  18761. angleb += Math.PI * 2;
  18762. }
  18763. var anglec = ( anglea + angleb ) / 2;
  18764. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18765. var x = - Math.cos( anglec );
  18766. var y = - Math.sin( anglec );
  18767. var vec = new THREE.Vector2( x, y ); //.normalize();
  18768. return vec;
  18769. }
  18770. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18771. var a = THREE.ExtrudeGeometry.__v1,
  18772. b = THREE.ExtrudeGeometry.__v2,
  18773. v_hat = THREE.ExtrudeGeometry.__v3,
  18774. w_hat = THREE.ExtrudeGeometry.__v4,
  18775. p = THREE.ExtrudeGeometry.__v5,
  18776. q = THREE.ExtrudeGeometry.__v6,
  18777. v, w,
  18778. v_dot_w_hat, q_sub_p_dot_w_hat,
  18779. s, intersection;
  18780. // good reading for line-line intersection
  18781. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18782. // define a as vector j->i
  18783. // define b as vectot k->i
  18784. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18785. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18786. // get unit vectors
  18787. v = a.normalize();
  18788. w = b.normalize();
  18789. // normals from pt i
  18790. v_hat.set( -v.y, v.x );
  18791. w_hat.set( w.y, -w.x );
  18792. // pts from i
  18793. p.copy( pt_i ).add( v_hat );
  18794. q.copy( pt_i ).add( w_hat );
  18795. if ( p.equals( q ) ) {
  18796. //console.log("Warning: lines are straight");
  18797. return w_hat.clone();
  18798. }
  18799. // Points from j, k. helps prevents points cross overover most of the time
  18800. p.copy( pt_j ).add( v_hat );
  18801. q.copy( pt_k ).add( w_hat );
  18802. v_dot_w_hat = v.dot( w_hat );
  18803. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18804. // We should not reach these conditions
  18805. if ( v_dot_w_hat === 0 ) {
  18806. console.log( "Either infinite or no solutions!" );
  18807. if ( q_sub_p_dot_w_hat === 0 ) {
  18808. console.log( "Its finite solutions." );
  18809. } else {
  18810. console.log( "Too bad, no solutions." );
  18811. }
  18812. }
  18813. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18814. if ( s < 0 ) {
  18815. // in case of emergecy, revert to algorithm 1.
  18816. return getBevelVec1( pt_i, pt_j, pt_k );
  18817. }
  18818. intersection = v.multiplyScalar( s ).add( p );
  18819. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18820. }
  18821. var contourMovements = [];
  18822. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18823. if ( j === il ) j = 0;
  18824. if ( k === il ) k = 0;
  18825. // (j)---(i)---(k)
  18826. // console.log('i,j,k', i, j , k)
  18827. var pt_i = contour[ i ];
  18828. var pt_j = contour[ j ];
  18829. var pt_k = contour[ k ];
  18830. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18831. }
  18832. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18833. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18834. ahole = holes[ h ];
  18835. oneHoleMovements = [];
  18836. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18837. if ( j === il ) j = 0;
  18838. if ( k === il ) k = 0;
  18839. // (j)---(i)---(k)
  18840. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18841. }
  18842. holesMovements.push( oneHoleMovements );
  18843. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18844. }
  18845. // Loop bevelSegments, 1 for the front, 1 for the back
  18846. for ( b = 0; b < bevelSegments; b ++ ) {
  18847. //for ( b = bevelSegments; b > 0; b -- ) {
  18848. t = b / bevelSegments;
  18849. z = bevelThickness * ( 1 - t );
  18850. //z = bevelThickness * t;
  18851. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18852. //bs = bevelSize * t ; // linear
  18853. // contract shape
  18854. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18855. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18856. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18857. v( vert.x, vert.y, - z );
  18858. }
  18859. // expand holes
  18860. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18861. ahole = holes[ h ];
  18862. oneHoleMovements = holesMovements[ h ];
  18863. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18864. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18865. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18866. v( vert.x, vert.y, -z );
  18867. }
  18868. }
  18869. }
  18870. bs = bevelSize;
  18871. // Back facing vertices
  18872. for ( i = 0; i < vlen; i ++ ) {
  18873. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18874. if ( !extrudeByPath ) {
  18875. v( vert.x, vert.y, 0 );
  18876. } else {
  18877. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18878. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18879. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18880. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18881. v( position2.x, position2.y, position2.z );
  18882. }
  18883. }
  18884. // Add stepped vertices...
  18885. // Including front facing vertices
  18886. var s;
  18887. for ( s = 1; s <= steps; s ++ ) {
  18888. for ( i = 0; i < vlen; i ++ ) {
  18889. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18890. if ( !extrudeByPath ) {
  18891. v( vert.x, vert.y, amount / steps * s );
  18892. } else {
  18893. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18894. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18895. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18896. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18897. v( position2.x, position2.y, position2.z );
  18898. }
  18899. }
  18900. }
  18901. // Add bevel segments planes
  18902. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18903. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18904. t = b / bevelSegments;
  18905. z = bevelThickness * ( 1 - t );
  18906. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18907. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18908. // contract shape
  18909. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18910. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18911. v( vert.x, vert.y, amount + z );
  18912. }
  18913. // expand holes
  18914. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18915. ahole = holes[ h ];
  18916. oneHoleMovements = holesMovements[ h ];
  18917. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18918. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18919. if ( !extrudeByPath ) {
  18920. v( vert.x, vert.y, amount + z );
  18921. } else {
  18922. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18923. }
  18924. }
  18925. }
  18926. }
  18927. /* Faces */
  18928. // Top and bottom faces
  18929. buildLidFaces();
  18930. // Sides faces
  18931. buildSideFaces();
  18932. ///// Internal functions
  18933. function buildLidFaces() {
  18934. if ( bevelEnabled ) {
  18935. var layer = 0 ; // steps + 1
  18936. var offset = vlen * layer;
  18937. // Bottom faces
  18938. for ( i = 0; i < flen; i ++ ) {
  18939. face = faces[ i ];
  18940. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18941. }
  18942. layer = steps + bevelSegments * 2;
  18943. offset = vlen * layer;
  18944. // Top faces
  18945. for ( i = 0; i < flen; i ++ ) {
  18946. face = faces[ i ];
  18947. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18948. }
  18949. } else {
  18950. // Bottom faces
  18951. for ( i = 0; i < flen; i++ ) {
  18952. face = faces[ i ];
  18953. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18954. }
  18955. // Top faces
  18956. for ( i = 0; i < flen; i ++ ) {
  18957. face = faces[ i ];
  18958. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18959. }
  18960. }
  18961. }
  18962. // Create faces for the z-sides of the shape
  18963. function buildSideFaces() {
  18964. var layeroffset = 0;
  18965. sidewalls( contour, layeroffset );
  18966. layeroffset += contour.length;
  18967. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18968. ahole = holes[ h ];
  18969. sidewalls( ahole, layeroffset );
  18970. //, true
  18971. layeroffset += ahole.length;
  18972. }
  18973. }
  18974. function sidewalls( contour, layeroffset ) {
  18975. var j, k;
  18976. i = contour.length;
  18977. while ( --i >= 0 ) {
  18978. j = i;
  18979. k = i - 1;
  18980. if ( k < 0 ) k = contour.length - 1;
  18981. //console.log('b', i,j, i-1, k,vertices.length);
  18982. var s = 0, sl = steps + bevelSegments * 2;
  18983. for ( s = 0; s < sl; s ++ ) {
  18984. var slen1 = vlen * s;
  18985. var slen2 = vlen * ( s + 1 );
  18986. var a = layeroffset + j + slen1,
  18987. b = layeroffset + k + slen1,
  18988. c = layeroffset + k + slen2,
  18989. d = layeroffset + j + slen2;
  18990. f4( a, b, c, d, contour, s, sl, j, k );
  18991. }
  18992. }
  18993. }
  18994. function v( x, y, z ) {
  18995. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18996. }
  18997. function f3( a, b, c, isBottom ) {
  18998. a += shapesOffset;
  18999. b += shapesOffset;
  19000. c += shapesOffset;
  19001. // normal, color, material
  19002. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19003. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19004. scope.faceVertexUvs[ 0 ].push( uvs );
  19005. }
  19006. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19007. a += shapesOffset;
  19008. b += shapesOffset;
  19009. c += shapesOffset;
  19010. d += shapesOffset;
  19011. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19012. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19013. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19014. scope.faceVertexUvs[ 0 ].push( uvs );
  19015. }
  19016. };
  19017. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19018. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19019. var ax = geometry.vertices[ indexA ].x,
  19020. ay = geometry.vertices[ indexA ].y,
  19021. bx = geometry.vertices[ indexB ].x,
  19022. by = geometry.vertices[ indexB ].y,
  19023. cx = geometry.vertices[ indexC ].x,
  19024. cy = geometry.vertices[ indexC ].y;
  19025. return [
  19026. new THREE.Vector2( ax, ay ),
  19027. new THREE.Vector2( bx, by ),
  19028. new THREE.Vector2( cx, cy )
  19029. ];
  19030. },
  19031. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19032. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19033. },
  19034. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19035. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19036. contourIndex1, contourIndex2 ) {
  19037. var ax = geometry.vertices[ indexA ].x,
  19038. ay = geometry.vertices[ indexA ].y,
  19039. az = geometry.vertices[ indexA ].z,
  19040. bx = geometry.vertices[ indexB ].x,
  19041. by = geometry.vertices[ indexB ].y,
  19042. bz = geometry.vertices[ indexB ].z,
  19043. cx = geometry.vertices[ indexC ].x,
  19044. cy = geometry.vertices[ indexC ].y,
  19045. cz = geometry.vertices[ indexC ].z,
  19046. dx = geometry.vertices[ indexD ].x,
  19047. dy = geometry.vertices[ indexD ].y,
  19048. dz = geometry.vertices[ indexD ].z;
  19049. if ( Math.abs( ay - by ) < 0.01 ) {
  19050. return [
  19051. new THREE.Vector2( ax, 1 - az ),
  19052. new THREE.Vector2( bx, 1 - bz ),
  19053. new THREE.Vector2( cx, 1 - cz ),
  19054. new THREE.Vector2( dx, 1 - dz )
  19055. ];
  19056. } else {
  19057. return [
  19058. new THREE.Vector2( ay, 1 - az ),
  19059. new THREE.Vector2( by, 1 - bz ),
  19060. new THREE.Vector2( cy, 1 - cz ),
  19061. new THREE.Vector2( dy, 1 - dz )
  19062. ];
  19063. }
  19064. }
  19065. };
  19066. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19067. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19068. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19069. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19070. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19071. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19072. /**
  19073. * @author jonobr1 / http://jonobr1.com
  19074. *
  19075. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19076. * ExtrudeGeometry.
  19077. *
  19078. * parameters = {
  19079. *
  19080. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19081. *
  19082. * material: <int> // material index for front and back faces
  19083. * uvGenerator: <Object> // object that provides UV generator functions
  19084. *
  19085. * }
  19086. **/
  19087. THREE.ShapeGeometry = function ( shapes, options ) {
  19088. THREE.Geometry.call( this );
  19089. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19090. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19091. this.addShapeList( shapes, options );
  19092. this.computeCentroids();
  19093. this.computeFaceNormals();
  19094. };
  19095. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19096. /**
  19097. * Add an array of shapes to THREE.ShapeGeometry.
  19098. */
  19099. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19100. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19101. this.addShape( shapes[ i ], options );
  19102. }
  19103. return this;
  19104. };
  19105. /**
  19106. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19107. */
  19108. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19109. if ( options === undefined ) options = {};
  19110. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19111. var material = options.material;
  19112. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19113. var shapebb = this.shapebb;
  19114. //
  19115. var i, l, hole, s;
  19116. var shapesOffset = this.vertices.length;
  19117. var shapePoints = shape.extractPoints( curveSegments );
  19118. var vertices = shapePoints.shape;
  19119. var holes = shapePoints.holes;
  19120. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19121. if ( reverse ) {
  19122. vertices = vertices.reverse();
  19123. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19124. for ( i = 0, l = holes.length; i < l; i++ ) {
  19125. hole = holes[ i ];
  19126. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19127. holes[ i ] = hole.reverse();
  19128. }
  19129. }
  19130. reverse = false;
  19131. }
  19132. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19133. // Vertices
  19134. var contour = vertices;
  19135. for ( i = 0, l = holes.length; i < l; i++ ) {
  19136. hole = holes[ i ];
  19137. vertices = vertices.concat( hole );
  19138. }
  19139. //
  19140. var vert, vlen = vertices.length;
  19141. var face, flen = faces.length;
  19142. var cont, clen = contour.length;
  19143. for ( i = 0; i < vlen; i++ ) {
  19144. vert = vertices[ i ];
  19145. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19146. }
  19147. for ( i = 0; i < flen; i++ ) {
  19148. face = faces[ i ];
  19149. var a = face[ 0 ] + shapesOffset;
  19150. var b = face[ 1 ] + shapesOffset;
  19151. var c = face[ 2 ] + shapesOffset;
  19152. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19153. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19154. }
  19155. };
  19156. /**
  19157. * @author astrodud / http://astrodud.isgreat.org/
  19158. * @author zz85 / https://github.com/zz85
  19159. * @author bhouston / http://exocortex.com
  19160. */
  19161. // points - to create a closed torus, one must use a set of points
  19162. // like so: [ a, b, c, d, a ], see first is the same as last.
  19163. // segments - the number of circumference segments to create
  19164. // phiStart - the starting radian
  19165. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19166. // 2*pi is a closed lathe, less than 2PI is a portion.
  19167. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19168. THREE.Geometry.call( this );
  19169. segments = segments || 12;
  19170. phiStart = phiStart || 0;
  19171. phiLength = phiLength || 2 * Math.PI;
  19172. var inversePointLength = 1.0 / ( points.length - 1 );
  19173. var inverseSegments = 1.0 / segments;
  19174. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19175. var phi = phiStart + i * inverseSegments * phiLength;
  19176. var c = Math.cos( phi ),
  19177. s = Math.sin( phi );
  19178. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19179. var pt = points[ j ];
  19180. var vertex = new THREE.Vector3();
  19181. vertex.x = c * pt.x - s * pt.y;
  19182. vertex.y = s * pt.x + c * pt.y;
  19183. vertex.z = pt.z;
  19184. this.vertices.push( vertex );
  19185. }
  19186. }
  19187. var np = points.length;
  19188. for ( var i = 0, il = segments; i < il; i ++ ) {
  19189. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19190. var base = j + np * i;
  19191. var a = base;
  19192. var b = base + np;
  19193. var c = base + 1 + np;
  19194. var d = base + 1;
  19195. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19196. var u0 = i * inverseSegments;
  19197. var v0 = j * inversePointLength;
  19198. var u1 = u0 + inverseSegments;
  19199. var v1 = v0 + inversePointLength;
  19200. this.faceVertexUvs[ 0 ].push( [
  19201. new THREE.Vector2( u0, v0 ),
  19202. new THREE.Vector2( u1, v0 ),
  19203. new THREE.Vector2( u1, v1 ),
  19204. new THREE.Vector2( u0, v1 )
  19205. ] );
  19206. }
  19207. }
  19208. this.mergeVertices();
  19209. this.computeCentroids();
  19210. this.computeFaceNormals();
  19211. this.computeVertexNormals();
  19212. };
  19213. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19214. /**
  19215. * @author mrdoob / http://mrdoob.com/
  19216. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19217. */
  19218. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19219. THREE.Geometry.call( this );
  19220. this.width = width;
  19221. this.height = height;
  19222. this.widthSegments = widthSegments || 1;
  19223. this.heightSegments = heightSegments || 1;
  19224. var ix, iz;
  19225. var width_half = width / 2;
  19226. var height_half = height / 2;
  19227. var gridX = this.widthSegments;
  19228. var gridZ = this.heightSegments;
  19229. var gridX1 = gridX + 1;
  19230. var gridZ1 = gridZ + 1;
  19231. var segment_width = this.width / gridX;
  19232. var segment_height = this.height / gridZ;
  19233. var normal = new THREE.Vector3( 0, 0, 1 );
  19234. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19235. for ( ix = 0; ix < gridX1; ix ++ ) {
  19236. var x = ix * segment_width - width_half;
  19237. var y = iz * segment_height - height_half;
  19238. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19239. }
  19240. }
  19241. for ( iz = 0; iz < gridZ; iz ++ ) {
  19242. for ( ix = 0; ix < gridX; ix ++ ) {
  19243. var a = ix + gridX1 * iz;
  19244. var b = ix + gridX1 * ( iz + 1 );
  19245. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19246. var d = ( ix + 1 ) + gridX1 * iz;
  19247. var face = new THREE.Face4( a, b, c, d );
  19248. face.normal.copy( normal );
  19249. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19250. this.faces.push( face );
  19251. this.faceVertexUvs[ 0 ].push( [
  19252. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19253. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19254. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19255. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19256. ] );
  19257. }
  19258. }
  19259. this.computeCentroids();
  19260. };
  19261. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19262. /**
  19263. * @author Kaleb Murphy
  19264. */
  19265. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19266. THREE.Geometry.call( this );
  19267. innerRadius = innerRadius || 0;
  19268. outerRadius = outerRadius || 50;
  19269. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19270. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19271. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19272. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19273. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19274. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19275. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19276. var vertex = new THREE.Vector3();
  19277. var segment = thetaStart + o / thetaSegments * thetaLength;
  19278. vertex.x = radius * Math.cos( segment );
  19279. vertex.y = radius * Math.sin( segment );
  19280. this.vertices.push( vertex );
  19281. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19282. }
  19283. radius += radiusStep;
  19284. }
  19285. var n = new THREE.Vector3( 0, 0, 1 );
  19286. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19287. var thetaSegment = i * thetaSegments;
  19288. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19289. var segment = o + thetaSegment;
  19290. var v1 = segment + i;
  19291. var v2 = segment + thetaSegments + i;
  19292. var v3 = segment + thetaSegments + 1 + i;
  19293. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19294. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19295. v1 = segment + i;
  19296. v2 = segment + thetaSegments + 1 + i;
  19297. v3 = segment + 1 + i;
  19298. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19299. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19300. }
  19301. }
  19302. this.computeCentroids();
  19303. this.computeFaceNormals();
  19304. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19305. };
  19306. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19307. /**
  19308. * @author mrdoob / http://mrdoob.com/
  19309. */
  19310. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19311. THREE.Geometry.call( this );
  19312. this.radius = radius = radius || 50;
  19313. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19314. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19315. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19316. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19317. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19318. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19319. var x, y, vertices = [], uvs = [];
  19320. for ( y = 0; y <= heightSegments; y ++ ) {
  19321. var verticesRow = [];
  19322. var uvsRow = [];
  19323. for ( x = 0; x <= widthSegments; x ++ ) {
  19324. var u = x / widthSegments;
  19325. var v = y / heightSegments;
  19326. var vertex = new THREE.Vector3();
  19327. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19328. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19329. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19330. this.vertices.push( vertex );
  19331. verticesRow.push( this.vertices.length - 1 );
  19332. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19333. }
  19334. vertices.push( verticesRow );
  19335. uvs.push( uvsRow );
  19336. }
  19337. for ( y = 0; y < this.heightSegments; y ++ ) {
  19338. for ( x = 0; x < this.widthSegments; x ++ ) {
  19339. var v1 = vertices[ y ][ x + 1 ];
  19340. var v2 = vertices[ y ][ x ];
  19341. var v3 = vertices[ y + 1 ][ x ];
  19342. var v4 = vertices[ y + 1 ][ x + 1 ];
  19343. var n1 = this.vertices[ v1 ].clone().normalize();
  19344. var n2 = this.vertices[ v2 ].clone().normalize();
  19345. var n3 = this.vertices[ v3 ].clone().normalize();
  19346. var n4 = this.vertices[ v4 ].clone().normalize();
  19347. var uv1 = uvs[ y ][ x + 1 ].clone();
  19348. var uv2 = uvs[ y ][ x ].clone();
  19349. var uv3 = uvs[ y + 1 ][ x ].clone();
  19350. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19351. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19352. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19353. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19354. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19355. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19356. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19357. } else {
  19358. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19359. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19360. }
  19361. }
  19362. }
  19363. this.computeCentroids();
  19364. this.computeFaceNormals();
  19365. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19366. };
  19367. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19368. /**
  19369. * @author zz85 / http://www.lab4games.net/zz85/blog
  19370. * @author alteredq / http://alteredqualia.com/
  19371. *
  19372. * For creating 3D text geometry in three.js
  19373. *
  19374. * Text = 3D Text
  19375. *
  19376. * parameters = {
  19377. * size: <float>, // size of the text
  19378. * height: <float>, // thickness to extrude text
  19379. * curveSegments: <int>, // number of points on the curves
  19380. *
  19381. * font: <string>, // font name
  19382. * weight: <string>, // font weight (normal, bold)
  19383. * style: <string>, // font style (normal, italics)
  19384. *
  19385. * bevelEnabled: <bool>, // turn on bevel
  19386. * bevelThickness: <float>, // how deep into text bevel goes
  19387. * bevelSize: <float>, // how far from text outline is bevel
  19388. * }
  19389. *
  19390. */
  19391. /* Usage Examples
  19392. // TextGeometry wrapper
  19393. var text3d = new TextGeometry( text, options );
  19394. // Complete manner
  19395. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19396. var text3d = new ExtrudeGeometry( textShapes, options );
  19397. */
  19398. THREE.TextGeometry = function ( text, parameters ) {
  19399. parameters = parameters || {};
  19400. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19401. // translate parameters to ExtrudeGeometry API
  19402. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19403. // defaults
  19404. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19405. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19406. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19407. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19408. };
  19409. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19410. /**
  19411. * @author oosmoxiecode
  19412. * @author mrdoob / http://mrdoob.com/
  19413. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19414. */
  19415. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19416. THREE.Geometry.call( this );
  19417. var scope = this;
  19418. this.radius = radius || 100;
  19419. this.tube = tube || 40;
  19420. this.radialSegments = radialSegments || 8;
  19421. this.tubularSegments = tubularSegments || 6;
  19422. this.arc = arc || Math.PI * 2;
  19423. var center = new THREE.Vector3(), uvs = [], normals = [];
  19424. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19425. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19426. var u = i / this.tubularSegments * this.arc;
  19427. var v = j / this.radialSegments * Math.PI * 2;
  19428. center.x = this.radius * Math.cos( u );
  19429. center.y = this.radius * Math.sin( u );
  19430. var vertex = new THREE.Vector3();
  19431. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19432. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19433. vertex.z = this.tube * Math.sin( v );
  19434. this.vertices.push( vertex );
  19435. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19436. normals.push( vertex.clone().sub( center ).normalize() );
  19437. }
  19438. }
  19439. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19440. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19441. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19442. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19443. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19444. var d = ( this.tubularSegments + 1 ) * j + i;
  19445. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19446. face.normal.add( normals[ a ] );
  19447. face.normal.add( normals[ b ] );
  19448. face.normal.add( normals[ c ] );
  19449. face.normal.add( normals[ d ] );
  19450. face.normal.normalize();
  19451. this.faces.push( face );
  19452. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19453. }
  19454. }
  19455. this.computeCentroids();
  19456. };
  19457. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19458. /**
  19459. * @author oosmoxiecode
  19460. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19461. */
  19462. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19463. THREE.Geometry.call( this );
  19464. var scope = this;
  19465. this.radius = radius || 100;
  19466. this.tube = tube || 40;
  19467. this.radialSegments = radialSegments || 64;
  19468. this.tubularSegments = tubularSegments || 8;
  19469. this.p = p || 2;
  19470. this.q = q || 3;
  19471. this.heightScale = heightScale || 1;
  19472. this.grid = new Array( this.radialSegments );
  19473. var tang = new THREE.Vector3();
  19474. var n = new THREE.Vector3();
  19475. var bitan = new THREE.Vector3();
  19476. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19477. this.grid[ i ] = new Array( this.tubularSegments );
  19478. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19479. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19480. var v = j / this.tubularSegments * 2 * Math.PI;
  19481. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19482. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19483. var cx, cy;
  19484. tang.subVectors( p2, p1 );
  19485. n.addVectors( p2, p1 );
  19486. bitan.crossVectors( tang, n );
  19487. n.crossVectors( bitan, tang );
  19488. bitan.normalize();
  19489. n.normalize();
  19490. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19491. cy = this.tube * Math.sin( v );
  19492. p1.x += cx * n.x + cy * bitan.x;
  19493. p1.y += cx * n.y + cy * bitan.y;
  19494. p1.z += cx * n.z + cy * bitan.z;
  19495. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19496. }
  19497. }
  19498. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19499. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19500. var ip = ( i + 1 ) % this.radialSegments;
  19501. var jp = ( j + 1 ) % this.tubularSegments;
  19502. var a = this.grid[ i ][ j ];
  19503. var b = this.grid[ ip ][ j ];
  19504. var c = this.grid[ ip ][ jp ];
  19505. var d = this.grid[ i ][ jp ];
  19506. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19507. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19508. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19509. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19510. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19511. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19512. }
  19513. }
  19514. this.computeCentroids();
  19515. this.computeFaceNormals();
  19516. this.computeVertexNormals();
  19517. function vert( x, y, z ) {
  19518. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19519. }
  19520. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19521. var cu = Math.cos( u );
  19522. var cv = Math.cos( v );
  19523. var su = Math.sin( u );
  19524. var quOverP = in_q / in_p * u;
  19525. var cs = Math.cos( quOverP );
  19526. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19527. var ty = radius * ( 2 + cs ) * su * 0.5;
  19528. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19529. return new THREE.Vector3( tx, ty, tz );
  19530. }
  19531. };
  19532. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19533. /**
  19534. * @author WestLangley / https://github.com/WestLangley
  19535. * @author zz85 / https://github.com/zz85
  19536. * @author miningold / https://github.com/miningold
  19537. *
  19538. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19539. *
  19540. * Creates a tube which extrudes along a 3d spline
  19541. *
  19542. * Uses parallel transport frames as described in
  19543. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19544. */
  19545. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19546. THREE.Geometry.call( this );
  19547. this.path = path;
  19548. this.segments = segments || 64;
  19549. this.radius = radius || 1;
  19550. this.radiusSegments = radiusSegments || 8;
  19551. this.closed = closed || false;
  19552. if ( debug ) this.debug = new THREE.Object3D();
  19553. this.grid = [];
  19554. var scope = this,
  19555. tangent,
  19556. normal,
  19557. binormal,
  19558. numpoints = this.segments + 1,
  19559. x, y, z,
  19560. tx, ty, tz,
  19561. u, v,
  19562. cx, cy,
  19563. pos, pos2 = new THREE.Vector3(),
  19564. i, j,
  19565. ip, jp,
  19566. a, b, c, d,
  19567. uva, uvb, uvc, uvd;
  19568. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19569. tangents = frames.tangents,
  19570. normals = frames.normals,
  19571. binormals = frames.binormals;
  19572. // proxy internals
  19573. this.tangents = tangents;
  19574. this.normals = normals;
  19575. this.binormals = binormals;
  19576. function vert( x, y, z ) {
  19577. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19578. }
  19579. // consruct the grid
  19580. for ( i = 0; i < numpoints; i++ ) {
  19581. this.grid[ i ] = [];
  19582. u = i / ( numpoints - 1 );
  19583. pos = path.getPointAt( u );
  19584. tangent = tangents[ i ];
  19585. normal = normals[ i ];
  19586. binormal = binormals[ i ];
  19587. if ( this.debug ) {
  19588. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19589. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19590. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19591. }
  19592. for ( j = 0; j < this.radiusSegments; j++ ) {
  19593. v = j / this.radiusSegments * 2 * Math.PI;
  19594. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19595. cy = this.radius * Math.sin( v );
  19596. pos2.copy( pos );
  19597. pos2.x += cx * normal.x + cy * binormal.x;
  19598. pos2.y += cx * normal.y + cy * binormal.y;
  19599. pos2.z += cx * normal.z + cy * binormal.z;
  19600. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19601. }
  19602. }
  19603. // construct the mesh
  19604. for ( i = 0; i < this.segments; i++ ) {
  19605. for ( j = 0; j < this.radiusSegments; j++ ) {
  19606. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19607. jp = (j + 1) % this.radiusSegments;
  19608. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19609. b = this.grid[ ip ][ j ];
  19610. c = this.grid[ ip ][ jp ];
  19611. d = this.grid[ i ][ jp ];
  19612. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19613. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19614. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19615. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19616. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19617. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19618. }
  19619. }
  19620. this.computeCentroids();
  19621. this.computeFaceNormals();
  19622. this.computeVertexNormals();
  19623. };
  19624. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19625. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19626. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19627. var tangent = new THREE.Vector3(),
  19628. normal = new THREE.Vector3(),
  19629. binormal = new THREE.Vector3(),
  19630. tangents = [],
  19631. normals = [],
  19632. binormals = [],
  19633. vec = new THREE.Vector3(),
  19634. mat = new THREE.Matrix4(),
  19635. numpoints = segments + 1,
  19636. theta,
  19637. epsilon = 0.0001,
  19638. smallest,
  19639. tx, ty, tz,
  19640. i, u, v;
  19641. // expose internals
  19642. this.tangents = tangents;
  19643. this.normals = normals;
  19644. this.binormals = binormals;
  19645. // compute the tangent vectors for each segment on the path
  19646. for ( i = 0; i < numpoints; i++ ) {
  19647. u = i / ( numpoints - 1 );
  19648. tangents[ i ] = path.getTangentAt( u );
  19649. tangents[ i ].normalize();
  19650. }
  19651. initialNormal3();
  19652. function initialNormal1(lastBinormal) {
  19653. // fixed start binormal. Has dangers of 0 vectors
  19654. normals[ 0 ] = new THREE.Vector3();
  19655. binormals[ 0 ] = new THREE.Vector3();
  19656. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19657. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19658. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19659. }
  19660. function initialNormal2() {
  19661. // This uses the Frenet-Serret formula for deriving binormal
  19662. var t2 = path.getTangentAt( epsilon );
  19663. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19664. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19665. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19666. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19667. }
  19668. function initialNormal3() {
  19669. // select an initial normal vector perpenicular to the first tangent vector,
  19670. // and in the direction of the smallest tangent xyz component
  19671. normals[ 0 ] = new THREE.Vector3();
  19672. binormals[ 0 ] = new THREE.Vector3();
  19673. smallest = Number.MAX_VALUE;
  19674. tx = Math.abs( tangents[ 0 ].x );
  19675. ty = Math.abs( tangents[ 0 ].y );
  19676. tz = Math.abs( tangents[ 0 ].z );
  19677. if ( tx <= smallest ) {
  19678. smallest = tx;
  19679. normal.set( 1, 0, 0 );
  19680. }
  19681. if ( ty <= smallest ) {
  19682. smallest = ty;
  19683. normal.set( 0, 1, 0 );
  19684. }
  19685. if ( tz <= smallest ) {
  19686. normal.set( 0, 0, 1 );
  19687. }
  19688. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19689. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19690. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19691. }
  19692. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19693. for ( i = 1; i < numpoints; i++ ) {
  19694. normals[ i ] = normals[ i-1 ].clone();
  19695. binormals[ i ] = binormals[ i-1 ].clone();
  19696. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19697. if ( vec.length() > epsilon ) {
  19698. vec.normalize();
  19699. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19700. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19701. }
  19702. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19703. }
  19704. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19705. if ( closed ) {
  19706. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19707. theta /= ( numpoints - 1 );
  19708. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19709. theta = -theta;
  19710. }
  19711. for ( i = 1; i < numpoints; i++ ) {
  19712. // twist a little...
  19713. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19714. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19715. }
  19716. }
  19717. };
  19718. /**
  19719. * @author clockworkgeek / https://github.com/clockworkgeek
  19720. * @author timothypratley / https://github.com/timothypratley
  19721. */
  19722. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19723. THREE.Geometry.call( this );
  19724. radius = radius || 1;
  19725. detail = detail || 0;
  19726. var that = this;
  19727. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19728. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19729. }
  19730. var midpoints = [], p = this.vertices;
  19731. var f = [];
  19732. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19733. var v1 = p[ faces[ i ][ 0 ] ];
  19734. var v2 = p[ faces[ i ][ 1 ] ];
  19735. var v3 = p[ faces[ i ][ 2 ] ];
  19736. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19737. }
  19738. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19739. subdivide(f[ i ], detail);
  19740. }
  19741. this.mergeVertices();
  19742. // Apply radius
  19743. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19744. this.vertices[ i ].multiplyScalar( radius );
  19745. }
  19746. // Project vector onto sphere's surface
  19747. function prepare( vector ) {
  19748. var vertex = vector.normalize().clone();
  19749. vertex.index = that.vertices.push( vertex ) - 1;
  19750. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19751. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19752. var v = inclination( vector ) / Math.PI + 0.5;
  19753. vertex.uv = new THREE.Vector2( u, 1 - v );
  19754. return vertex;
  19755. }
  19756. // Approximate a curved face with recursively sub-divided triangles.
  19757. function make( v1, v2, v3 ) {
  19758. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19759. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19760. face.normal.copy( face.centroid ).normalize();
  19761. that.faces.push( face );
  19762. var azi = azimuth( face.centroid );
  19763. that.faceVertexUvs[ 0 ].push( [
  19764. correctUV( v1.uv, v1, azi ),
  19765. correctUV( v2.uv, v2, azi ),
  19766. correctUV( v3.uv, v3, azi )
  19767. ] );
  19768. }
  19769. // Analytically subdivide a face to the required detail level.
  19770. function subdivide(face, detail ) {
  19771. var cols = Math.pow(2, detail);
  19772. var cells = Math.pow(4, detail);
  19773. var a = prepare( that.vertices[ face.a ] );
  19774. var b = prepare( that.vertices[ face.b ] );
  19775. var c = prepare( that.vertices[ face.c ] );
  19776. var v = [];
  19777. // Construct all of the vertices for this subdivision.
  19778. for ( var i = 0 ; i <= cols; i ++ ) {
  19779. v[ i ] = [];
  19780. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19781. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19782. var rows = cols - i;
  19783. for ( var j = 0; j <= rows; j ++) {
  19784. if ( j == 0 && i == cols ) {
  19785. v[ i ][ j ] = aj;
  19786. } else {
  19787. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19788. }
  19789. }
  19790. }
  19791. // Construct all of the faces.
  19792. for ( var i = 0; i < cols ; i ++ ) {
  19793. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19794. var k = Math.floor( j / 2 );
  19795. if ( j % 2 == 0 ) {
  19796. make(
  19797. v[ i ][ k + 1],
  19798. v[ i + 1 ][ k ],
  19799. v[ i ][ k ]
  19800. );
  19801. } else {
  19802. make(
  19803. v[ i ][ k + 1 ],
  19804. v[ i + 1][ k + 1],
  19805. v[ i + 1 ][ k ]
  19806. );
  19807. }
  19808. }
  19809. }
  19810. }
  19811. // Angle around the Y axis, counter-clockwise when looking from above.
  19812. function azimuth( vector ) {
  19813. return Math.atan2( vector.z, -vector.x );
  19814. }
  19815. // Angle above the XZ plane.
  19816. function inclination( vector ) {
  19817. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19818. }
  19819. // Texture fixing helper. Spheres have some odd behaviours.
  19820. function correctUV( uv, vector, azimuth ) {
  19821. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19822. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19823. return uv;
  19824. }
  19825. this.computeCentroids();
  19826. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19827. };
  19828. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19829. /**
  19830. * @author timothypratley / https://github.com/timothypratley
  19831. */
  19832. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19833. this.radius = radius;
  19834. this.detail = detail;
  19835. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19836. var vertices = [
  19837. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19838. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19839. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19840. ];
  19841. var faces = [
  19842. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19843. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19844. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19845. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19846. ];
  19847. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19848. };
  19849. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19850. /**
  19851. * @author timothypratley / https://github.com/timothypratley
  19852. */
  19853. THREE.OctahedronGeometry = function ( radius, detail ) {
  19854. var vertices = [
  19855. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19856. ];
  19857. var faces = [
  19858. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19859. ];
  19860. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19861. };
  19862. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19863. /**
  19864. * @author timothypratley / https://github.com/timothypratley
  19865. */
  19866. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19867. var vertices = [
  19868. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19869. ];
  19870. var faces = [
  19871. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19872. ];
  19873. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19874. };
  19875. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19876. /**
  19877. * @author zz85 / https://github.com/zz85
  19878. * Parametric Surfaces Geometry
  19879. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19880. *
  19881. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19882. *
  19883. */
  19884. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19885. THREE.Geometry.call( this );
  19886. var verts = this.vertices;
  19887. var faces = this.faces;
  19888. var uvs = this.faceVertexUvs[ 0 ];
  19889. useTris = (useTris === undefined) ? false : useTris;
  19890. var i, il, j, p;
  19891. var u, v;
  19892. var stackCount = stacks + 1;
  19893. var sliceCount = slices + 1;
  19894. for ( i = 0; i <= stacks; i ++ ) {
  19895. v = i / stacks;
  19896. for ( j = 0; j <= slices; j ++ ) {
  19897. u = j / slices;
  19898. p = func( u, v );
  19899. verts.push( p );
  19900. }
  19901. }
  19902. var a, b, c, d;
  19903. var uva, uvb, uvc, uvd;
  19904. for ( i = 0; i < stacks; i ++ ) {
  19905. for ( j = 0; j < slices; j ++ ) {
  19906. a = i * sliceCount + j;
  19907. b = i * sliceCount + j + 1;
  19908. c = (i + 1) * sliceCount + j;
  19909. d = (i + 1) * sliceCount + j + 1;
  19910. uva = new THREE.Vector2( j / slices, i / stacks );
  19911. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19912. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19913. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19914. if ( useTris ) {
  19915. faces.push( new THREE.Face3( a, b, c ) );
  19916. faces.push( new THREE.Face3( b, d, c ) );
  19917. uvs.push( [ uva, uvb, uvc ] );
  19918. uvs.push( [ uvb, uvd, uvc ] );
  19919. } else {
  19920. faces.push( new THREE.Face4( a, b, d, c ) );
  19921. uvs.push( [ uva, uvb, uvd, uvc ] );
  19922. }
  19923. }
  19924. }
  19925. // console.log(this);
  19926. // magic bullet
  19927. // var diff = this.mergeVertices();
  19928. // console.log('removed ', diff, ' vertices by merging');
  19929. this.computeCentroids();
  19930. this.computeFaceNormals();
  19931. this.computeVertexNormals();
  19932. };
  19933. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19934. /**
  19935. * @author qiao / https://github.com/qiao
  19936. * @fileoverview This is a convex hull generator using the incremental method.
  19937. * The complexity is O(n^2) where n is the number of vertices.
  19938. * O(nlogn) algorithms do exist, but they are much more complicated.
  19939. *
  19940. * Benchmark:
  19941. *
  19942. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19943. *
  19944. * Num Vertices Time(ms)
  19945. *
  19946. * 10 1
  19947. * 20 3
  19948. * 30 19
  19949. * 40 48
  19950. * 50 107
  19951. */
  19952. THREE.ConvexGeometry = function( vertices ) {
  19953. THREE.Geometry.call( this );
  19954. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19955. for ( var i = 3; i < vertices.length; i++ ) {
  19956. addPoint( i );
  19957. }
  19958. function addPoint( vertexId ) {
  19959. var vertex = vertices[ vertexId ].clone();
  19960. var mag = vertex.length();
  19961. vertex.x += mag * randomOffset();
  19962. vertex.y += mag * randomOffset();
  19963. vertex.z += mag * randomOffset();
  19964. var hole = [];
  19965. for ( var f = 0; f < faces.length; ) {
  19966. var face = faces[ f ];
  19967. // for each face, if the vertex can see it,
  19968. // then we try to add the face's edges into the hole.
  19969. if ( visible( face, vertex ) ) {
  19970. for ( var e = 0; e < 3; e++ ) {
  19971. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19972. var boundary = true;
  19973. // remove duplicated edges.
  19974. for ( var h = 0; h < hole.length; h++ ) {
  19975. if ( equalEdge( hole[ h ], edge ) ) {
  19976. hole[ h ] = hole[ hole.length - 1 ];
  19977. hole.pop();
  19978. boundary = false;
  19979. break;
  19980. }
  19981. }
  19982. if ( boundary ) {
  19983. hole.push( edge );
  19984. }
  19985. }
  19986. // remove faces[ f ]
  19987. faces[ f ] = faces[ faces.length - 1 ];
  19988. faces.pop();
  19989. } else { // not visible
  19990. f++;
  19991. }
  19992. }
  19993. // construct the new faces formed by the edges of the hole and the vertex
  19994. for ( var h = 0; h < hole.length; h++ ) {
  19995. faces.push( [
  19996. hole[ h ][ 0 ],
  19997. hole[ h ][ 1 ],
  19998. vertexId
  19999. ] );
  20000. }
  20001. }
  20002. /**
  20003. * Whether the face is visible from the vertex
  20004. */
  20005. function visible( face, vertex ) {
  20006. var va = vertices[ face[ 0 ] ];
  20007. var vb = vertices[ face[ 1 ] ];
  20008. var vc = vertices[ face[ 2 ] ];
  20009. var n = normal( va, vb, vc );
  20010. // distance from face to origin
  20011. var dist = n.dot( va );
  20012. return n.dot( vertex ) >= dist;
  20013. }
  20014. /**
  20015. * Face normal
  20016. */
  20017. function normal( va, vb, vc ) {
  20018. var cb = new THREE.Vector3();
  20019. var ab = new THREE.Vector3();
  20020. cb.subVectors( vc, vb );
  20021. ab.subVectors( va, vb );
  20022. cb.cross( ab );
  20023. cb.normalize();
  20024. return cb;
  20025. }
  20026. /**
  20027. * Detect whether two edges are equal.
  20028. * Note that when constructing the convex hull, two same edges can only
  20029. * be of the negative direction.
  20030. */
  20031. function equalEdge( ea, eb ) {
  20032. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20033. }
  20034. /**
  20035. * Create a random offset between -1e-6 and 1e-6.
  20036. */
  20037. function randomOffset() {
  20038. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20039. }
  20040. /**
  20041. * XXX: Not sure if this is the correct approach. Need someone to review.
  20042. */
  20043. function vertexUv( vertex ) {
  20044. var mag = vertex.length();
  20045. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20046. }
  20047. // Push vertices into `this.vertices`, skipping those inside the hull
  20048. var id = 0;
  20049. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20050. for ( var i = 0; i < faces.length; i++ ) {
  20051. var face = faces[ i ];
  20052. for ( var j = 0; j < 3; j++ ) {
  20053. if ( newId[ face[ j ] ] === undefined ) {
  20054. newId[ face[ j ] ] = id++;
  20055. this.vertices.push( vertices[ face[ j ] ] );
  20056. }
  20057. face[ j ] = newId[ face[ j ] ];
  20058. }
  20059. }
  20060. // Convert faces into instances of THREE.Face3
  20061. for ( var i = 0; i < faces.length; i++ ) {
  20062. this.faces.push( new THREE.Face3(
  20063. faces[ i ][ 0 ],
  20064. faces[ i ][ 1 ],
  20065. faces[ i ][ 2 ]
  20066. ) );
  20067. }
  20068. // Compute UVs
  20069. for ( var i = 0; i < this.faces.length; i++ ) {
  20070. var face = this.faces[ i ];
  20071. this.faceVertexUvs[ 0 ].push( [
  20072. vertexUv( this.vertices[ face.a ] ),
  20073. vertexUv( this.vertices[ face.b ] ),
  20074. vertexUv( this.vertices[ face.c ])
  20075. ] );
  20076. }
  20077. this.computeCentroids();
  20078. this.computeFaceNormals();
  20079. this.computeVertexNormals();
  20080. };
  20081. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20082. /**
  20083. * @author sroucheray / http://sroucheray.org/
  20084. * @author mrdoob / http://mrdoob.com/
  20085. */
  20086. THREE.AxisHelper = function ( size ) {
  20087. var geometry = new THREE.Geometry();
  20088. geometry.vertices.push(
  20089. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20090. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20091. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20092. );
  20093. geometry.colors.push(
  20094. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20095. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20096. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20097. );
  20098. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20099. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20100. };
  20101. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20102. /**
  20103. * @author WestLangley / http://github.com/WestLangley
  20104. * @author zz85 / https://github.com/zz85
  20105. * @author bhouston / https://exocortex.com
  20106. *
  20107. * Creates an arrow for visualizing directions
  20108. *
  20109. * Parameters:
  20110. * dir - Vector3
  20111. * origin - Vector3
  20112. * length - Number
  20113. * hex - color in hex value
  20114. */
  20115. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20116. THREE.Object3D.call( this );
  20117. if ( length === undefined ) length = 20;
  20118. if ( hex === undefined ) hex = 0xffff00;
  20119. var lineGeometry = new THREE.Geometry();
  20120. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20121. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20122. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20123. this.add( this.line );
  20124. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20125. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20126. this.cone.position.set( 0, 1, 0 );
  20127. this.add( this.cone );
  20128. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20129. this.setDirection( dir );
  20130. this.setLength( length );
  20131. };
  20132. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20133. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20134. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  20135. if ( d.y > 0.999 ) {
  20136. this.rotation.set( 0, 0, 0 );
  20137. } else if ( d.y < - 0.999 ) {
  20138. this.rotation.set( Math.PI, 0, 0 );
  20139. } else {
  20140. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  20141. var radians = Math.acos( d.y );
  20142. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  20143. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  20144. }
  20145. };
  20146. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20147. this.scale.set( length, length, length );
  20148. };
  20149. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20150. this.line.material.color.setHex( hex );
  20151. this.cone.material.color.setHex( hex );
  20152. };
  20153. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20154. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20155. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20156. /**
  20157. * @author alteredq / http://alteredqualia.com/
  20158. *
  20159. * - shows frustum, line of sight and up of the camera
  20160. * - suitable for fast updates
  20161. * - based on frustum visualization in lightgl.js shadowmap example
  20162. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20163. */
  20164. THREE.CameraHelper = function ( camera ) {
  20165. THREE.Line.call( this );
  20166. var scope = this;
  20167. this.geometry = new THREE.Geometry();
  20168. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20169. this.type = THREE.LinePieces;
  20170. this.matrixWorld = camera.matrixWorld;
  20171. this.matrixAutoUpdate = false;
  20172. this.pointMap = {};
  20173. // colors
  20174. var hexFrustum = 0xffaa00;
  20175. var hexCone = 0xff0000;
  20176. var hexUp = 0x00aaff;
  20177. var hexTarget = 0xffffff;
  20178. var hexCross = 0x333333;
  20179. // near
  20180. addLine( "n1", "n2", hexFrustum );
  20181. addLine( "n2", "n4", hexFrustum );
  20182. addLine( "n4", "n3", hexFrustum );
  20183. addLine( "n3", "n1", hexFrustum );
  20184. // far
  20185. addLine( "f1", "f2", hexFrustum );
  20186. addLine( "f2", "f4", hexFrustum );
  20187. addLine( "f4", "f3", hexFrustum );
  20188. addLine( "f3", "f1", hexFrustum );
  20189. // sides
  20190. addLine( "n1", "f1", hexFrustum );
  20191. addLine( "n2", "f2", hexFrustum );
  20192. addLine( "n3", "f3", hexFrustum );
  20193. addLine( "n4", "f4", hexFrustum );
  20194. // cone
  20195. addLine( "p", "n1", hexCone );
  20196. addLine( "p", "n2", hexCone );
  20197. addLine( "p", "n3", hexCone );
  20198. addLine( "p", "n4", hexCone );
  20199. // up
  20200. addLine( "u1", "u2", hexUp );
  20201. addLine( "u2", "u3", hexUp );
  20202. addLine( "u3", "u1", hexUp );
  20203. // target
  20204. addLine( "c", "t", hexTarget );
  20205. addLine( "p", "c", hexCross );
  20206. // cross
  20207. addLine( "cn1", "cn2", hexCross );
  20208. addLine( "cn3", "cn4", hexCross );
  20209. addLine( "cf1", "cf2", hexCross );
  20210. addLine( "cf3", "cf4", hexCross );
  20211. this.camera = camera;
  20212. function addLine( a, b, hex ) {
  20213. addPoint( a, hex );
  20214. addPoint( b, hex );
  20215. }
  20216. function addPoint( id, hex ) {
  20217. scope.geometry.vertices.push( new THREE.Vector3() );
  20218. scope.geometry.colors.push( new THREE.Color( hex ) );
  20219. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20220. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20221. }
  20222. this.update( camera );
  20223. };
  20224. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20225. THREE.CameraHelper.prototype.update = function () {
  20226. var scope = this;
  20227. var w = 1, h = 1;
  20228. // we need just camera projection matrix
  20229. // world matrix must be identity
  20230. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20231. // center / target
  20232. setPoint( "c", 0, 0, -1 );
  20233. setPoint( "t", 0, 0, 1 );
  20234. // near
  20235. setPoint( "n1", -w, -h, -1 );
  20236. setPoint( "n2", w, -h, -1 );
  20237. setPoint( "n3", -w, h, -1 );
  20238. setPoint( "n4", w, h, -1 );
  20239. // far
  20240. setPoint( "f1", -w, -h, 1 );
  20241. setPoint( "f2", w, -h, 1 );
  20242. setPoint( "f3", -w, h, 1 );
  20243. setPoint( "f4", w, h, 1 );
  20244. // up
  20245. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20246. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20247. setPoint( "u3", 0, h * 2, -1 );
  20248. // cross
  20249. setPoint( "cf1", -w, 0, 1 );
  20250. setPoint( "cf2", w, 0, 1 );
  20251. setPoint( "cf3", 0, -h, 1 );
  20252. setPoint( "cf4", 0, h, 1 );
  20253. setPoint( "cn1", -w, 0, -1 );
  20254. setPoint( "cn2", w, 0, -1 );
  20255. setPoint( "cn3", 0, -h, -1 );
  20256. setPoint( "cn4", 0, h, -1 );
  20257. function setPoint( point, x, y, z ) {
  20258. THREE.CameraHelper.__v.set( x, y, z );
  20259. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20260. var points = scope.pointMap[ point ];
  20261. if ( points !== undefined ) {
  20262. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20263. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20264. }
  20265. }
  20266. }
  20267. this.geometry.verticesNeedUpdate = true;
  20268. };
  20269. THREE.CameraHelper.__projector = new THREE.Projector();
  20270. THREE.CameraHelper.__v = new THREE.Vector3();
  20271. THREE.CameraHelper.__c = new THREE.Camera();
  20272. /**
  20273. * @author alteredq / http://alteredqualia.com/
  20274. * @author mrdoob / http://mrdoob.com/
  20275. */
  20276. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20277. THREE.Object3D.call( this );
  20278. this.light = light;
  20279. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20280. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20281. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20282. this.lightSphere = new THREE.Mesh( geometry, material );
  20283. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20284. this.lightSphere.matrixAutoUpdate = false;
  20285. this.add( this.lightSphere );
  20286. /*
  20287. this.targetSphere = new THREE.Mesh( geometry, material );
  20288. this.targetSphere.position = this.light.target.position;
  20289. this.add( this.targetSphere );
  20290. */
  20291. geometry = new THREE.Geometry();
  20292. geometry.vertices.push( this.light.position );
  20293. geometry.vertices.push( this.light.target.position );
  20294. geometry.computeLineDistances();
  20295. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20296. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20297. this.targetLine = new THREE.Line( geometry, material );
  20298. this.add( this.targetLine );
  20299. }
  20300. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20301. THREE.DirectionalLightHelper.prototype.update = function () {
  20302. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20303. this.targetLine.geometry.computeLineDistances();
  20304. this.targetLine.geometry.verticesNeedUpdate = true;
  20305. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20306. };
  20307. /**
  20308. * @author mrdoob / http://mrdoob.com/
  20309. */
  20310. THREE.GridHelper = function ( size, step ) {
  20311. var geometry = new THREE.Geometry();
  20312. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20313. var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0x888888 );
  20314. for ( var i = - size; i <= size; i += step ) {
  20315. geometry.vertices.push( new THREE.Vector3( -size, 0, i ) );
  20316. geometry.vertices.push( new THREE.Vector3( size, 0, i ) );
  20317. geometry.vertices.push( new THREE.Vector3( i, 0, -size ) );
  20318. geometry.vertices.push( new THREE.Vector3( i, 0, size ) );
  20319. var color = i === 0 ? color1 : color2;
  20320. geometry.colors.push( color, color, color, color );
  20321. }
  20322. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20323. };
  20324. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20325. /**
  20326. * @author alteredq / http://alteredqualia.com/
  20327. * @author mrdoob / http://mrdoob.com/
  20328. */
  20329. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20330. THREE.Object3D.call( this );
  20331. this.light = light;
  20332. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20333. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20334. for ( var i = 0, il = 8; i < il; i ++ ) {
  20335. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  20336. }
  20337. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20338. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  20339. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20340. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  20341. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  20342. this.lightSphere.position = light.position;
  20343. this.lightSphere.lookAt( new THREE.Vector3() );
  20344. this.add( this.lightSphere );
  20345. };
  20346. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20347. THREE.HemisphereLightHelper.prototype.update = function () {
  20348. this.lightSphere.lookAt( new THREE.Vector3() );
  20349. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20350. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20351. };
  20352. /**
  20353. * @author alteredq / http://alteredqualia.com/
  20354. * @author mrdoob / http://mrdoob.com/
  20355. */
  20356. THREE.PointLightHelper = function ( light, sphereSize ) {
  20357. THREE.Object3D.call( this );
  20358. this.light = light;
  20359. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20360. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20361. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20362. this.lightSphere = new THREE.Mesh( geometry, material );
  20363. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20364. this.lightSphere.matrixAutoUpdate = false;
  20365. this.add( this.lightSphere );
  20366. /*
  20367. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20368. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20369. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20370. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20371. var d = light.distance;
  20372. if ( d === 0.0 ) {
  20373. this.lightDistance.visible = false;
  20374. } else {
  20375. this.lightDistance.scale.set( d, d, d );
  20376. }
  20377. this.add( this.lightDistance );
  20378. */
  20379. };
  20380. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20381. THREE.PointLightHelper.prototype.update = function () {
  20382. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20383. /*
  20384. this.lightDistance.material.color.copy( this.color );
  20385. var d = this.light.distance;
  20386. if ( d === 0.0 ) {
  20387. this.lightDistance.visible = false;
  20388. } else {
  20389. this.lightDistance.visible = true;
  20390. this.lightDistance.scale.set( d, d, d );
  20391. }
  20392. */
  20393. };
  20394. /**
  20395. * @author alteredq / http://alteredqualia.com/
  20396. * @author mrdoob / http://mrdoob.com/
  20397. */
  20398. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20399. THREE.Object3D.call( this );
  20400. this.light = light;
  20401. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20402. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20403. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20404. this.lightSphere = new THREE.Mesh( geometry, material );
  20405. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20406. this.lightSphere.matrixAutoUpdate = false;
  20407. this.add( this.lightSphere );
  20408. geometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20409. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20410. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20411. material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20412. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20413. this.lightCone = new THREE.Mesh( geometry, material );
  20414. this.lightCone.position = this.light.position;
  20415. var coneLength = light.distance ? light.distance : 10000;
  20416. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20417. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20418. this.lightCone.lookAt( this.light.target.position );
  20419. this.add( this.lightCone );
  20420. };
  20421. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20422. THREE.SpotLightHelper.prototype.update = function () {
  20423. var coneLength = this.light.distance ? this.light.distance : 10000;
  20424. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20425. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20426. this.lightCone.lookAt( this.light.target.position );
  20427. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20428. this.lightCone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20429. };
  20430. /**
  20431. * @author alteredq / http://alteredqualia.com/
  20432. */
  20433. THREE.ImmediateRenderObject = function () {
  20434. THREE.Object3D.call( this );
  20435. this.render = function ( renderCallback ) { };
  20436. };
  20437. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20438. /**
  20439. * @author mikael emtinger / http://gomo.se/
  20440. * @author alteredq / http://alteredqualia.com/
  20441. */
  20442. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20443. THREE.Object3D.call( this );
  20444. this.lensFlares = [];
  20445. this.positionScreen = new THREE.Vector3();
  20446. this.customUpdateCallback = undefined;
  20447. if( texture !== undefined ) {
  20448. this.add( texture, size, distance, blending, color );
  20449. }
  20450. };
  20451. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20452. /*
  20453. * Add: adds another flare
  20454. */
  20455. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20456. if( size === undefined ) size = -1;
  20457. if( distance === undefined ) distance = 0;
  20458. if( opacity === undefined ) opacity = 1;
  20459. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20460. if( blending === undefined ) blending = THREE.NormalBlending;
  20461. distance = Math.min( distance, Math.max( 0, distance ) );
  20462. this.lensFlares.push( { texture: texture, // THREE.Texture
  20463. size: size, // size in pixels (-1 = use texture.width)
  20464. distance: distance, // distance (0-1) from light source (0=at light source)
  20465. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20466. scale: 1, // scale
  20467. rotation: 1, // rotation
  20468. opacity: opacity, // opacity
  20469. color: color, // color
  20470. blending: blending } ); // blending
  20471. };
  20472. /*
  20473. * Update lens flares update positions on all flares based on the screen position
  20474. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20475. */
  20476. THREE.LensFlare.prototype.updateLensFlares = function () {
  20477. var f, fl = this.lensFlares.length;
  20478. var flare;
  20479. var vecX = -this.positionScreen.x * 2;
  20480. var vecY = -this.positionScreen.y * 2;
  20481. for( f = 0; f < fl; f ++ ) {
  20482. flare = this.lensFlares[ f ];
  20483. flare.x = this.positionScreen.x + vecX * flare.distance;
  20484. flare.y = this.positionScreen.y + vecY * flare.distance;
  20485. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20486. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20487. }
  20488. };
  20489. /**
  20490. * @author alteredq / http://alteredqualia.com/
  20491. */
  20492. THREE.MorphBlendMesh = function( geometry, material ) {
  20493. THREE.Mesh.call( this, geometry, material );
  20494. this.animationsMap = {};
  20495. this.animationsList = [];
  20496. // prepare default animation
  20497. // (all frames played together in 1 second)
  20498. var numFrames = this.geometry.morphTargets.length;
  20499. var name = "__default";
  20500. var startFrame = 0;
  20501. var endFrame = numFrames - 1;
  20502. var fps = numFrames / 1;
  20503. this.createAnimation( name, startFrame, endFrame, fps );
  20504. this.setAnimationWeight( name, 1 );
  20505. };
  20506. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20507. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20508. var animation = {
  20509. startFrame: start,
  20510. endFrame: end,
  20511. length: end - start + 1,
  20512. fps: fps,
  20513. duration: ( end - start ) / fps,
  20514. lastFrame: 0,
  20515. currentFrame: 0,
  20516. active: false,
  20517. time: 0,
  20518. direction: 1,
  20519. weight: 1,
  20520. directionBackwards: false,
  20521. mirroredLoop: false
  20522. };
  20523. this.animationsMap[ name ] = animation;
  20524. this.animationsList.push( animation );
  20525. };
  20526. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20527. var pattern = /([a-z]+)(\d+)/;
  20528. var firstAnimation, frameRanges = {};
  20529. var geometry = this.geometry;
  20530. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20531. var morph = geometry.morphTargets[ i ];
  20532. var chunks = morph.name.match( pattern );
  20533. if ( chunks && chunks.length > 1 ) {
  20534. var name = chunks[ 1 ];
  20535. var num = chunks[ 2 ];
  20536. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20537. var range = frameRanges[ name ];
  20538. if ( i < range.start ) range.start = i;
  20539. if ( i > range.end ) range.end = i;
  20540. if ( ! firstAnimation ) firstAnimation = name;
  20541. }
  20542. }
  20543. for ( var name in frameRanges ) {
  20544. var range = frameRanges[ name ];
  20545. this.createAnimation( name, range.start, range.end, fps );
  20546. }
  20547. this.firstAnimation = firstAnimation;
  20548. };
  20549. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20550. var animation = this.animationsMap[ name ];
  20551. if ( animation ) {
  20552. animation.direction = 1;
  20553. animation.directionBackwards = false;
  20554. }
  20555. };
  20556. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20557. var animation = this.animationsMap[ name ];
  20558. if ( animation ) {
  20559. animation.direction = -1;
  20560. animation.directionBackwards = true;
  20561. }
  20562. };
  20563. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20564. var animation = this.animationsMap[ name ];
  20565. if ( animation ) {
  20566. animation.fps = fps;
  20567. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20568. }
  20569. };
  20570. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20571. var animation = this.animationsMap[ name ];
  20572. if ( animation ) {
  20573. animation.duration = duration;
  20574. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20575. }
  20576. };
  20577. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20578. var animation = this.animationsMap[ name ];
  20579. if ( animation ) {
  20580. animation.weight = weight;
  20581. }
  20582. };
  20583. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20584. var animation = this.animationsMap[ name ];
  20585. if ( animation ) {
  20586. animation.time = time;
  20587. }
  20588. };
  20589. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20590. var time = 0;
  20591. var animation = this.animationsMap[ name ];
  20592. if ( animation ) {
  20593. time = animation.time;
  20594. }
  20595. return time;
  20596. };
  20597. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20598. var duration = -1;
  20599. var animation = this.animationsMap[ name ];
  20600. if ( animation ) {
  20601. duration = animation.duration;
  20602. }
  20603. return duration;
  20604. };
  20605. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20606. var animation = this.animationsMap[ name ];
  20607. if ( animation ) {
  20608. animation.time = 0;
  20609. animation.active = true;
  20610. } else {
  20611. console.warn( "animation[" + name + "] undefined" );
  20612. }
  20613. };
  20614. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20615. var animation = this.animationsMap[ name ];
  20616. if ( animation ) {
  20617. animation.active = false;
  20618. }
  20619. };
  20620. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20621. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20622. var animation = this.animationsList[ i ];
  20623. if ( ! animation.active ) continue;
  20624. var frameTime = animation.duration / animation.length;
  20625. animation.time += animation.direction * delta;
  20626. if ( animation.mirroredLoop ) {
  20627. if ( animation.time > animation.duration || animation.time < 0 ) {
  20628. animation.direction *= -1;
  20629. if ( animation.time > animation.duration ) {
  20630. animation.time = animation.duration;
  20631. animation.directionBackwards = true;
  20632. }
  20633. if ( animation.time < 0 ) {
  20634. animation.time = 0;
  20635. animation.directionBackwards = false;
  20636. }
  20637. }
  20638. } else {
  20639. animation.time = animation.time % animation.duration;
  20640. if ( animation.time < 0 ) animation.time += animation.duration;
  20641. }
  20642. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20643. var weight = animation.weight;
  20644. if ( keyframe !== animation.currentFrame ) {
  20645. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20646. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20647. this.morphTargetInfluences[ keyframe ] = 0;
  20648. animation.lastFrame = animation.currentFrame;
  20649. animation.currentFrame = keyframe;
  20650. }
  20651. var mix = ( animation.time % frameTime ) / frameTime;
  20652. if ( animation.directionBackwards ) mix = 1 - mix;
  20653. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20654. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20655. }
  20656. };
  20657. /**
  20658. * @author mikael emtinger / http://gomo.se/
  20659. * @author alteredq / http://alteredqualia.com/
  20660. */
  20661. THREE.LensFlarePlugin = function () {
  20662. var _gl, _renderer, _precision, _lensFlare = {};
  20663. this.init = function ( renderer ) {
  20664. _gl = renderer.context;
  20665. _renderer = renderer;
  20666. _precision = renderer.getPrecision();
  20667. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20668. _lensFlare.faces = new Uint16Array( 6 );
  20669. var i = 0;
  20670. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20671. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20672. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20673. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20674. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20675. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20676. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20677. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20678. i = 0;
  20679. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20680. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20681. // buffers
  20682. _lensFlare.vertexBuffer = _gl.createBuffer();
  20683. _lensFlare.elementBuffer = _gl.createBuffer();
  20684. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20685. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20686. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20687. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20688. // textures
  20689. _lensFlare.tempTexture = _gl.createTexture();
  20690. _lensFlare.occlusionTexture = _gl.createTexture();
  20691. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20692. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20693. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20694. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20695. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20696. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20697. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20698. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20699. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20700. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20701. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20702. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20703. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20704. _lensFlare.hasVertexTexture = false;
  20705. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20706. } else {
  20707. _lensFlare.hasVertexTexture = true;
  20708. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20709. }
  20710. _lensFlare.attributes = {};
  20711. _lensFlare.uniforms = {};
  20712. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20713. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20714. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20715. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20716. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20717. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20718. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20719. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20720. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20721. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20722. };
  20723. /*
  20724. * Render lens flares
  20725. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20726. * reads these back and calculates occlusion.
  20727. * Then _lensFlare.update_lensFlares() is called to re-position and
  20728. * update transparency of flares. Then they are rendered.
  20729. *
  20730. */
  20731. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20732. var flares = scene.__webglFlares,
  20733. nFlares = flares.length;
  20734. if ( ! nFlares ) return;
  20735. var tempPosition = new THREE.Vector3();
  20736. var invAspect = viewportHeight / viewportWidth,
  20737. halfViewportWidth = viewportWidth * 0.5,
  20738. halfViewportHeight = viewportHeight * 0.5;
  20739. var size = 16 / viewportHeight,
  20740. scale = new THREE.Vector2( size * invAspect, size );
  20741. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20742. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20743. var uniforms = _lensFlare.uniforms,
  20744. attributes = _lensFlare.attributes;
  20745. // set _lensFlare program and reset blending
  20746. _gl.useProgram( _lensFlare.program );
  20747. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20748. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20749. // loop through all lens flares to update their occlusion and positions
  20750. // setup gl and common used attribs/unforms
  20751. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20752. _gl.uniform1i( uniforms.map, 1 );
  20753. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20754. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20755. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20756. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20757. _gl.disable( _gl.CULL_FACE );
  20758. _gl.depthMask( false );
  20759. var i, j, jl, flare, sprite;
  20760. for ( i = 0; i < nFlares; i ++ ) {
  20761. size = 16 / viewportHeight;
  20762. scale.set( size * invAspect, size );
  20763. // calc object screen position
  20764. flare = flares[ i ];
  20765. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20766. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20767. tempPosition.applyProjection( camera.projectionMatrix );
  20768. // setup arrays for gl programs
  20769. screenPosition.copy( tempPosition )
  20770. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20771. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20772. // screen cull
  20773. if ( _lensFlare.hasVertexTexture || (
  20774. screenPositionPixels.x > 0 &&
  20775. screenPositionPixels.x < viewportWidth &&
  20776. screenPositionPixels.y > 0 &&
  20777. screenPositionPixels.y < viewportHeight ) ) {
  20778. // save current RGB to temp texture
  20779. _gl.activeTexture( _gl.TEXTURE1 );
  20780. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20781. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20782. // render pink quad
  20783. _gl.uniform1i( uniforms.renderType, 0 );
  20784. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20785. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20786. _gl.disable( _gl.BLEND );
  20787. _gl.enable( _gl.DEPTH_TEST );
  20788. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20789. // copy result to occlusionMap
  20790. _gl.activeTexture( _gl.TEXTURE0 );
  20791. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20792. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20793. // restore graphics
  20794. _gl.uniform1i( uniforms.renderType, 1 );
  20795. _gl.disable( _gl.DEPTH_TEST );
  20796. _gl.activeTexture( _gl.TEXTURE1 );
  20797. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20798. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20799. // update object positions
  20800. flare.positionScreen.copy( screenPosition )
  20801. if ( flare.customUpdateCallback ) {
  20802. flare.customUpdateCallback( flare );
  20803. } else {
  20804. flare.updateLensFlares();
  20805. }
  20806. // render flares
  20807. _gl.uniform1i( uniforms.renderType, 2 );
  20808. _gl.enable( _gl.BLEND );
  20809. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20810. sprite = flare.lensFlares[ j ];
  20811. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20812. screenPosition.x = sprite.x;
  20813. screenPosition.y = sprite.y;
  20814. screenPosition.z = sprite.z;
  20815. size = sprite.size * sprite.scale / viewportHeight;
  20816. scale.x = size * invAspect;
  20817. scale.y = size;
  20818. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20819. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20820. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20821. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20822. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20823. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20824. _renderer.setTexture( sprite.texture, 1 );
  20825. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20826. }
  20827. }
  20828. }
  20829. }
  20830. // restore gl
  20831. _gl.enable( _gl.CULL_FACE );
  20832. _gl.enable( _gl.DEPTH_TEST );
  20833. _gl.depthMask( true );
  20834. };
  20835. function createProgram ( shader, precision ) {
  20836. var program = _gl.createProgram();
  20837. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20838. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20839. var prefix = "precision " + precision + " float;\n";
  20840. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20841. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20842. _gl.compileShader( fragmentShader );
  20843. _gl.compileShader( vertexShader );
  20844. _gl.attachShader( program, fragmentShader );
  20845. _gl.attachShader( program, vertexShader );
  20846. _gl.linkProgram( program );
  20847. return program;
  20848. };
  20849. };
  20850. /**
  20851. * @author alteredq / http://alteredqualia.com/
  20852. */
  20853. THREE.ShadowMapPlugin = function () {
  20854. var _gl,
  20855. _renderer,
  20856. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20857. _frustum = new THREE.Frustum(),
  20858. _projScreenMatrix = new THREE.Matrix4(),
  20859. _min = new THREE.Vector3(),
  20860. _max = new THREE.Vector3(),
  20861. _matrixPosition = new THREE.Vector3();
  20862. this.init = function ( renderer ) {
  20863. _gl = renderer.context;
  20864. _renderer = renderer;
  20865. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20866. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20867. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20868. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20869. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20870. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20871. _depthMaterial._shadowPass = true;
  20872. _depthMaterialMorph._shadowPass = true;
  20873. _depthMaterialSkin._shadowPass = true;
  20874. _depthMaterialMorphSkin._shadowPass = true;
  20875. };
  20876. this.render = function ( scene, camera ) {
  20877. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20878. this.update( scene, camera );
  20879. };
  20880. this.update = function ( scene, camera ) {
  20881. var i, il, j, jl, n,
  20882. shadowMap, shadowMatrix, shadowCamera,
  20883. program, buffer, material,
  20884. webglObject, object, light,
  20885. renderList,
  20886. lights = [],
  20887. k = 0,
  20888. fog = null;
  20889. // set GL state for depth map
  20890. _gl.clearColor( 1, 1, 1, 1 );
  20891. _gl.disable( _gl.BLEND );
  20892. _gl.enable( _gl.CULL_FACE );
  20893. _gl.frontFace( _gl.CCW );
  20894. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20895. _gl.cullFace( _gl.FRONT );
  20896. } else {
  20897. _gl.cullFace( _gl.BACK );
  20898. }
  20899. _renderer.setDepthTest( true );
  20900. // preprocess lights
  20901. // - skip lights that are not casting shadows
  20902. // - create virtual lights for cascaded shadow maps
  20903. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20904. light = scene.__lights[ i ];
  20905. if ( ! light.castShadow ) continue;
  20906. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20907. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20908. var virtualLight;
  20909. if ( ! light.shadowCascadeArray[ n ] ) {
  20910. virtualLight = createVirtualLight( light, n );
  20911. virtualLight.originalCamera = camera;
  20912. var gyro = new THREE.Gyroscope();
  20913. gyro.position = light.shadowCascadeOffset;
  20914. gyro.add( virtualLight );
  20915. gyro.add( virtualLight.target );
  20916. camera.add( gyro );
  20917. light.shadowCascadeArray[ n ] = virtualLight;
  20918. console.log( "Created virtualLight", virtualLight );
  20919. } else {
  20920. virtualLight = light.shadowCascadeArray[ n ];
  20921. }
  20922. updateVirtualLight( light, n );
  20923. lights[ k ] = virtualLight;
  20924. k ++;
  20925. }
  20926. } else {
  20927. lights[ k ] = light;
  20928. k ++;
  20929. }
  20930. }
  20931. // render depth map
  20932. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20933. light = lights[ i ];
  20934. if ( ! light.shadowMap ) {
  20935. var shadowFilter = THREE.LinearFilter;
  20936. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20937. shadowFilter = THREE.NearestFilter;
  20938. }
  20939. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20940. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20941. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20942. light.shadowMatrix = new THREE.Matrix4();
  20943. }
  20944. if ( ! light.shadowCamera ) {
  20945. if ( light instanceof THREE.SpotLight ) {
  20946. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20947. } else if ( light instanceof THREE.DirectionalLight ) {
  20948. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20949. } else {
  20950. console.error( "Unsupported light type for shadow" );
  20951. continue;
  20952. }
  20953. scene.add( light.shadowCamera );
  20954. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20955. }
  20956. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20957. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20958. light.shadowCamera.add( light.cameraHelper );
  20959. }
  20960. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20961. updateShadowCamera( camera, light );
  20962. }
  20963. shadowMap = light.shadowMap;
  20964. shadowMatrix = light.shadowMatrix;
  20965. shadowCamera = light.shadowCamera;
  20966. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  20967. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  20968. shadowCamera.lookAt( _matrixPosition );
  20969. shadowCamera.updateMatrixWorld();
  20970. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20971. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20972. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20973. // compute shadow matrix
  20974. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20975. 0.0, 0.5, 0.0, 0.5,
  20976. 0.0, 0.0, 0.5, 0.5,
  20977. 0.0, 0.0, 0.0, 1.0 );
  20978. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20979. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20980. // update camera matrices and frustum
  20981. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20982. _frustum.setFromMatrix( _projScreenMatrix );
  20983. // render shadow map
  20984. _renderer.setRenderTarget( shadowMap );
  20985. _renderer.clear();
  20986. // set object matrices & frustum culling
  20987. renderList = scene.__webglObjects;
  20988. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20989. webglObject = renderList[ j ];
  20990. object = webglObject.object;
  20991. webglObject.render = false;
  20992. if ( object.visible && object.castShadow ) {
  20993. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20994. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20995. webglObject.render = true;
  20996. }
  20997. }
  20998. }
  20999. // render regular objects
  21000. var objectMaterial, useMorphing, useSkinning;
  21001. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21002. webglObject = renderList[ j ];
  21003. if ( webglObject.render ) {
  21004. object = webglObject.object;
  21005. buffer = webglObject.buffer;
  21006. // culling is overriden globally for all objects
  21007. // while rendering depth map
  21008. // need to deal with MeshFaceMaterial somehow
  21009. // in that case just use the first of material.materials for now
  21010. // (proper solution would require to break objects by materials
  21011. // similarly to regular rendering and then set corresponding
  21012. // depth materials per each chunk instead of just once per object)
  21013. objectMaterial = getObjectMaterial( object );
  21014. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21015. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21016. if ( object.customDepthMaterial ) {
  21017. material = object.customDepthMaterial;
  21018. } else if ( useSkinning ) {
  21019. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21020. } else if ( useMorphing ) {
  21021. material = _depthMaterialMorph;
  21022. } else {
  21023. material = _depthMaterial;
  21024. }
  21025. if ( buffer instanceof THREE.BufferGeometry ) {
  21026. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21027. } else {
  21028. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21029. }
  21030. }
  21031. }
  21032. // set matrices and render immediate objects
  21033. renderList = scene.__webglObjectsImmediate;
  21034. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21035. webglObject = renderList[ j ];
  21036. object = webglObject.object;
  21037. if ( object.visible && object.castShadow ) {
  21038. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21039. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21040. }
  21041. }
  21042. }
  21043. // restore GL state
  21044. var clearColor = _renderer.getClearColor(),
  21045. clearAlpha = _renderer.getClearAlpha();
  21046. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21047. _gl.enable( _gl.BLEND );
  21048. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21049. _gl.cullFace( _gl.BACK );
  21050. }
  21051. };
  21052. function createVirtualLight( light, cascade ) {
  21053. var virtualLight = new THREE.DirectionalLight();
  21054. virtualLight.isVirtual = true;
  21055. virtualLight.onlyShadow = true;
  21056. virtualLight.castShadow = true;
  21057. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21058. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21059. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21060. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21061. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21062. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21063. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21064. virtualLight.shadowDarkness = light.shadowDarkness;
  21065. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21066. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21067. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21068. virtualLight.pointsWorld = [];
  21069. virtualLight.pointsFrustum = [];
  21070. var pointsWorld = virtualLight.pointsWorld,
  21071. pointsFrustum = virtualLight.pointsFrustum;
  21072. for ( var i = 0; i < 8; i ++ ) {
  21073. pointsWorld[ i ] = new THREE.Vector3();
  21074. pointsFrustum[ i ] = new THREE.Vector3();
  21075. }
  21076. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21077. var farZ = light.shadowCascadeFarZ[ cascade ];
  21078. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21079. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21080. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21081. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21082. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21083. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21084. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21085. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21086. return virtualLight;
  21087. }
  21088. // Synchronize virtual light with the original light
  21089. function updateVirtualLight( light, cascade ) {
  21090. var virtualLight = light.shadowCascadeArray[ cascade ];
  21091. virtualLight.position.copy( light.position );
  21092. virtualLight.target.position.copy( light.target.position );
  21093. virtualLight.lookAt( virtualLight.target );
  21094. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21095. virtualLight.shadowDarkness = light.shadowDarkness;
  21096. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21097. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21098. var farZ = light.shadowCascadeFarZ[ cascade ];
  21099. var pointsFrustum = virtualLight.pointsFrustum;
  21100. pointsFrustum[ 0 ].z = nearZ;
  21101. pointsFrustum[ 1 ].z = nearZ;
  21102. pointsFrustum[ 2 ].z = nearZ;
  21103. pointsFrustum[ 3 ].z = nearZ;
  21104. pointsFrustum[ 4 ].z = farZ;
  21105. pointsFrustum[ 5 ].z = farZ;
  21106. pointsFrustum[ 6 ].z = farZ;
  21107. pointsFrustum[ 7 ].z = farZ;
  21108. }
  21109. // Fit shadow camera's ortho frustum to camera frustum
  21110. function updateShadowCamera( camera, light ) {
  21111. var shadowCamera = light.shadowCamera,
  21112. pointsFrustum = light.pointsFrustum,
  21113. pointsWorld = light.pointsWorld;
  21114. _min.set( Infinity, Infinity, Infinity );
  21115. _max.set( -Infinity, -Infinity, -Infinity );
  21116. for ( var i = 0; i < 8; i ++ ) {
  21117. var p = pointsWorld[ i ];
  21118. p.copy( pointsFrustum[ i ] );
  21119. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21120. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21121. if ( p.x < _min.x ) _min.x = p.x;
  21122. if ( p.x > _max.x ) _max.x = p.x;
  21123. if ( p.y < _min.y ) _min.y = p.y;
  21124. if ( p.y > _max.y ) _max.y = p.y;
  21125. if ( p.z < _min.z ) _min.z = p.z;
  21126. if ( p.z > _max.z ) _max.z = p.z;
  21127. }
  21128. shadowCamera.left = _min.x;
  21129. shadowCamera.right = _max.x;
  21130. shadowCamera.top = _max.y;
  21131. shadowCamera.bottom = _min.y;
  21132. // can't really fit near/far
  21133. //shadowCamera.near = _min.z;
  21134. //shadowCamera.far = _max.z;
  21135. shadowCamera.updateProjectionMatrix();
  21136. }
  21137. // For the moment just ignore objects that have multiple materials with different animation methods
  21138. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21139. function getObjectMaterial( object ) {
  21140. return object.material instanceof THREE.MeshFaceMaterial
  21141. ? object.material.materials[ 0 ]
  21142. : object.material;
  21143. };
  21144. };
  21145. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21146. /**
  21147. * @author mikael emtinger / http://gomo.se/
  21148. * @author alteredq / http://alteredqualia.com/
  21149. */
  21150. THREE.SpritePlugin = function () {
  21151. var _gl, _renderer, _precision, _sprite = {};
  21152. this.init = function ( renderer ) {
  21153. _gl = renderer.context;
  21154. _renderer = renderer;
  21155. _precision = renderer.getPrecision();
  21156. _sprite.vertices = new Float32Array( 8 + 8 );
  21157. _sprite.faces = new Uint16Array( 6 );
  21158. var i = 0;
  21159. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21160. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21161. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21162. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21163. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21164. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21165. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21166. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21167. i = 0;
  21168. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21169. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21170. _sprite.vertexBuffer = _gl.createBuffer();
  21171. _sprite.elementBuffer = _gl.createBuffer();
  21172. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21173. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21174. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21175. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21176. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21177. _sprite.attributes = {};
  21178. _sprite.uniforms = {};
  21179. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21180. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21181. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21182. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21183. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21184. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21185. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21186. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21187. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21188. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21189. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21190. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21191. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21192. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21193. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21194. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21195. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21196. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21197. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21198. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21199. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21200. };
  21201. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21202. var sprites = scene.__webglSprites,
  21203. nSprites = sprites.length;
  21204. if ( ! nSprites ) return;
  21205. var attributes = _sprite.attributes,
  21206. uniforms = _sprite.uniforms;
  21207. var invAspect = viewportHeight / viewportWidth;
  21208. var halfViewportWidth = viewportWidth * 0.5,
  21209. halfViewportHeight = viewportHeight * 0.5;
  21210. // setup gl
  21211. _gl.useProgram( _sprite.program );
  21212. _gl.enableVertexAttribArray( attributes.position );
  21213. _gl.enableVertexAttribArray( attributes.uv );
  21214. _gl.disable( _gl.CULL_FACE );
  21215. _gl.enable( _gl.BLEND );
  21216. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21217. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21218. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21219. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21220. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21221. _gl.activeTexture( _gl.TEXTURE0 );
  21222. _gl.uniform1i( uniforms.map, 0 );
  21223. var oldFogType = 0;
  21224. var sceneFogType = 0;
  21225. var fog = scene.fog;
  21226. if ( fog ) {
  21227. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21228. if ( fog instanceof THREE.Fog ) {
  21229. _gl.uniform1f( uniforms.fogNear, fog.near );
  21230. _gl.uniform1f( uniforms.fogFar, fog.far );
  21231. _gl.uniform1i( uniforms.fogType, 1 );
  21232. oldFogType = 1;
  21233. sceneFogType = 1;
  21234. } else if ( fog instanceof THREE.FogExp2 ) {
  21235. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21236. _gl.uniform1i( uniforms.fogType, 2 );
  21237. oldFogType = 2;
  21238. sceneFogType = 2;
  21239. }
  21240. } else {
  21241. _gl.uniform1i( uniforms.fogType, 0 );
  21242. oldFogType = 0;
  21243. sceneFogType = 0;
  21244. }
  21245. // update positions and sort
  21246. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21247. for( i = 0; i < nSprites; i ++ ) {
  21248. sprite = sprites[ i ];
  21249. material = sprite.material;
  21250. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21251. if ( ! material.useScreenCoordinates ) {
  21252. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21253. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21254. } else {
  21255. sprite.z = - sprite.position.z;
  21256. }
  21257. }
  21258. sprites.sort( painterSortStable );
  21259. // render all sprites
  21260. for( i = 0; i < nSprites; i ++ ) {
  21261. sprite = sprites[ i ];
  21262. material = sprite.material;
  21263. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21264. if ( material.map && material.map.image && material.map.image.width ) {
  21265. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21266. if ( material.useScreenCoordinates === true ) {
  21267. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21268. _gl.uniform3f(
  21269. uniforms.screenPosition,
  21270. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21271. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21272. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21273. );
  21274. scale[ 0 ] = _renderer.devicePixelRatio;
  21275. scale[ 1 ] = _renderer.devicePixelRatio;
  21276. } else {
  21277. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21278. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21279. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21280. scale[ 0 ] = 1;
  21281. scale[ 1 ] = 1;
  21282. }
  21283. if ( scene.fog && material.fog ) {
  21284. fogType = sceneFogType;
  21285. } else {
  21286. fogType = 0;
  21287. }
  21288. if ( oldFogType !== fogType ) {
  21289. _gl.uniform1i( uniforms.fogType, fogType );
  21290. oldFogType = fogType;
  21291. }
  21292. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21293. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21294. scale[ 1 ] *= size * sprite.scale.y;
  21295. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21296. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21297. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21298. _gl.uniform1f( uniforms.opacity, material.opacity );
  21299. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21300. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21301. _gl.uniform2fv( uniforms.scale, scale );
  21302. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21303. _renderer.setDepthTest( material.depthTest );
  21304. _renderer.setDepthWrite( material.depthWrite );
  21305. _renderer.setTexture( material.map, 0 );
  21306. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21307. }
  21308. }
  21309. // restore gl
  21310. _gl.enable( _gl.CULL_FACE );
  21311. };
  21312. function createProgram ( shader, precision ) {
  21313. var program = _gl.createProgram();
  21314. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21315. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21316. var prefix = "precision " + precision + " float;\n";
  21317. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21318. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21319. _gl.compileShader( fragmentShader );
  21320. _gl.compileShader( vertexShader );
  21321. _gl.attachShader( program, fragmentShader );
  21322. _gl.attachShader( program, vertexShader );
  21323. _gl.linkProgram( program );
  21324. return program;
  21325. };
  21326. function painterSortStable ( a, b ) {
  21327. if ( a.z !== b.z ) {
  21328. return b.z - a.z;
  21329. } else {
  21330. return b.id - a.id;
  21331. }
  21332. };
  21333. };
  21334. /**
  21335. * @author alteredq / http://alteredqualia.com/
  21336. */
  21337. THREE.DepthPassPlugin = function () {
  21338. this.enabled = false;
  21339. this.renderTarget = null;
  21340. var _gl,
  21341. _renderer,
  21342. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21343. _frustum = new THREE.Frustum(),
  21344. _projScreenMatrix = new THREE.Matrix4();
  21345. this.init = function ( renderer ) {
  21346. _gl = renderer.context;
  21347. _renderer = renderer;
  21348. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21349. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21350. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21351. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21352. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21353. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21354. _depthMaterial._shadowPass = true;
  21355. _depthMaterialMorph._shadowPass = true;
  21356. _depthMaterialSkin._shadowPass = true;
  21357. _depthMaterialMorphSkin._shadowPass = true;
  21358. };
  21359. this.render = function ( scene, camera ) {
  21360. if ( ! this.enabled ) return;
  21361. this.update( scene, camera );
  21362. };
  21363. this.update = function ( scene, camera ) {
  21364. var i, il, j, jl, n,
  21365. program, buffer, material,
  21366. webglObject, object, light,
  21367. renderList,
  21368. fog = null;
  21369. // set GL state for depth map
  21370. _gl.clearColor( 1, 1, 1, 1 );
  21371. _gl.disable( _gl.BLEND );
  21372. _renderer.setDepthTest( true );
  21373. // update scene
  21374. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21375. // update camera matrices and frustum
  21376. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21377. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21378. _frustum.setFromMatrix( _projScreenMatrix );
  21379. // render depth map
  21380. _renderer.setRenderTarget( this.renderTarget );
  21381. _renderer.clear();
  21382. // set object matrices & frustum culling
  21383. renderList = scene.__webglObjects;
  21384. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21385. webglObject = renderList[ j ];
  21386. object = webglObject.object;
  21387. webglObject.render = false;
  21388. if ( object.visible ) {
  21389. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21390. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21391. webglObject.render = true;
  21392. }
  21393. }
  21394. }
  21395. // render regular objects
  21396. var objectMaterial, useMorphing, useSkinning;
  21397. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21398. webglObject = renderList[ j ];
  21399. if ( webglObject.render ) {
  21400. object = webglObject.object;
  21401. buffer = webglObject.buffer;
  21402. // todo: create proper depth material for particles
  21403. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21404. objectMaterial = getObjectMaterial( object );
  21405. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21406. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21407. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21408. if ( object.customDepthMaterial ) {
  21409. material = object.customDepthMaterial;
  21410. } else if ( useSkinning ) {
  21411. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21412. } else if ( useMorphing ) {
  21413. material = _depthMaterialMorph;
  21414. } else {
  21415. material = _depthMaterial;
  21416. }
  21417. if ( buffer instanceof THREE.BufferGeometry ) {
  21418. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21419. } else {
  21420. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21421. }
  21422. }
  21423. }
  21424. // set matrices and render immediate objects
  21425. renderList = scene.__webglObjectsImmediate;
  21426. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21427. webglObject = renderList[ j ];
  21428. object = webglObject.object;
  21429. if ( object.visible ) {
  21430. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21431. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21432. }
  21433. }
  21434. // restore GL state
  21435. var clearColor = _renderer.getClearColor(),
  21436. clearAlpha = _renderer.getClearAlpha();
  21437. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21438. _gl.enable( _gl.BLEND );
  21439. };
  21440. // For the moment just ignore objects that have multiple materials with different animation methods
  21441. // Only the first material will be taken into account for deciding which depth material to use
  21442. function getObjectMaterial( object ) {
  21443. return object.material instanceof THREE.MeshFaceMaterial
  21444. ? object.material.materials[ 0 ]
  21445. : object.material;
  21446. };
  21447. };
  21448. /**
  21449. * @author mikael emtinger / http://gomo.se/
  21450. *
  21451. */
  21452. THREE.ShaderFlares = {
  21453. 'lensFlareVertexTexture': {
  21454. vertexShader: [
  21455. "uniform lowp int renderType;",
  21456. "uniform vec3 screenPosition;",
  21457. "uniform vec2 scale;",
  21458. "uniform float rotation;",
  21459. "uniform sampler2D occlusionMap;",
  21460. "attribute vec2 position;",
  21461. "attribute vec2 uv;",
  21462. "varying vec2 vUV;",
  21463. "varying float vVisibility;",
  21464. "void main() {",
  21465. "vUV = uv;",
  21466. "vec2 pos = position;",
  21467. "if( renderType == 2 ) {",
  21468. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21469. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21470. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21471. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21472. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21473. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21474. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21475. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21476. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21477. "vVisibility = ( visibility.r / 9.0 ) *",
  21478. "( 1.0 - visibility.g / 9.0 ) *",
  21479. "( visibility.b / 9.0 ) *",
  21480. "( 1.0 - visibility.a / 9.0 );",
  21481. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21482. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21483. "}",
  21484. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21485. "}"
  21486. ].join( "\n" ),
  21487. fragmentShader: [
  21488. "uniform lowp int renderType;",
  21489. "uniform sampler2D map;",
  21490. "uniform float opacity;",
  21491. "uniform vec3 color;",
  21492. "varying vec2 vUV;",
  21493. "varying float vVisibility;",
  21494. "void main() {",
  21495. // pink square
  21496. "if( renderType == 0 ) {",
  21497. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21498. // restore
  21499. "} else if( renderType == 1 ) {",
  21500. "gl_FragColor = texture2D( map, vUV );",
  21501. // flare
  21502. "} else {",
  21503. "vec4 texture = texture2D( map, vUV );",
  21504. "texture.a *= opacity * vVisibility;",
  21505. "gl_FragColor = texture;",
  21506. "gl_FragColor.rgb *= color;",
  21507. "}",
  21508. "}"
  21509. ].join( "\n" )
  21510. },
  21511. 'lensFlare': {
  21512. vertexShader: [
  21513. "uniform lowp int renderType;",
  21514. "uniform vec3 screenPosition;",
  21515. "uniform vec2 scale;",
  21516. "uniform float rotation;",
  21517. "attribute vec2 position;",
  21518. "attribute vec2 uv;",
  21519. "varying vec2 vUV;",
  21520. "void main() {",
  21521. "vUV = uv;",
  21522. "vec2 pos = position;",
  21523. "if( renderType == 2 ) {",
  21524. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21525. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21526. "}",
  21527. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21528. "}"
  21529. ].join( "\n" ),
  21530. fragmentShader: [
  21531. "precision mediump float;",
  21532. "uniform lowp int renderType;",
  21533. "uniform sampler2D map;",
  21534. "uniform sampler2D occlusionMap;",
  21535. "uniform float opacity;",
  21536. "uniform vec3 color;",
  21537. "varying vec2 vUV;",
  21538. "void main() {",
  21539. // pink square
  21540. "if( renderType == 0 ) {",
  21541. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21542. // restore
  21543. "} else if( renderType == 1 ) {",
  21544. "gl_FragColor = texture2D( map, vUV );",
  21545. // flare
  21546. "} else {",
  21547. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21548. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21549. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21550. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21551. "visibility = ( 1.0 - visibility / 4.0 );",
  21552. "vec4 texture = texture2D( map, vUV );",
  21553. "texture.a *= opacity * visibility;",
  21554. "gl_FragColor = texture;",
  21555. "gl_FragColor.rgb *= color;",
  21556. "}",
  21557. "}"
  21558. ].join( "\n" )
  21559. }
  21560. };
  21561. /**
  21562. * @author mikael emtinger / http://gomo.se/
  21563. * @author alteredq / http://alteredqualia.com/
  21564. *
  21565. */
  21566. THREE.ShaderSprite = {
  21567. 'sprite': {
  21568. vertexShader: [
  21569. "uniform int useScreenCoordinates;",
  21570. "uniform int sizeAttenuation;",
  21571. "uniform vec3 screenPosition;",
  21572. "uniform mat4 modelViewMatrix;",
  21573. "uniform mat4 projectionMatrix;",
  21574. "uniform float rotation;",
  21575. "uniform vec2 scale;",
  21576. "uniform vec2 alignment;",
  21577. "uniform vec2 uvOffset;",
  21578. "uniform vec2 uvScale;",
  21579. "attribute vec2 position;",
  21580. "attribute vec2 uv;",
  21581. "varying vec2 vUV;",
  21582. "void main() {",
  21583. "vUV = uvOffset + uv * uvScale;",
  21584. "vec2 alignedPosition = position + alignment;",
  21585. "vec2 rotatedPosition;",
  21586. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21587. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21588. "vec4 finalPosition;",
  21589. "if( useScreenCoordinates != 0 ) {",
  21590. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21591. "} else {",
  21592. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21593. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21594. "}",
  21595. "gl_Position = finalPosition;",
  21596. "}"
  21597. ].join( "\n" ),
  21598. fragmentShader: [
  21599. "uniform vec3 color;",
  21600. "uniform sampler2D map;",
  21601. "uniform float opacity;",
  21602. "uniform int fogType;",
  21603. "uniform vec3 fogColor;",
  21604. "uniform float fogDensity;",
  21605. "uniform float fogNear;",
  21606. "uniform float fogFar;",
  21607. "uniform float alphaTest;",
  21608. "varying vec2 vUV;",
  21609. "void main() {",
  21610. "vec4 texture = texture2D( map, vUV );",
  21611. "if ( texture.a < alphaTest ) discard;",
  21612. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21613. "if ( fogType > 0 ) {",
  21614. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21615. "float fogFactor = 0.0;",
  21616. "if ( fogType == 1 ) {",
  21617. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21618. "} else {",
  21619. "const float LOG2 = 1.442695;",
  21620. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21621. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21622. "}",
  21623. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21624. "}",
  21625. "}"
  21626. ].join( "\n" )
  21627. }
  21628. };