three.js 797 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '57dev' };
  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.extend( THREE.Color.prototype, {
  174. r: 1, g: 1, b: 1,
  175. set: function ( value ) {
  176. switch ( typeof value ) {
  177. case "number":
  178. this.setHex( value );
  179. break;
  180. case "string":
  181. this.setStyle( value );
  182. break;
  183. }
  184. },
  185. setHex: function ( hex ) {
  186. hex = Math.floor( hex );
  187. this.r = ( hex >> 16 & 255 ) / 255;
  188. this.g = ( hex >> 8 & 255 ) / 255;
  189. this.b = ( hex & 255 ) / 255;
  190. return this;
  191. },
  192. setRGB: function ( r, g, b ) {
  193. this.r = r;
  194. this.g = g;
  195. this.b = b;
  196. return this;
  197. },
  198. setHSV: function ( h, s, v ) {
  199. console.log( 'DEPRECATED: Color\'s .setHSV() will be removed. Use .setHSL( h, s, l ) instead.' );
  200. return this.setHSL(h,s*v/((h=(2-s)*v)<1?h:2-h),h/2); // https://gist.github.com/xpansive/1337890
  201. },
  202. setHSL: function ( h, s, l ) {
  203. // h,s,l ranges are in 0.0 - 1.0
  204. if ( s === 0 ) {
  205. this.r = this.g = this.b = l;
  206. } else {
  207. var hue2rgb = function ( p, q, t ) {
  208. if ( t < 0 ) t += 1;
  209. if ( t > 1 ) t -= 1;
  210. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  211. if ( t < 1 / 2 ) return q;
  212. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  213. return p;
  214. };
  215. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  216. var q = ( 2 * l ) - p;
  217. this.r = hue2rgb( q, p, h + 1 / 3 );
  218. this.g = hue2rgb( q, p, h );
  219. this.b = hue2rgb( q, p, h - 1 / 3 );
  220. }
  221. return this;
  222. },
  223. setStyle: function ( style ) {
  224. // rgb(255,0,0)
  225. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  226. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  227. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  228. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  229. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  230. return this;
  231. }
  232. // rgb(100%,0%,0%)
  233. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  234. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  235. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  236. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  237. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  238. return this;
  239. }
  240. // #ff0000
  241. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  242. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  243. this.setHex( parseInt( color[ 1 ], 16 ) );
  244. return this;
  245. }
  246. // #f00
  247. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  248. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  249. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  250. return this;
  251. }
  252. // red
  253. if ( /^(\w+)$/i.test( style ) ) {
  254. this.setHex( THREE.ColorKeywords[ style ] );
  255. return this;
  256. }
  257. },
  258. copy: function ( color ) {
  259. this.r = color.r;
  260. this.g = color.g;
  261. this.b = color.b;
  262. return this;
  263. },
  264. copyGammaToLinear: function ( color ) {
  265. this.r = color.r * color.r;
  266. this.g = color.g * color.g;
  267. this.b = color.b * color.b;
  268. return this;
  269. },
  270. copyLinearToGamma: function ( color ) {
  271. this.r = Math.sqrt( color.r );
  272. this.g = Math.sqrt( color.g );
  273. this.b = Math.sqrt( color.b );
  274. return this;
  275. },
  276. convertGammaToLinear: function () {
  277. var r = this.r, g = this.g, b = this.b;
  278. this.r = r * r;
  279. this.g = g * g;
  280. this.b = b * b;
  281. return this;
  282. },
  283. convertLinearToGamma: function () {
  284. this.r = Math.sqrt( this.r );
  285. this.g = Math.sqrt( this.g );
  286. this.b = Math.sqrt( this.b );
  287. return this;
  288. },
  289. getHex: function () {
  290. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  291. },
  292. getHexString: function () {
  293. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  294. },
  295. getHSL: function () {
  296. var hsl = { h: 0, s: 0, l: 0 };
  297. return function () {
  298. // h,s,l ranges are in 0.0 - 1.0
  299. var r = this.r, g = this.g, b = this.b;
  300. var max = Math.max( r, g, b );
  301. var min = Math.min( r, g, b );
  302. var hue, saturation;
  303. var lightness = ( min + max ) / 2.0;
  304. if ( min === max ) {
  305. hue = 0;
  306. saturation = 0;
  307. } else {
  308. var delta = max - min;
  309. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  310. switch ( max ) {
  311. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  312. case g: hue = ( b - r ) / delta + 2; break;
  313. case b: hue = ( r - g ) / delta + 4; break;
  314. }
  315. hue /= 6;
  316. }
  317. hsl.h = hue;
  318. hsl.s = saturation;
  319. hsl.l = lightness;
  320. return hsl;
  321. };
  322. }(),
  323. getStyle: function () {
  324. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  325. },
  326. offsetHSL: function ( h, s, l ) {
  327. var hsl = this.getHSL();
  328. hsl.h += h; hsl.s += s; hsl.l += l;
  329. this.setHSL( hsl.h, hsl.s, hsl.l );
  330. return this;
  331. },
  332. add: function ( color ) {
  333. this.r += color.r;
  334. this.g += color.g;
  335. this.b += color.b;
  336. return this;
  337. },
  338. addColors: function ( color1, color2 ) {
  339. this.r = color1.r + color2.r;
  340. this.g = color1.g + color2.g;
  341. this.b = color1.b + color2.b;
  342. return this;
  343. },
  344. addScalar: function ( s ) {
  345. this.r += s;
  346. this.g += s;
  347. this.b += s;
  348. return this;
  349. },
  350. multiply: function ( color ) {
  351. this.r *= color.r;
  352. this.g *= color.g;
  353. this.b *= color.b;
  354. return this;
  355. },
  356. multiplyScalar: function ( s ) {
  357. this.r *= s;
  358. this.g *= s;
  359. this.b *= s;
  360. return this;
  361. },
  362. lerp: function ( color, alpha ) {
  363. this.r += ( color.r - this.r ) * alpha;
  364. this.g += ( color.g - this.g ) * alpha;
  365. this.b += ( color.b - this.b ) * alpha;
  366. return this;
  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.extend( THREE.Quaternion.prototype, {
  409. set: function ( x, y, z, w ) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. this.w = w;
  414. return this;
  415. },
  416. copy: function ( q ) {
  417. this.x = q.x;
  418. this.y = q.y;
  419. this.z = q.z;
  420. this.w = q.w;
  421. return this;
  422. },
  423. setFromEuler: function ( v, order ) {
  424. // http://www.mathworks.com/matlabcentral/fileexchange/
  425. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  426. // content/SpinCalc.m
  427. var c1 = Math.cos( v.x / 2 );
  428. var c2 = Math.cos( v.y / 2 );
  429. var c3 = Math.cos( v.z / 2 );
  430. var s1 = Math.sin( v.x / 2 );
  431. var s2 = Math.sin( v.y / 2 );
  432. var s3 = Math.sin( v.z / 2 );
  433. if ( order === undefined || order === 'XYZ' ) {
  434. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  435. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  436. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  437. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  438. } else if ( order === 'YXZ' ) {
  439. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  440. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  441. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  442. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  443. } else if ( order === 'ZXY' ) {
  444. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  445. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  446. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  447. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  448. } else if ( order === 'ZYX' ) {
  449. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  450. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  451. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  452. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  453. } else if ( order === 'YZX' ) {
  454. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  455. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  456. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  457. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  458. } else if ( order === 'XZY' ) {
  459. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  460. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  461. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  462. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  463. }
  464. return this;
  465. },
  466. setFromAxisAngle: function ( axis, angle ) {
  467. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  468. // axis have to be normalized
  469. var halfAngle = angle / 2,
  470. s = Math.sin( halfAngle );
  471. this.x = axis.x * s;
  472. this.y = axis.y * s;
  473. this.z = axis.z * s;
  474. this.w = Math.cos( halfAngle );
  475. return this;
  476. },
  477. setFromRotationMatrix: function ( m ) {
  478. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  479. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  480. var te = m.elements,
  481. m11 = te[0], m12 = te[4], m13 = te[8],
  482. m21 = te[1], m22 = te[5], m23 = te[9],
  483. m31 = te[2], m32 = te[6], m33 = te[10],
  484. trace = m11 + m22 + m33,
  485. s;
  486. if ( trace > 0 ) {
  487. s = 0.5 / Math.sqrt( trace + 1.0 );
  488. this.w = 0.25 / s;
  489. this.x = ( m32 - m23 ) * s;
  490. this.y = ( m13 - m31 ) * s;
  491. this.z = ( m21 - m12 ) * s;
  492. } else if ( m11 > m22 && m11 > m33 ) {
  493. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  494. this.w = (m32 - m23 ) / s;
  495. this.x = 0.25 * s;
  496. this.y = (m12 + m21 ) / s;
  497. this.z = (m13 + m31 ) / s;
  498. } else if ( m22 > m33 ) {
  499. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  500. this.w = (m13 - m31 ) / s;
  501. this.x = (m12 + m21 ) / s;
  502. this.y = 0.25 * s;
  503. this.z = (m23 + m32 ) / s;
  504. } else {
  505. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  506. this.w = ( m21 - m12 ) / s;
  507. this.x = ( m13 + m31 ) / s;
  508. this.y = ( m23 + m32 ) / s;
  509. this.z = 0.25 * s;
  510. }
  511. return this;
  512. },
  513. inverse: function () {
  514. this.conjugate().normalize();
  515. return this;
  516. },
  517. conjugate: function () {
  518. this.x *= -1;
  519. this.y *= -1;
  520. this.z *= -1;
  521. return this;
  522. },
  523. lengthSq: function () {
  524. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  525. },
  526. length: function () {
  527. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  528. },
  529. normalize: function () {
  530. var l = this.length();
  531. if ( l === 0 ) {
  532. this.x = 0;
  533. this.y = 0;
  534. this.z = 0;
  535. this.w = 1;
  536. } else {
  537. l = 1 / l;
  538. this.x = this.x * l;
  539. this.y = this.y * l;
  540. this.z = this.z * l;
  541. this.w = this.w * l;
  542. }
  543. return this;
  544. },
  545. multiply: function ( q, p ) {
  546. if ( p !== undefined ) {
  547. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  548. return this.multiplyQuaternions( q, p );
  549. }
  550. return this.multiplyQuaternions( this, q );
  551. },
  552. multiplyQuaternions: function ( a, b ) {
  553. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  554. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  555. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  556. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  557. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  558. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  559. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  560. return this;
  561. },
  562. multiplyVector3: function ( vector ) {
  563. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  564. return vector.applyQuaternion( this );
  565. },
  566. slerp: function ( qb, t ) {
  567. var x = this.x, y = this.y, z = this.z, w = this.w;
  568. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  569. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  570. if ( cosHalfTheta < 0 ) {
  571. this.w = -qb.w;
  572. this.x = -qb.x;
  573. this.y = -qb.y;
  574. this.z = -qb.z;
  575. cosHalfTheta = -cosHalfTheta;
  576. } else {
  577. this.copy( qb );
  578. }
  579. if ( cosHalfTheta >= 1.0 ) {
  580. this.w = w;
  581. this.x = x;
  582. this.y = y;
  583. this.z = z;
  584. return this;
  585. }
  586. var halfTheta = Math.acos( cosHalfTheta );
  587. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  588. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  589. this.w = 0.5 * ( w + this.w );
  590. this.x = 0.5 * ( x + this.x );
  591. this.y = 0.5 * ( y + this.y );
  592. this.z = 0.5 * ( z + this.z );
  593. return this;
  594. }
  595. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  596. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  597. this.w = ( w * ratioA + this.w * ratioB );
  598. this.x = ( x * ratioA + this.x * ratioB );
  599. this.y = ( y * ratioA + this.y * ratioB );
  600. this.z = ( z * ratioA + this.z * ratioB );
  601. return this;
  602. },
  603. equals: function ( v ) {
  604. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  605. },
  606. clone: function () {
  607. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  608. }
  609. } );
  610. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  611. return qm.copy( qa ).slerp( qb, t );
  612. }
  613. /**
  614. * @author mrdoob / http://mrdoob.com/
  615. * @author philogb / http://blog.thejit.org/
  616. * @author egraether / http://egraether.com/
  617. * @author zz85 / http://www.lab4games.net/zz85/blog
  618. */
  619. THREE.Vector2 = function ( x, y ) {
  620. this.x = x || 0;
  621. this.y = y || 0;
  622. };
  623. THREE.extend( THREE.Vector2.prototype, {
  624. set: function ( x, y ) {
  625. this.x = x;
  626. this.y = y;
  627. return this;
  628. },
  629. setX: function ( x ) {
  630. this.x = x;
  631. return this;
  632. },
  633. setY: function ( y ) {
  634. this.y = y;
  635. return this;
  636. },
  637. setComponent: function ( index, value ) {
  638. switch ( index ) {
  639. case 0: this.x = value; break;
  640. case 1: this.y = value; break;
  641. default: throw new Error( "index is out of range: " + index );
  642. }
  643. },
  644. getComponent: function ( index ) {
  645. switch ( index ) {
  646. case 0: return this.x;
  647. case 1: return this.y;
  648. default: throw new Error( "index is out of range: " + index );
  649. }
  650. },
  651. copy: function ( v ) {
  652. this.x = v.x;
  653. this.y = v.y;
  654. return this;
  655. },
  656. add: function ( v, w ) {
  657. if ( w !== undefined ) {
  658. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  659. return this.addVectors( v, w );
  660. }
  661. this.x += v.x;
  662. this.y += v.y;
  663. return this;
  664. },
  665. addVectors: function ( a, b ) {
  666. this.x = a.x + b.x;
  667. this.y = a.y + b.y;
  668. return this;
  669. },
  670. addScalar: function ( s ) {
  671. this.x += s;
  672. this.y += s;
  673. return this;
  674. },
  675. sub: function ( v, w ) {
  676. if ( w !== undefined ) {
  677. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  678. return this.subVectors( v, w );
  679. }
  680. this.x -= v.x;
  681. this.y -= v.y;
  682. return this;
  683. },
  684. subVectors: function ( a, b ) {
  685. this.x = a.x - b.x;
  686. this.y = a.y - b.y;
  687. return this;
  688. },
  689. multiplyScalar: function ( s ) {
  690. this.x *= s;
  691. this.y *= s;
  692. return this;
  693. },
  694. divideScalar: function ( s ) {
  695. if ( s !== 0 ) {
  696. this.x /= s;
  697. this.y /= s;
  698. } else {
  699. this.set( 0, 0 );
  700. }
  701. return this;
  702. },
  703. min: function ( v ) {
  704. if ( this.x > v.x ) {
  705. this.x = v.x;
  706. }
  707. if ( this.y > v.y ) {
  708. this.y = v.y;
  709. }
  710. return this;
  711. },
  712. max: function ( v ) {
  713. if ( this.x < v.x ) {
  714. this.x = v.x;
  715. }
  716. if ( this.y < v.y ) {
  717. this.y = v.y;
  718. }
  719. return this;
  720. },
  721. clamp: function ( min, max ) {
  722. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  723. if ( this.x < min.x ) {
  724. this.x = min.x;
  725. } else if ( this.x > max.x ) {
  726. this.x = max.x;
  727. }
  728. if ( this.y < min.y ) {
  729. this.y = min.y;
  730. } else if ( this.y > max.y ) {
  731. this.y = max.y;
  732. }
  733. return this;
  734. },
  735. negate: function() {
  736. return this.multiplyScalar( - 1 );
  737. },
  738. dot: function ( v ) {
  739. return this.x * v.x + this.y * v.y;
  740. },
  741. lengthSq: function () {
  742. return this.x * this.x + this.y * this.y;
  743. },
  744. length: function () {
  745. return Math.sqrt( this.x * this.x + this.y * this.y );
  746. },
  747. normalize: function () {
  748. return this.divideScalar( this.length() );
  749. },
  750. distanceTo: function ( v ) {
  751. return Math.sqrt( this.distanceToSquared( v ) );
  752. },
  753. distanceToSquared: function ( v ) {
  754. var dx = this.x - v.x, dy = this.y - v.y;
  755. return dx * dx + dy * dy;
  756. },
  757. setLength: function ( l ) {
  758. var oldLength = this.length();
  759. if ( oldLength !== 0 && l !== oldLength ) {
  760. this.multiplyScalar( l / oldLength );
  761. }
  762. return this;
  763. },
  764. lerp: function ( v, alpha ) {
  765. this.x += ( v.x - this.x ) * alpha;
  766. this.y += ( v.y - this.y ) * alpha;
  767. return this;
  768. },
  769. equals: function( v ) {
  770. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  771. },
  772. toArray: function () {
  773. return [ this.x, this.y ];
  774. },
  775. clone: function () {
  776. return new THREE.Vector2( this.x, this.y );
  777. }
  778. } );
  779. /**
  780. * @author mrdoob / http://mrdoob.com/
  781. * @author *kile / http://kile.stravaganza.org/
  782. * @author philogb / http://blog.thejit.org/
  783. * @author mikael emtinger / http://gomo.se/
  784. * @author egraether / http://egraether.com/
  785. * @author WestLangley / http://github.com/WestLangley
  786. */
  787. THREE.Vector3 = function ( x, y, z ) {
  788. this.x = x || 0;
  789. this.y = y || 0;
  790. this.z = z || 0;
  791. };
  792. THREE.extend( THREE.Vector3.prototype, {
  793. set: function ( x, y, z ) {
  794. this.x = x;
  795. this.y = y;
  796. this.z = z;
  797. return this;
  798. },
  799. setX: function ( x ) {
  800. this.x = x;
  801. return this;
  802. },
  803. setY: function ( y ) {
  804. this.y = y;
  805. return this;
  806. },
  807. setZ: function ( z ) {
  808. this.z = z;
  809. return this;
  810. },
  811. setComponent: function ( index, value ) {
  812. switch ( index ) {
  813. case 0: this.x = value; break;
  814. case 1: this.y = value; break;
  815. case 2: this.z = value; break;
  816. default: throw new Error( "index is out of range: " + index );
  817. }
  818. },
  819. getComponent: function ( index ) {
  820. switch ( index ) {
  821. case 0: return this.x;
  822. case 1: return this.y;
  823. case 2: return this.z;
  824. default: throw new Error( "index is out of range: " + index );
  825. }
  826. },
  827. copy: function ( v ) {
  828. this.x = v.x;
  829. this.y = v.y;
  830. this.z = v.z;
  831. return this;
  832. },
  833. add: function ( v, w ) {
  834. if ( w !== undefined ) {
  835. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  836. return this.addVectors( v, w );
  837. }
  838. this.x += v.x;
  839. this.y += v.y;
  840. this.z += v.z;
  841. return this;
  842. },
  843. addScalar: function ( s ) {
  844. this.x += s;
  845. this.y += s;
  846. this.z += s;
  847. return this;
  848. },
  849. addVectors: function ( a, b ) {
  850. this.x = a.x + b.x;
  851. this.y = a.y + b.y;
  852. this.z = a.z + b.z;
  853. return this;
  854. },
  855. sub: function ( v, w ) {
  856. if ( w !== undefined ) {
  857. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  858. return this.subVectors( v, w );
  859. }
  860. this.x -= v.x;
  861. this.y -= v.y;
  862. this.z -= v.z;
  863. return this;
  864. },
  865. subVectors: function ( a, b ) {
  866. this.x = a.x - b.x;
  867. this.y = a.y - b.y;
  868. this.z = a.z - b.z;
  869. return this;
  870. },
  871. multiply: function ( v, w ) {
  872. if ( w !== undefined ) {
  873. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  874. return this.multiplyVectors( v, w );
  875. }
  876. this.x *= v.x;
  877. this.y *= v.y;
  878. this.z *= v.z;
  879. return this;
  880. },
  881. multiplyScalar: function ( s ) {
  882. this.x *= s;
  883. this.y *= s;
  884. this.z *= s;
  885. return this;
  886. },
  887. multiplyVectors: function ( a, b ) {
  888. this.x = a.x * b.x;
  889. this.y = a.y * b.y;
  890. this.z = a.z * b.z;
  891. return this;
  892. },
  893. applyMatrix3: function ( m ) {
  894. var x = this.x;
  895. var y = this.y;
  896. var z = this.z;
  897. var e = m.elements;
  898. this.x = e[0] * x + e[3] * y + e[6] * z;
  899. this.y = e[1] * x + e[4] * y + e[7] * z;
  900. this.z = e[2] * x + e[5] * y + e[8] * z;
  901. return this;
  902. },
  903. applyMatrix4: function ( m ) {
  904. // input: THREE.Matrix4 affine matrix
  905. var x = this.x, y = this.y, z = this.z;
  906. var e = m.elements;
  907. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  908. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  909. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  910. return this;
  911. },
  912. applyProjection: function ( m ) {
  913. // input: THREE.Matrix4 projection matrix
  914. var x = this.x, y = this.y, z = this.z;
  915. var e = m.elements;
  916. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  917. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  918. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  919. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  920. return this;
  921. },
  922. applyQuaternion: function ( q ) {
  923. var x = this.x;
  924. var y = this.y;
  925. var z = this.z;
  926. var qx = q.x;
  927. var qy = q.y;
  928. var qz = q.z;
  929. var qw = q.w;
  930. // calculate quat * vector
  931. var ix = qw * x + qy * z - qz * y;
  932. var iy = qw * y + qz * x - qx * z;
  933. var iz = qw * z + qx * y - qy * x;
  934. var iw = -qx * x - qy * y - qz * z;
  935. // calculate result * inverse quat
  936. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  937. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  938. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  939. return this;
  940. },
  941. applyEuler: function () {
  942. var q1 = new THREE.Quaternion();
  943. return function ( v, eulerOrder ) {
  944. var quaternion = q1.setFromEuler( v, eulerOrder );
  945. this.applyQuaternion( quaternion );
  946. return this;
  947. };
  948. }(),
  949. applyAxisAngle: function () {
  950. var q1 = new THREE.Quaternion();
  951. return function ( axis, angle ) {
  952. var quaternion = q1.setFromAxisAngle( axis, angle );
  953. this.applyQuaternion( quaternion );
  954. return this;
  955. };
  956. }(),
  957. transformDirection: function ( m ) {
  958. // input: THREE.Matrix4 affine matrix
  959. // vector interpreted as a direction
  960. var x = this.x, y = this.y, z = this.z;
  961. var e = m.elements;
  962. this.x = e[0] * x + e[4] * y + e[8] * z;
  963. this.y = e[1] * x + e[5] * y + e[9] * z;
  964. this.z = e[2] * x + e[6] * y + e[10] * z;
  965. this.normalize();
  966. return this;
  967. },
  968. divide: function ( v ) {
  969. this.x /= v.x;
  970. this.y /= v.y;
  971. this.z /= v.z;
  972. return this;
  973. },
  974. divideScalar: function ( s ) {
  975. if ( s !== 0 ) {
  976. this.x /= s;
  977. this.y /= s;
  978. this.z /= s;
  979. } else {
  980. this.x = 0;
  981. this.y = 0;
  982. this.z = 0;
  983. }
  984. return this;
  985. },
  986. min: function ( v ) {
  987. if ( this.x > v.x ) {
  988. this.x = v.x;
  989. }
  990. if ( this.y > v.y ) {
  991. this.y = v.y;
  992. }
  993. if ( this.z > v.z ) {
  994. this.z = v.z;
  995. }
  996. return this;
  997. },
  998. max: function ( v ) {
  999. if ( this.x < v.x ) {
  1000. this.x = v.x;
  1001. }
  1002. if ( this.y < v.y ) {
  1003. this.y = v.y;
  1004. }
  1005. if ( this.z < v.z ) {
  1006. this.z = v.z;
  1007. }
  1008. return this;
  1009. },
  1010. clamp: function ( min, max ) {
  1011. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1012. if ( this.x < min.x ) {
  1013. this.x = min.x;
  1014. } else if ( this.x > max.x ) {
  1015. this.x = max.x;
  1016. }
  1017. if ( this.y < min.y ) {
  1018. this.y = min.y;
  1019. } else if ( this.y > max.y ) {
  1020. this.y = max.y;
  1021. }
  1022. if ( this.z < min.z ) {
  1023. this.z = min.z;
  1024. } else if ( this.z > max.z ) {
  1025. this.z = max.z;
  1026. }
  1027. return this;
  1028. },
  1029. negate: function () {
  1030. return this.multiplyScalar( - 1 );
  1031. },
  1032. dot: function ( v ) {
  1033. return this.x * v.x + this.y * v.y + this.z * v.z;
  1034. },
  1035. lengthSq: function () {
  1036. return this.x * this.x + this.y * this.y + this.z * this.z;
  1037. },
  1038. length: function () {
  1039. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1040. },
  1041. lengthManhattan: function () {
  1042. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1043. },
  1044. normalize: function () {
  1045. return this.divideScalar( this.length() );
  1046. },
  1047. setLength: function ( l ) {
  1048. var oldLength = this.length();
  1049. if ( oldLength !== 0 && l !== oldLength ) {
  1050. this.multiplyScalar( l / oldLength );
  1051. }
  1052. return this;
  1053. },
  1054. lerp: function ( v, alpha ) {
  1055. this.x += ( v.x - this.x ) * alpha;
  1056. this.y += ( v.y - this.y ) * alpha;
  1057. this.z += ( v.z - this.z ) * alpha;
  1058. return this;
  1059. },
  1060. cross: function ( v, w ) {
  1061. if ( w !== undefined ) {
  1062. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1063. return this.crossVectors( v, w );
  1064. }
  1065. var x = this.x, y = this.y, z = this.z;
  1066. this.x = y * v.z - z * v.y;
  1067. this.y = z * v.x - x * v.z;
  1068. this.z = x * v.y - y * v.x;
  1069. return this;
  1070. },
  1071. crossVectors: function ( a, b ) {
  1072. this.x = a.y * b.z - a.z * b.y;
  1073. this.y = a.z * b.x - a.x * b.z;
  1074. this.z = a.x * b.y - a.y * b.x;
  1075. return this;
  1076. },
  1077. projectOnVector: function () {
  1078. var v1 = new THREE.Vector3();
  1079. return function( vector ) {
  1080. v1.copy( vector ).normalize();
  1081. var d = this.dot( v1 );
  1082. return this.copy( v1 ).multiplyScalar( d );
  1083. };
  1084. }(),
  1085. projectOnPlane: function () {
  1086. var v1 = new THREE.Vector3();
  1087. return function( planeNormal ) {
  1088. v1.copy( this ).projectOnVector( planeNormal );
  1089. return this.sub( v1 );
  1090. }
  1091. }(),
  1092. reflect: function () {
  1093. var v1 = new THREE.Vector3();
  1094. return function ( vector ) {
  1095. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1096. return this.subVectors( v1, this );
  1097. }
  1098. }(),
  1099. angleTo: function ( v ) {
  1100. var theta = this.dot( v ) / ( this.length() * v.length() );
  1101. // clamp, to handle numerical problems
  1102. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1103. },
  1104. distanceTo: function ( v ) {
  1105. return Math.sqrt( this.distanceToSquared( v ) );
  1106. },
  1107. distanceToSquared: function ( v ) {
  1108. var dx = this.x - v.x;
  1109. var dy = this.y - v.y;
  1110. var dz = this.z - v.z;
  1111. return dx * dx + dy * dy + dz * dz;
  1112. },
  1113. getPositionFromMatrix: function ( m ) {
  1114. this.x = m.elements[12];
  1115. this.y = m.elements[13];
  1116. this.z = m.elements[14];
  1117. return this;
  1118. },
  1119. setEulerFromRotationMatrix: function ( m, order ) {
  1120. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1121. // clamp, to handle numerical problems
  1122. function clamp( x ) {
  1123. return Math.min( Math.max( x, -1 ), 1 );
  1124. }
  1125. var te = m.elements;
  1126. var m11 = te[0], m12 = te[4], m13 = te[8];
  1127. var m21 = te[1], m22 = te[5], m23 = te[9];
  1128. var m31 = te[2], m32 = te[6], m33 = te[10];
  1129. if ( order === undefined || order === 'XYZ' ) {
  1130. this.y = Math.asin( clamp( m13 ) );
  1131. if ( Math.abs( m13 ) < 0.99999 ) {
  1132. this.x = Math.atan2( - m23, m33 );
  1133. this.z = Math.atan2( - m12, m11 );
  1134. } else {
  1135. this.x = Math.atan2( m32, m22 );
  1136. this.z = 0;
  1137. }
  1138. } else if ( order === 'YXZ' ) {
  1139. this.x = Math.asin( - clamp( m23 ) );
  1140. if ( Math.abs( m23 ) < 0.99999 ) {
  1141. this.y = Math.atan2( m13, m33 );
  1142. this.z = Math.atan2( m21, m22 );
  1143. } else {
  1144. this.y = Math.atan2( - m31, m11 );
  1145. this.z = 0;
  1146. }
  1147. } else if ( order === 'ZXY' ) {
  1148. this.x = Math.asin( clamp( m32 ) );
  1149. if ( Math.abs( m32 ) < 0.99999 ) {
  1150. this.y = Math.atan2( - m31, m33 );
  1151. this.z = Math.atan2( - m12, m22 );
  1152. } else {
  1153. this.y = 0;
  1154. this.z = Math.atan2( m21, m11 );
  1155. }
  1156. } else if ( order === 'ZYX' ) {
  1157. this.y = Math.asin( - clamp( m31 ) );
  1158. if ( Math.abs( m31 ) < 0.99999 ) {
  1159. this.x = Math.atan2( m32, m33 );
  1160. this.z = Math.atan2( m21, m11 );
  1161. } else {
  1162. this.x = 0;
  1163. this.z = Math.atan2( - m12, m22 );
  1164. }
  1165. } else if ( order === 'YZX' ) {
  1166. this.z = Math.asin( clamp( m21 ) );
  1167. if ( Math.abs( m21 ) < 0.99999 ) {
  1168. this.x = Math.atan2( - m23, m22 );
  1169. this.y = Math.atan2( - m31, m11 );
  1170. } else {
  1171. this.x = 0;
  1172. this.y = Math.atan2( m13, m33 );
  1173. }
  1174. } else if ( order === 'XZY' ) {
  1175. this.z = Math.asin( - clamp( m12 ) );
  1176. if ( Math.abs( m12 ) < 0.99999 ) {
  1177. this.x = Math.atan2( m32, m22 );
  1178. this.y = Math.atan2( m13, m11 );
  1179. } else {
  1180. this.x = Math.atan2( - m23, m33 );
  1181. this.y = 0;
  1182. }
  1183. }
  1184. return this;
  1185. },
  1186. setEulerFromQuaternion: function ( q, order ) {
  1187. // q is assumed to be normalized
  1188. // clamp, to handle numerical problems
  1189. function clamp( x ) {
  1190. return Math.min( Math.max( x, -1 ), 1 );
  1191. }
  1192. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1193. var sqx = q.x * q.x;
  1194. var sqy = q.y * q.y;
  1195. var sqz = q.z * q.z;
  1196. var sqw = q.w * q.w;
  1197. if ( order === undefined || order === 'XYZ' ) {
  1198. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1199. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1200. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1201. } else if ( order === 'YXZ' ) {
  1202. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1203. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1204. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1205. } else if ( order === 'ZXY' ) {
  1206. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1207. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1208. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1209. } else if ( order === 'ZYX' ) {
  1210. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1211. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1212. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1213. } else if ( order === 'YZX' ) {
  1214. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1215. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1216. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1217. } else if ( order === 'XZY' ) {
  1218. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1219. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1220. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1221. }
  1222. return this;
  1223. },
  1224. getScaleFromMatrix: function ( m ) {
  1225. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1226. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1227. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1228. this.x = sx;
  1229. this.y = sy;
  1230. this.z = sz;
  1231. return this;
  1232. },
  1233. equals: function ( v ) {
  1234. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1235. },
  1236. toArray: function () {
  1237. return [ this.x, this.y, this.z ];
  1238. },
  1239. clone: function () {
  1240. return new THREE.Vector3( this.x, this.y, this.z );
  1241. }
  1242. } );
  1243. /**
  1244. * @author supereggbert / http://www.paulbrunt.co.uk/
  1245. * @author philogb / http://blog.thejit.org/
  1246. * @author mikael emtinger / http://gomo.se/
  1247. * @author egraether / http://egraether.com/
  1248. * @author WestLangley / http://github.com/WestLangley
  1249. */
  1250. THREE.Vector4 = function ( x, y, z, w ) {
  1251. this.x = x || 0;
  1252. this.y = y || 0;
  1253. this.z = z || 0;
  1254. this.w = ( w !== undefined ) ? w : 1;
  1255. };
  1256. THREE.extend( THREE.Vector4.prototype, {
  1257. set: function ( x, y, z, w ) {
  1258. this.x = x;
  1259. this.y = y;
  1260. this.z = z;
  1261. this.w = w;
  1262. return this;
  1263. },
  1264. setX: function ( x ) {
  1265. this.x = x;
  1266. return this;
  1267. },
  1268. setY: function ( y ) {
  1269. this.y = y;
  1270. return this;
  1271. },
  1272. setZ: function ( z ) {
  1273. this.z = z;
  1274. return this;
  1275. },
  1276. setW: function ( w ) {
  1277. this.w = w;
  1278. return this;
  1279. },
  1280. setComponent: function ( index, value ) {
  1281. switch ( index ) {
  1282. case 0: this.x = value; break;
  1283. case 1: this.y = value; break;
  1284. case 2: this.z = value; break;
  1285. case 3: this.w = value; break;
  1286. default: throw new Error( "index is out of range: " + index );
  1287. }
  1288. },
  1289. getComponent: function ( index ) {
  1290. switch ( index ) {
  1291. case 0: return this.x;
  1292. case 1: return this.y;
  1293. case 2: return this.z;
  1294. case 3: return this.w;
  1295. default: throw new Error( "index is out of range: " + index );
  1296. }
  1297. },
  1298. copy: function ( v ) {
  1299. this.x = v.x;
  1300. this.y = v.y;
  1301. this.z = v.z;
  1302. this.w = ( v.w !== undefined ) ? v.w : 1;
  1303. return this;
  1304. },
  1305. add: function ( v, w ) {
  1306. if ( w !== undefined ) {
  1307. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1308. return this.addVectors( v, w );
  1309. }
  1310. this.x += v.x;
  1311. this.y += v.y;
  1312. this.z += v.z;
  1313. this.w += v.w;
  1314. return this;
  1315. },
  1316. addScalar: function ( s ) {
  1317. this.x += s;
  1318. this.y += s;
  1319. this.z += s;
  1320. this.w += s;
  1321. return this;
  1322. },
  1323. addVectors: function ( a, b ) {
  1324. this.x = a.x + b.x;
  1325. this.y = a.y + b.y;
  1326. this.z = a.z + b.z;
  1327. this.w = a.w + b.w;
  1328. return this;
  1329. },
  1330. sub: function ( v, w ) {
  1331. if ( w !== undefined ) {
  1332. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1333. return this.subVectors( 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. subVectors: function ( a, b ) {
  1342. this.x = a.x - b.x;
  1343. this.y = a.y - b.y;
  1344. this.z = a.z - b.z;
  1345. this.w = a.w - b.w;
  1346. return this;
  1347. },
  1348. multiplyScalar: function ( s ) {
  1349. this.x *= s;
  1350. this.y *= s;
  1351. this.z *= s;
  1352. this.w *= s;
  1353. return this;
  1354. },
  1355. applyMatrix4: function ( m ) {
  1356. var x = this.x;
  1357. var y = this.y;
  1358. var z = this.z;
  1359. var w = this.w;
  1360. var e = m.elements;
  1361. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1362. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1363. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1364. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1365. return this;
  1366. },
  1367. divideScalar: function ( s ) {
  1368. if ( s !== 0 ) {
  1369. this.x /= s;
  1370. this.y /= s;
  1371. this.z /= s;
  1372. this.w /= s;
  1373. } else {
  1374. this.x = 0;
  1375. this.y = 0;
  1376. this.z = 0;
  1377. this.w = 1;
  1378. }
  1379. return this;
  1380. },
  1381. setAxisAngleFromQuaternion: function ( q ) {
  1382. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1383. // q is assumed to be normalized
  1384. this.w = 2 * Math.acos( q.w );
  1385. var s = Math.sqrt( 1 - q.w * q.w );
  1386. if ( s < 0.0001 ) {
  1387. this.x = 1;
  1388. this.y = 0;
  1389. this.z = 0;
  1390. } else {
  1391. this.x = q.x / s;
  1392. this.y = q.y / s;
  1393. this.z = q.z / s;
  1394. }
  1395. return this;
  1396. },
  1397. setAxisAngleFromRotationMatrix: function ( m ) {
  1398. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1400. var angle, x, y, z, // variables for result
  1401. epsilon = 0.01, // margin to allow for rounding errors
  1402. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1403. te = m.elements,
  1404. m11 = te[0], m12 = te[4], m13 = te[8],
  1405. m21 = te[1], m22 = te[5], m23 = te[9],
  1406. m31 = te[2], m32 = te[6], m33 = te[10];
  1407. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1408. && ( Math.abs( m13 - m31 ) < epsilon )
  1409. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1410. // singularity found
  1411. // first check for identity matrix which must have +1 for all terms
  1412. // in leading diagonal and zero in other terms
  1413. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1414. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1415. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1416. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1417. // this singularity is identity matrix so angle = 0
  1418. this.set( 1, 0, 0, 0 );
  1419. return this; // zero angle, arbitrary axis
  1420. }
  1421. // otherwise this singularity is angle = 180
  1422. angle = Math.PI;
  1423. var xx = ( m11 + 1 ) / 2;
  1424. var yy = ( m22 + 1 ) / 2;
  1425. var zz = ( m33 + 1 ) / 2;
  1426. var xy = ( m12 + m21 ) / 4;
  1427. var xz = ( m13 + m31 ) / 4;
  1428. var yz = ( m23 + m32 ) / 4;
  1429. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1430. if ( xx < epsilon ) {
  1431. x = 0;
  1432. y = 0.707106781;
  1433. z = 0.707106781;
  1434. } else {
  1435. x = Math.sqrt( xx );
  1436. y = xy / x;
  1437. z = xz / x;
  1438. }
  1439. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1440. if ( yy < epsilon ) {
  1441. x = 0.707106781;
  1442. y = 0;
  1443. z = 0.707106781;
  1444. } else {
  1445. y = Math.sqrt( yy );
  1446. x = xy / y;
  1447. z = yz / y;
  1448. }
  1449. } else { // m33 is the largest diagonal term so base result on this
  1450. if ( zz < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0.707106781;
  1453. z = 0;
  1454. } else {
  1455. z = Math.sqrt( zz );
  1456. x = xz / z;
  1457. y = yz / z;
  1458. }
  1459. }
  1460. this.set( x, y, z, angle );
  1461. return this; // return 180 deg rotation
  1462. }
  1463. // as we have reached here there are no singularities so we can handle normally
  1464. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1465. + ( m13 - m31 ) * ( m13 - m31 )
  1466. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1467. if ( Math.abs( s ) < 0.001 ) s = 1;
  1468. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1469. // caught by singularity test above, but I've left it in just in case
  1470. this.x = ( m32 - m23 ) / s;
  1471. this.y = ( m13 - m31 ) / s;
  1472. this.z = ( m21 - m12 ) / s;
  1473. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1474. return this;
  1475. },
  1476. min: function ( v ) {
  1477. if ( this.x > v.x ) {
  1478. this.x = v.x;
  1479. }
  1480. if ( this.y > v.y ) {
  1481. this.y = v.y;
  1482. }
  1483. if ( this.z > v.z ) {
  1484. this.z = v.z;
  1485. }
  1486. if ( this.w > v.w ) {
  1487. this.w = v.w;
  1488. }
  1489. return this;
  1490. },
  1491. max: function ( v ) {
  1492. if ( this.x < v.x ) {
  1493. this.x = v.x;
  1494. }
  1495. if ( this.y < v.y ) {
  1496. this.y = v.y;
  1497. }
  1498. if ( this.z < v.z ) {
  1499. this.z = v.z;
  1500. }
  1501. if ( this.w < v.w ) {
  1502. this.w = v.w;
  1503. }
  1504. return this;
  1505. },
  1506. clamp: function ( min, max ) {
  1507. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1508. if ( this.x < min.x ) {
  1509. this.x = min.x;
  1510. } else if ( this.x > max.x ) {
  1511. this.x = max.x;
  1512. }
  1513. if ( this.y < min.y ) {
  1514. this.y = min.y;
  1515. } else if ( this.y > max.y ) {
  1516. this.y = max.y;
  1517. }
  1518. if ( this.z < min.z ) {
  1519. this.z = min.z;
  1520. } else if ( this.z > max.z ) {
  1521. this.z = max.z;
  1522. }
  1523. if ( this.w < min.w ) {
  1524. this.w = min.w;
  1525. } else if ( this.w > max.w ) {
  1526. this.w = max.w;
  1527. }
  1528. return this;
  1529. },
  1530. negate: function() {
  1531. return this.multiplyScalar( -1 );
  1532. },
  1533. dot: function ( v ) {
  1534. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1535. },
  1536. lengthSq: function () {
  1537. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1538. },
  1539. length: function () {
  1540. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1541. },
  1542. lengthManhattan: function () {
  1543. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1544. },
  1545. normalize: function () {
  1546. return this.divideScalar( this.length() );
  1547. },
  1548. setLength: function ( l ) {
  1549. var oldLength = this.length();
  1550. if ( oldLength !== 0 && l !== oldLength ) {
  1551. this.multiplyScalar( l / oldLength );
  1552. }
  1553. return this;
  1554. },
  1555. lerp: function ( v, alpha ) {
  1556. this.x += ( v.x - this.x ) * alpha;
  1557. this.y += ( v.y - this.y ) * alpha;
  1558. this.z += ( v.z - this.z ) * alpha;
  1559. this.w += ( v.w - this.w ) * alpha;
  1560. return this;
  1561. },
  1562. equals: function ( v ) {
  1563. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1564. },
  1565. toArray: function () {
  1566. return [ this.x, this.y, this.z, this.w ];
  1567. },
  1568. clone: function () {
  1569. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1570. }
  1571. } );
  1572. /**
  1573. * @author bhouston / http://exocortex.com
  1574. */
  1575. THREE.Line3 = function ( start, end ) {
  1576. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1577. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1578. };
  1579. THREE.extend( THREE.Line3.prototype, {
  1580. set: function ( start, end ) {
  1581. this.start.copy( start );
  1582. this.end.copy( end );
  1583. return this;
  1584. },
  1585. copy: function ( line ) {
  1586. this.start.copy( line.start );
  1587. this.end.copy( line.end );
  1588. return this;
  1589. },
  1590. center: function ( optionalTarget ) {
  1591. var result = optionalTarget || new THREE.Vector3();
  1592. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1593. },
  1594. delta: function ( optionalTarget ) {
  1595. var result = optionalTarget || new THREE.Vector3();
  1596. return result.subVectors( this.end, this.start );
  1597. },
  1598. distanceSq: function () {
  1599. return this.start.distanceToSquared( this.end );
  1600. },
  1601. distance: function () {
  1602. return this.start.distanceTo( this.end );
  1603. },
  1604. at: function ( t, optionalTarget ) {
  1605. var result = optionalTarget || new THREE.Vector3();
  1606. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1607. },
  1608. closestPointToPointParameter: function() {
  1609. var startP = new THREE.Vector3();
  1610. var startEnd = new THREE.Vector3();
  1611. return function ( point, clampToLine ) {
  1612. startP.subVectors( point, this.start );
  1613. startEnd.subVectors( this.end, this.start );
  1614. var startEnd2 = startEnd.dot( startEnd );
  1615. var startEnd_startP = startEnd.dot( startP );
  1616. var t = startEnd_startP / startEnd2;
  1617. if( clampToLine ) {
  1618. t = THREE.Math.clamp( t, 0, 1 );
  1619. }
  1620. return t;
  1621. };
  1622. }(),
  1623. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1624. var t = this.closestPointToPointParameter( point, clampToLine );
  1625. var result = optionalTarget || new THREE.Vector3();
  1626. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1627. },
  1628. applyMatrix4: function ( matrix ) {
  1629. this.start.applyMatrix4( matrix );
  1630. this.end.applyMatrix4( matrix );
  1631. return this;
  1632. },
  1633. equals: function ( line ) {
  1634. return line.start.equals( this.start ) && line.end.equals( this.end );
  1635. },
  1636. clone: function () {
  1637. return new THREE.Line3().copy( this );
  1638. }
  1639. } );
  1640. /**
  1641. * @author bhouston / http://exocortex.com
  1642. */
  1643. THREE.Box2 = function ( min, max ) {
  1644. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1645. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1646. };
  1647. THREE.extend( THREE.Box2.prototype, {
  1648. set: function ( min, max ) {
  1649. this.min.copy( min );
  1650. this.max.copy( max );
  1651. return this;
  1652. },
  1653. setFromPoints: function ( points ) {
  1654. if ( points.length > 0 ) {
  1655. var point = points[ 0 ];
  1656. this.min.copy( point );
  1657. this.max.copy( point );
  1658. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1659. point = points[ i ];
  1660. if ( point.x < this.min.x ) {
  1661. this.min.x = point.x;
  1662. } else if ( point.x > this.max.x ) {
  1663. this.max.x = point.x;
  1664. }
  1665. if ( point.y < this.min.y ) {
  1666. this.min.y = point.y;
  1667. } else if ( point.y > this.max.y ) {
  1668. this.max.y = point.y;
  1669. }
  1670. }
  1671. } else {
  1672. this.makeEmpty();
  1673. }
  1674. return this;
  1675. },
  1676. setFromCenterAndSize: function() {
  1677. var v1 = new THREE.Vector2();
  1678. return function ( center, size ) {
  1679. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1680. this.min.copy( center ).sub( halfSize );
  1681. this.max.copy( center ).add( halfSize );
  1682. return this;
  1683. };
  1684. }(),
  1685. copy: function ( box ) {
  1686. this.min.copy( box.min );
  1687. this.max.copy( box.max );
  1688. return this;
  1689. },
  1690. makeEmpty: function () {
  1691. this.min.x = this.min.y = Infinity;
  1692. this.max.x = this.max.y = -Infinity;
  1693. return this;
  1694. },
  1695. empty: function () {
  1696. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1697. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1698. },
  1699. center: function ( optionalTarget ) {
  1700. var result = optionalTarget || new THREE.Vector2();
  1701. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1702. },
  1703. size: function ( optionalTarget ) {
  1704. var result = optionalTarget || new THREE.Vector2();
  1705. return result.subVectors( this.max, this.min );
  1706. },
  1707. expandByPoint: function ( point ) {
  1708. this.min.min( point );
  1709. this.max.max( point );
  1710. return this;
  1711. },
  1712. expandByVector: function ( vector ) {
  1713. this.min.sub( vector );
  1714. this.max.add( vector );
  1715. return this;
  1716. },
  1717. expandByScalar: function ( scalar ) {
  1718. this.min.addScalar( -scalar );
  1719. this.max.addScalar( scalar );
  1720. return this;
  1721. },
  1722. containsPoint: function ( point ) {
  1723. if ( point.x < this.min.x || point.x > this.max.x ||
  1724. point.y < this.min.y || point.y > this.max.y ) {
  1725. return false;
  1726. }
  1727. return true;
  1728. },
  1729. containsBox: function ( box ) {
  1730. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1731. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1732. return true;
  1733. }
  1734. return false;
  1735. },
  1736. getParameter: function ( point ) {
  1737. // This can potentially have a divide by zero if the box
  1738. // has a size dimension of 0.
  1739. return new THREE.Vector2(
  1740. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1741. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1742. );
  1743. },
  1744. isIntersectionBox: function ( box ) {
  1745. // using 6 splitting planes to rule out intersections.
  1746. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1747. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1748. return false;
  1749. }
  1750. return true;
  1751. },
  1752. clampPoint: function ( point, optionalTarget ) {
  1753. var result = optionalTarget || new THREE.Vector2();
  1754. return result.copy( point ).clamp( this.min, this.max );
  1755. },
  1756. distanceToPoint: function() {
  1757. var v1 = new THREE.Vector2();
  1758. return function ( point ) {
  1759. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1760. return clampedPoint.sub( point ).length();
  1761. };
  1762. }(),
  1763. intersect: function ( box ) {
  1764. this.min.max( box.min );
  1765. this.max.min( box.max );
  1766. return this;
  1767. },
  1768. union: function ( box ) {
  1769. this.min.min( box.min );
  1770. this.max.max( box.max );
  1771. return this;
  1772. },
  1773. translate: function ( offset ) {
  1774. this.min.add( offset );
  1775. this.max.add( offset );
  1776. return this;
  1777. },
  1778. equals: function ( box ) {
  1779. return box.min.equals( this.min ) && box.max.equals( this.max );
  1780. },
  1781. clone: function () {
  1782. return new THREE.Box2().copy( this );
  1783. }
  1784. } );
  1785. /**
  1786. * @author bhouston / http://exocortex.com
  1787. */
  1788. THREE.Box3 = function ( min, max ) {
  1789. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1790. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1791. };
  1792. THREE.extend( THREE.Box3.prototype, {
  1793. set: function ( min, max ) {
  1794. this.min.copy( min );
  1795. this.max.copy( max );
  1796. return this;
  1797. },
  1798. setFromPoints: function ( points ) {
  1799. if ( points.length > 0 ) {
  1800. var point = points[ 0 ];
  1801. this.min.copy( point );
  1802. this.max.copy( point );
  1803. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1804. point = points[ i ];
  1805. if ( point.x < this.min.x ) {
  1806. this.min.x = point.x;
  1807. } else if ( point.x > this.max.x ) {
  1808. this.max.x = point.x;
  1809. }
  1810. if ( point.y < this.min.y ) {
  1811. this.min.y = point.y;
  1812. } else if ( point.y > this.max.y ) {
  1813. this.max.y = point.y;
  1814. }
  1815. if ( point.z < this.min.z ) {
  1816. this.min.z = point.z;
  1817. } else if ( point.z > this.max.z ) {
  1818. this.max.z = point.z;
  1819. }
  1820. }
  1821. } else {
  1822. this.makeEmpty();
  1823. }
  1824. return this;
  1825. },
  1826. setFromCenterAndSize: function() {
  1827. var v1 = new THREE.Vector3();
  1828. return function ( center, size ) {
  1829. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1830. this.min.copy( center ).sub( halfSize );
  1831. this.max.copy( center ).add( halfSize );
  1832. return this;
  1833. };
  1834. }(),
  1835. copy: function ( box ) {
  1836. this.min.copy( box.min );
  1837. this.max.copy( box.max );
  1838. return this;
  1839. },
  1840. makeEmpty: function () {
  1841. this.min.x = this.min.y = this.min.z = Infinity;
  1842. this.max.x = this.max.y = this.max.z = -Infinity;
  1843. return this;
  1844. },
  1845. empty: function () {
  1846. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1847. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1848. },
  1849. center: function ( optionalTarget ) {
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1852. },
  1853. size: function ( optionalTarget ) {
  1854. var result = optionalTarget || new THREE.Vector3();
  1855. return result.subVectors( this.max, this.min );
  1856. },
  1857. expandByPoint: function ( point ) {
  1858. this.min.min( point );
  1859. this.max.max( point );
  1860. return this;
  1861. },
  1862. expandByVector: function ( vector ) {
  1863. this.min.sub( vector );
  1864. this.max.add( vector );
  1865. return this;
  1866. },
  1867. expandByScalar: function ( scalar ) {
  1868. this.min.addScalar( -scalar );
  1869. this.max.addScalar( scalar );
  1870. return this;
  1871. },
  1872. containsPoint: function ( point ) {
  1873. if ( point.x < this.min.x || point.x > this.max.x ||
  1874. point.y < this.min.y || point.y > this.max.y ||
  1875. point.z < this.min.z || point.z > this.max.z ) {
  1876. return false;
  1877. }
  1878. return true;
  1879. },
  1880. containsBox: function ( box ) {
  1881. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1882. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1883. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1884. return true;
  1885. }
  1886. return false;
  1887. },
  1888. getParameter: function ( point ) {
  1889. // This can potentially have a divide by zero if the box
  1890. // has a size dimension of 0.
  1891. return new THREE.Vector3(
  1892. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1893. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1894. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1895. );
  1896. },
  1897. isIntersectionBox: function ( box ) {
  1898. // using 6 splitting planes to rule out intersections.
  1899. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1900. box.max.y < this.min.y || box.min.y > this.max.y ||
  1901. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1902. return false;
  1903. }
  1904. return true;
  1905. },
  1906. clampPoint: function ( point, optionalTarget ) {
  1907. var result = optionalTarget || new THREE.Vector3();
  1908. return result.copy( point ).clamp( this.min, this.max );
  1909. },
  1910. distanceToPoint: function() {
  1911. var v1 = new THREE.Vector3();
  1912. return function ( point ) {
  1913. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1914. return clampedPoint.sub( point ).length();
  1915. };
  1916. }(),
  1917. getBoundingSphere: function() {
  1918. var v1 = new THREE.Vector3();
  1919. return function ( optionalTarget ) {
  1920. var result = optionalTarget || new THREE.Sphere();
  1921. result.center = this.center();
  1922. result.radius = this.size( v1 ).length() * 0.5;
  1923. return result;
  1924. };
  1925. }(),
  1926. intersect: function ( box ) {
  1927. this.min.max( box.min );
  1928. this.max.min( box.max );
  1929. return this;
  1930. },
  1931. union: function ( box ) {
  1932. this.min.min( box.min );
  1933. this.max.max( box.max );
  1934. return this;
  1935. },
  1936. applyMatrix4: function() {
  1937. var points = [
  1938. new THREE.Vector3(),
  1939. new THREE.Vector3(),
  1940. new THREE.Vector3(),
  1941. new THREE.Vector3(),
  1942. new THREE.Vector3(),
  1943. new THREE.Vector3(),
  1944. new THREE.Vector3(),
  1945. new THREE.Vector3()
  1946. ];
  1947. return function ( matrix ) {
  1948. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1949. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1950. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1951. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1952. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1953. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1954. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1955. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1956. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1957. this.makeEmpty();
  1958. this.setFromPoints( points );
  1959. return this;
  1960. };
  1961. }(),
  1962. translate: function ( offset ) {
  1963. this.min.add( offset );
  1964. this.max.add( offset );
  1965. return this;
  1966. },
  1967. equals: function ( box ) {
  1968. return box.min.equals( this.min ) && box.max.equals( this.max );
  1969. },
  1970. clone: function () {
  1971. return new THREE.Box3().copy( this );
  1972. }
  1973. } );
  1974. /**
  1975. * @author alteredq / http://alteredqualia.com/
  1976. * @author WestLangley / http://github.com/WestLangley
  1977. * @author bhouston / http://exocortex.com
  1978. */
  1979. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1980. this.elements = new Float32Array(9);
  1981. this.set(
  1982. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1983. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1984. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1985. );
  1986. };
  1987. THREE.extend( THREE.Matrix3.prototype, {
  1988. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1989. var te = this.elements;
  1990. te[0] = n11; te[3] = n12; te[6] = n13;
  1991. te[1] = n21; te[4] = n22; te[7] = n23;
  1992. te[2] = n31; te[5] = n32; te[8] = n33;
  1993. return this;
  1994. },
  1995. identity: function () {
  1996. this.set(
  1997. 1, 0, 0,
  1998. 0, 1, 0,
  1999. 0, 0, 1
  2000. );
  2001. return this;
  2002. },
  2003. copy: function ( m ) {
  2004. var me = m.elements;
  2005. this.set(
  2006. me[0], me[3], me[6],
  2007. me[1], me[4], me[7],
  2008. me[2], me[5], me[8]
  2009. );
  2010. return this;
  2011. },
  2012. multiplyVector3: function ( vector ) {
  2013. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2014. return vector.applyMatrix3( this );
  2015. },
  2016. multiplyVector3Array: function() {
  2017. var v1 = new THREE.Vector3();
  2018. return function ( a ) {
  2019. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2020. v1.x = a[ i ];
  2021. v1.y = a[ i + 1 ];
  2022. v1.z = a[ i + 2 ];
  2023. v1.applyMatrix3(this);
  2024. a[ i ] = v1.x;
  2025. a[ i + 1 ] = v1.y;
  2026. a[ i + 2 ] = v1.z;
  2027. }
  2028. return a;
  2029. };
  2030. }(),
  2031. multiplyScalar: function ( s ) {
  2032. var te = this.elements;
  2033. te[0] *= s; te[3] *= s; te[6] *= s;
  2034. te[1] *= s; te[4] *= s; te[7] *= s;
  2035. te[2] *= s; te[5] *= s; te[8] *= s;
  2036. return this;
  2037. },
  2038. determinant: function () {
  2039. var te = this.elements;
  2040. var a = te[0], b = te[1], c = te[2],
  2041. d = te[3], e = te[4], f = te[5],
  2042. g = te[6], h = te[7], i = te[8];
  2043. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2044. },
  2045. getInverse: function ( matrix, throwOnInvertible ) {
  2046. // input: THREE.Matrix4
  2047. // ( based on http://code.google.com/p/webgl-mjs/ )
  2048. var me = matrix.elements;
  2049. var te = this.elements;
  2050. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2051. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2052. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2053. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2054. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2055. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2056. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2057. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2058. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2059. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2060. // no inverse
  2061. if ( det === 0 ) {
  2062. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2063. if ( throwOnInvertible || false ) {
  2064. throw new Error( msg );
  2065. } else {
  2066. console.warn( msg );
  2067. }
  2068. this.identity();
  2069. return this;
  2070. }
  2071. this.multiplyScalar( 1.0 / det );
  2072. return this;
  2073. },
  2074. transpose: function () {
  2075. var tmp, m = this.elements;
  2076. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2077. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2078. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2079. return this;
  2080. },
  2081. getNormalMatrix: function ( m ) {
  2082. // input: THREE.Matrix4
  2083. this.getInverse( m ).transpose();
  2084. return this;
  2085. },
  2086. transposeIntoArray: function ( r ) {
  2087. var m = this.elements;
  2088. r[ 0 ] = m[ 0 ];
  2089. r[ 1 ] = m[ 3 ];
  2090. r[ 2 ] = m[ 6 ];
  2091. r[ 3 ] = m[ 1 ];
  2092. r[ 4 ] = m[ 4 ];
  2093. r[ 5 ] = m[ 7 ];
  2094. r[ 6 ] = m[ 2 ];
  2095. r[ 7 ] = m[ 5 ];
  2096. r[ 8 ] = m[ 8 ];
  2097. return this;
  2098. },
  2099. clone: function () {
  2100. var te = this.elements;
  2101. return new THREE.Matrix3(
  2102. te[0], te[3], te[6],
  2103. te[1], te[4], te[7],
  2104. te[2], te[5], te[8]
  2105. );
  2106. }
  2107. } );
  2108. /**
  2109. * @author mrdoob / http://mrdoob.com/
  2110. * @author supereggbert / http://www.paulbrunt.co.uk/
  2111. * @author philogb / http://blog.thejit.org/
  2112. * @author jordi_ros / http://plattsoft.com
  2113. * @author D1plo1d / http://github.com/D1plo1d
  2114. * @author alteredq / http://alteredqualia.com/
  2115. * @author mikael emtinger / http://gomo.se/
  2116. * @author timknip / http://www.floorplanner.com/
  2117. * @author bhouston / http://exocortex.com
  2118. */
  2119. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2120. var te = this.elements = new Float32Array( 16 );
  2121. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2122. // we should not support semi specification of Matrix4, it is just weird.
  2123. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2124. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2125. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2126. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2127. };
  2128. THREE.extend( THREE.Matrix4.prototype, {
  2129. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2130. var te = this.elements;
  2131. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2132. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2133. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2134. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2135. return this;
  2136. },
  2137. identity: function () {
  2138. this.set(
  2139. 1, 0, 0, 0,
  2140. 0, 1, 0, 0,
  2141. 0, 0, 1, 0,
  2142. 0, 0, 0, 1
  2143. );
  2144. return this;
  2145. },
  2146. copy: function ( m ) {
  2147. var me = m.elements;
  2148. this.set(
  2149. me[0], me[4], me[8], me[12],
  2150. me[1], me[5], me[9], me[13],
  2151. me[2], me[6], me[10], me[14],
  2152. me[3], me[7], me[11], me[15]
  2153. );
  2154. return this;
  2155. },
  2156. setRotationFromEuler: function ( v, order ) {
  2157. var te = this.elements;
  2158. var x = v.x, y = v.y, z = v.z;
  2159. var a = Math.cos( x ), b = Math.sin( x );
  2160. var c = Math.cos( y ), d = Math.sin( y );
  2161. var e = Math.cos( z ), f = Math.sin( z );
  2162. if ( order === undefined || order === 'XYZ' ) {
  2163. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2164. te[0] = c * e;
  2165. te[4] = - c * f;
  2166. te[8] = d;
  2167. te[1] = af + be * d;
  2168. te[5] = ae - bf * d;
  2169. te[9] = - b * c;
  2170. te[2] = bf - ae * d;
  2171. te[6] = be + af * d;
  2172. te[10] = a * c;
  2173. } else if ( order === 'YXZ' ) {
  2174. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2175. te[0] = ce + df * b;
  2176. te[4] = de * b - cf;
  2177. te[8] = a * d;
  2178. te[1] = a * f;
  2179. te[5] = a * e;
  2180. te[9] = - b;
  2181. te[2] = cf * b - de;
  2182. te[6] = df + ce * b;
  2183. te[10] = a * c;
  2184. } else if ( order === 'ZXY' ) {
  2185. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2186. te[0] = ce - df * b;
  2187. te[4] = - a * f;
  2188. te[8] = de + cf * b;
  2189. te[1] = cf + de * b;
  2190. te[5] = a * e;
  2191. te[9] = df - ce * b;
  2192. te[2] = - a * d;
  2193. te[6] = b;
  2194. te[10] = a * c;
  2195. } else if ( order === 'ZYX' ) {
  2196. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2197. te[0] = c * e;
  2198. te[4] = be * d - af;
  2199. te[8] = ae * d + bf;
  2200. te[1] = c * f;
  2201. te[5] = bf * d + ae;
  2202. te[9] = af * d - be;
  2203. te[2] = - d;
  2204. te[6] = b * c;
  2205. te[10] = a * c;
  2206. } else if ( order === 'YZX' ) {
  2207. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2208. te[0] = c * e;
  2209. te[4] = bd - ac * f;
  2210. te[8] = bc * f + ad;
  2211. te[1] = f;
  2212. te[5] = a * e;
  2213. te[9] = - b * e;
  2214. te[2] = - d * e;
  2215. te[6] = ad * f + bc;
  2216. te[10] = ac - bd * f;
  2217. } else if ( order === 'XZY' ) {
  2218. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2219. te[0] = c * e;
  2220. te[4] = - f;
  2221. te[8] = d * e;
  2222. te[1] = ac * f + bd;
  2223. te[5] = a * e;
  2224. te[9] = ad * f - bc;
  2225. te[2] = bc * f - ad;
  2226. te[6] = b * e;
  2227. te[10] = bd * f + ac;
  2228. }
  2229. return this;
  2230. },
  2231. setRotationFromQuaternion: function ( q ) {
  2232. var te = this.elements;
  2233. var x = q.x, y = q.y, z = q.z, w = q.w;
  2234. var x2 = x + x, y2 = y + y, z2 = z + z;
  2235. var xx = x * x2, xy = x * y2, xz = x * z2;
  2236. var yy = y * y2, yz = y * z2, zz = z * z2;
  2237. var wx = w * x2, wy = w * y2, wz = w * z2;
  2238. te[0] = 1 - ( yy + zz );
  2239. te[4] = xy - wz;
  2240. te[8] = xz + wy;
  2241. te[1] = xy + wz;
  2242. te[5] = 1 - ( xx + zz );
  2243. te[9] = yz - wx;
  2244. te[2] = xz - wy;
  2245. te[6] = yz + wx;
  2246. te[10] = 1 - ( xx + yy );
  2247. return this;
  2248. },
  2249. lookAt: function() {
  2250. var x = new THREE.Vector3();
  2251. var y = new THREE.Vector3();
  2252. var z = new THREE.Vector3();
  2253. return function ( eye, target, up ) {
  2254. var te = this.elements;
  2255. z.subVectors( eye, target ).normalize();
  2256. if ( z.length() === 0 ) {
  2257. z.z = 1;
  2258. }
  2259. x.crossVectors( up, z ).normalize();
  2260. if ( x.length() === 0 ) {
  2261. z.x += 0.0001;
  2262. x.crossVectors( up, z ).normalize();
  2263. }
  2264. y.crossVectors( z, x );
  2265. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2266. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2267. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2268. return this;
  2269. };
  2270. }(),
  2271. multiply: function ( m, n ) {
  2272. if ( n !== undefined ) {
  2273. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2274. return this.multiplyMatrices( m, n );
  2275. }
  2276. return this.multiplyMatrices( this, m );
  2277. },
  2278. multiplyMatrices: function ( a, b ) {
  2279. var ae = a.elements;
  2280. var be = b.elements;
  2281. var te = this.elements;
  2282. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2283. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2284. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2285. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2286. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2287. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2288. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2289. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2290. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2291. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2292. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2293. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2294. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2295. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2296. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2297. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2298. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2299. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2300. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2301. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2302. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2303. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2304. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2305. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2306. return this;
  2307. },
  2308. multiplyToArray: function ( a, b, r ) {
  2309. var te = this.elements;
  2310. this.multiplyMatrices( a, b );
  2311. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2312. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2313. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2314. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2315. return this;
  2316. },
  2317. multiplyScalar: function ( s ) {
  2318. var te = this.elements;
  2319. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2320. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2321. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2322. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2323. return this;
  2324. },
  2325. multiplyVector3: function ( vector ) {
  2326. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2327. return vector.applyProjection( this );
  2328. },
  2329. multiplyVector4: function ( vector ) {
  2330. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2331. return vector.applyMatrix4( this );
  2332. },
  2333. multiplyVector3Array: function() {
  2334. var v1 = new THREE.Vector3();
  2335. return function ( a ) {
  2336. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2337. v1.x = a[ i ];
  2338. v1.y = a[ i + 1 ];
  2339. v1.z = a[ i + 2 ];
  2340. v1.applyProjection( this );
  2341. a[ i ] = v1.x;
  2342. a[ i + 1 ] = v1.y;
  2343. a[ i + 2 ] = v1.z;
  2344. }
  2345. return a;
  2346. };
  2347. }(),
  2348. rotateAxis: function ( v ) {
  2349. var te = this.elements;
  2350. var vx = v.x, vy = v.y, vz = v.z;
  2351. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  2352. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  2353. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  2354. v.normalize();
  2355. return v;
  2356. },
  2357. crossVector: function ( a ) {
  2358. var te = this.elements;
  2359. var v = new THREE.Vector4();
  2360. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2361. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2362. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2363. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2364. return v;
  2365. },
  2366. determinant: function () {
  2367. var te = this.elements;
  2368. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2369. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2370. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2371. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2372. //TODO: make this more efficient
  2373. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2374. return (
  2375. n41 * (
  2376. +n14 * n23 * n32
  2377. -n13 * n24 * n32
  2378. -n14 * n22 * n33
  2379. +n12 * n24 * n33
  2380. +n13 * n22 * n34
  2381. -n12 * n23 * n34
  2382. ) +
  2383. n42 * (
  2384. +n11 * n23 * n34
  2385. -n11 * n24 * n33
  2386. +n14 * n21 * n33
  2387. -n13 * n21 * n34
  2388. +n13 * n24 * n31
  2389. -n14 * n23 * n31
  2390. ) +
  2391. n43 * (
  2392. +n11 * n24 * n32
  2393. -n11 * n22 * n34
  2394. -n14 * n21 * n32
  2395. +n12 * n21 * n34
  2396. +n14 * n22 * n31
  2397. -n12 * n24 * n31
  2398. ) +
  2399. n44 * (
  2400. -n13 * n22 * n31
  2401. -n11 * n23 * n32
  2402. +n11 * n22 * n33
  2403. +n13 * n21 * n32
  2404. -n12 * n21 * n33
  2405. +n12 * n23 * n31
  2406. )
  2407. );
  2408. },
  2409. transpose: function () {
  2410. var te = this.elements;
  2411. var tmp;
  2412. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2413. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2414. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2415. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2416. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2417. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2418. return this;
  2419. },
  2420. flattenToArray: function ( flat ) {
  2421. var te = this.elements;
  2422. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2423. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2424. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2425. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2426. return flat;
  2427. },
  2428. flattenToArrayOffset: function( flat, offset ) {
  2429. var te = this.elements;
  2430. flat[ offset ] = te[0];
  2431. flat[ offset + 1 ] = te[1];
  2432. flat[ offset + 2 ] = te[2];
  2433. flat[ offset + 3 ] = te[3];
  2434. flat[ offset + 4 ] = te[4];
  2435. flat[ offset + 5 ] = te[5];
  2436. flat[ offset + 6 ] = te[6];
  2437. flat[ offset + 7 ] = te[7];
  2438. flat[ offset + 8 ] = te[8];
  2439. flat[ offset + 9 ] = te[9];
  2440. flat[ offset + 10 ] = te[10];
  2441. flat[ offset + 11 ] = te[11];
  2442. flat[ offset + 12 ] = te[12];
  2443. flat[ offset + 13 ] = te[13];
  2444. flat[ offset + 14 ] = te[14];
  2445. flat[ offset + 15 ] = te[15];
  2446. return flat;
  2447. },
  2448. getPosition: function() {
  2449. var v1 = new THREE.Vector3();
  2450. return function () {
  2451. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2452. var te = this.elements;
  2453. return v1.set( te[12], te[13], te[14] );
  2454. };
  2455. }(),
  2456. setPosition: function ( v ) {
  2457. var te = this.elements;
  2458. te[12] = v.x;
  2459. te[13] = v.y;
  2460. te[14] = v.z;
  2461. return this;
  2462. },
  2463. getInverse: function ( m, throwOnInvertible ) {
  2464. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2465. var te = this.elements;
  2466. var me = m.elements;
  2467. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2468. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2469. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2470. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2471. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2472. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2473. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2474. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2475. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2476. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2477. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2478. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2479. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2480. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2481. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2482. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2483. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2484. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2485. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2486. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2487. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2488. if ( det == 0 ) {
  2489. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2490. if ( throwOnInvertible || false ) {
  2491. throw new Error( msg );
  2492. } else {
  2493. console.warn( msg );
  2494. }
  2495. this.identity();
  2496. return this;
  2497. }
  2498. this.multiplyScalar( 1 / det );
  2499. return this;
  2500. },
  2501. compose: function() {
  2502. var mRotation = new THREE.Matrix4(),
  2503. mScale = new THREE.Matrix4();
  2504. return function ( translation, rotation, scale ) {
  2505. var te = this.elements;
  2506. mRotation.identity();
  2507. mRotation.setRotationFromQuaternion( rotation );
  2508. mScale.makeScale( scale.x, scale.y, scale.z );
  2509. this.multiplyMatrices( mRotation, mScale );
  2510. te[12] = translation.x;
  2511. te[13] = translation.y;
  2512. te[14] = translation.z;
  2513. return this;
  2514. };
  2515. }(),
  2516. decompose: function() {
  2517. var x = new THREE.Vector3(),
  2518. y = new THREE.Vector3(),
  2519. z = new THREE.Vector3(),
  2520. matrix = new THREE.Matrix4();
  2521. return function ( translation, rotation, scale ) {
  2522. var te = this.elements;
  2523. // grab the axis vectors
  2524. x.set( te[0], te[1], te[2] );
  2525. y.set( te[4], te[5], te[6] );
  2526. z.set( te[8], te[9], te[10] );
  2527. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2528. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2529. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2530. scale.x = x.length();
  2531. scale.y = y.length();
  2532. scale.z = z.length();
  2533. translation.x = te[12];
  2534. translation.y = te[13];
  2535. translation.z = te[14];
  2536. // scale the rotation part
  2537. matrix.copy( this );
  2538. matrix.elements[0] /= scale.x;
  2539. matrix.elements[1] /= scale.x;
  2540. matrix.elements[2] /= scale.x;
  2541. matrix.elements[4] /= scale.y;
  2542. matrix.elements[5] /= scale.y;
  2543. matrix.elements[6] /= scale.y;
  2544. matrix.elements[8] /= scale.z;
  2545. matrix.elements[9] /= scale.z;
  2546. matrix.elements[10] /= scale.z;
  2547. rotation.setFromRotationMatrix( matrix );
  2548. return [ translation, rotation, scale ];
  2549. };
  2550. }(),
  2551. extractPosition: function ( m ) {
  2552. var te = this.elements;
  2553. var me = m.elements;
  2554. te[12] = me[12];
  2555. te[13] = me[13];
  2556. te[14] = me[14];
  2557. return this;
  2558. },
  2559. extractRotation: function() {
  2560. var v1 = new THREE.Vector3();
  2561. return function ( m ) {
  2562. var te = this.elements;
  2563. var me = m.elements;
  2564. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2565. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2566. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2567. te[0] = me[0] * scaleX;
  2568. te[1] = me[1] * scaleX;
  2569. te[2] = me[2] * scaleX;
  2570. te[4] = me[4] * scaleY;
  2571. te[5] = me[5] * scaleY;
  2572. te[6] = me[6] * scaleY;
  2573. te[8] = me[8] * scaleZ;
  2574. te[9] = me[9] * scaleZ;
  2575. te[10] = me[10] * scaleZ;
  2576. return this;
  2577. };
  2578. }(),
  2579. translate: function ( v ) {
  2580. var te = this.elements;
  2581. var x = v.x, y = v.y, z = v.z;
  2582. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2583. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2584. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2585. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2586. return this;
  2587. },
  2588. rotateX: function ( angle ) {
  2589. var te = this.elements;
  2590. var m12 = te[4];
  2591. var m22 = te[5];
  2592. var m32 = te[6];
  2593. var m42 = te[7];
  2594. var m13 = te[8];
  2595. var m23 = te[9];
  2596. var m33 = te[10];
  2597. var m43 = te[11];
  2598. var c = Math.cos( angle );
  2599. var s = Math.sin( angle );
  2600. te[4] = c * m12 + s * m13;
  2601. te[5] = c * m22 + s * m23;
  2602. te[6] = c * m32 + s * m33;
  2603. te[7] = c * m42 + s * m43;
  2604. te[8] = c * m13 - s * m12;
  2605. te[9] = c * m23 - s * m22;
  2606. te[10] = c * m33 - s * m32;
  2607. te[11] = c * m43 - s * m42;
  2608. return this;
  2609. },
  2610. rotateY: function ( angle ) {
  2611. var te = this.elements;
  2612. var m11 = te[0];
  2613. var m21 = te[1];
  2614. var m31 = te[2];
  2615. var m41 = te[3];
  2616. var m13 = te[8];
  2617. var m23 = te[9];
  2618. var m33 = te[10];
  2619. var m43 = te[11];
  2620. var c = Math.cos( angle );
  2621. var s = Math.sin( angle );
  2622. te[0] = c * m11 - s * m13;
  2623. te[1] = c * m21 - s * m23;
  2624. te[2] = c * m31 - s * m33;
  2625. te[3] = c * m41 - s * m43;
  2626. te[8] = c * m13 + s * m11;
  2627. te[9] = c * m23 + s * m21;
  2628. te[10] = c * m33 + s * m31;
  2629. te[11] = c * m43 + s * m41;
  2630. return this;
  2631. },
  2632. rotateZ: function ( angle ) {
  2633. var te = this.elements;
  2634. var m11 = te[0];
  2635. var m21 = te[1];
  2636. var m31 = te[2];
  2637. var m41 = te[3];
  2638. var m12 = te[4];
  2639. var m22 = te[5];
  2640. var m32 = te[6];
  2641. var m42 = te[7];
  2642. var c = Math.cos( angle );
  2643. var s = Math.sin( angle );
  2644. te[0] = c * m11 + s * m12;
  2645. te[1] = c * m21 + s * m22;
  2646. te[2] = c * m31 + s * m32;
  2647. te[3] = c * m41 + s * m42;
  2648. te[4] = c * m12 - s * m11;
  2649. te[5] = c * m22 - s * m21;
  2650. te[6] = c * m32 - s * m31;
  2651. te[7] = c * m42 - s * m41;
  2652. return this;
  2653. },
  2654. rotateByAxis: function ( axis, angle ) {
  2655. var te = this.elements;
  2656. // optimize by checking axis
  2657. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2658. return this.rotateX( angle );
  2659. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2660. return this.rotateY( angle );
  2661. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2662. return this.rotateZ( angle );
  2663. }
  2664. var x = axis.x, y = axis.y, z = axis.z;
  2665. var n = Math.sqrt(x * x + y * y + z * z);
  2666. x /= n;
  2667. y /= n;
  2668. z /= n;
  2669. var xx = x * x, yy = y * y, zz = z * z;
  2670. var c = Math.cos( angle );
  2671. var s = Math.sin( angle );
  2672. var oneMinusCosine = 1 - c;
  2673. var xy = x * y * oneMinusCosine;
  2674. var xz = x * z * oneMinusCosine;
  2675. var yz = y * z * oneMinusCosine;
  2676. var xs = x * s;
  2677. var ys = y * s;
  2678. var zs = z * s;
  2679. var r11 = xx + (1 - xx) * c;
  2680. var r21 = xy + zs;
  2681. var r31 = xz - ys;
  2682. var r12 = xy - zs;
  2683. var r22 = yy + (1 - yy) * c;
  2684. var r32 = yz + xs;
  2685. var r13 = xz + ys;
  2686. var r23 = yz - xs;
  2687. var r33 = zz + (1 - zz) * c;
  2688. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2689. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2690. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2691. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2692. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2693. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2694. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2695. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2696. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2697. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2698. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2699. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2700. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2701. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2702. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2703. return this;
  2704. },
  2705. scale: function ( v ) {
  2706. var te = this.elements;
  2707. var x = v.x, y = v.y, z = v.z;
  2708. te[0] *= x; te[4] *= y; te[8] *= z;
  2709. te[1] *= x; te[5] *= y; te[9] *= z;
  2710. te[2] *= x; te[6] *= y; te[10] *= z;
  2711. te[3] *= x; te[7] *= y; te[11] *= z;
  2712. return this;
  2713. },
  2714. getMaxScaleOnAxis: function () {
  2715. var te = this.elements;
  2716. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2717. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2718. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2719. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2720. },
  2721. makeTranslation: function ( x, y, z ) {
  2722. this.set(
  2723. 1, 0, 0, x,
  2724. 0, 1, 0, y,
  2725. 0, 0, 1, z,
  2726. 0, 0, 0, 1
  2727. );
  2728. return this;
  2729. },
  2730. makeRotationX: function ( theta ) {
  2731. var c = Math.cos( theta ), s = Math.sin( theta );
  2732. this.set(
  2733. 1, 0, 0, 0,
  2734. 0, c, -s, 0,
  2735. 0, s, c, 0,
  2736. 0, 0, 0, 1
  2737. );
  2738. return this;
  2739. },
  2740. makeRotationY: function ( theta ) {
  2741. var c = Math.cos( theta ), s = Math.sin( theta );
  2742. this.set(
  2743. c, 0, s, 0,
  2744. 0, 1, 0, 0,
  2745. -s, 0, c, 0,
  2746. 0, 0, 0, 1
  2747. );
  2748. return this;
  2749. },
  2750. makeRotationZ: function ( theta ) {
  2751. var c = Math.cos( theta ), s = Math.sin( theta );
  2752. this.set(
  2753. c, -s, 0, 0,
  2754. s, c, 0, 0,
  2755. 0, 0, 1, 0,
  2756. 0, 0, 0, 1
  2757. );
  2758. return this;
  2759. },
  2760. makeRotationAxis: function ( axis, angle ) {
  2761. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2762. var c = Math.cos( angle );
  2763. var s = Math.sin( angle );
  2764. var t = 1 - c;
  2765. var x = axis.x, y = axis.y, z = axis.z;
  2766. var tx = t * x, ty = t * y;
  2767. this.set(
  2768. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2769. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2770. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2771. 0, 0, 0, 1
  2772. );
  2773. return this;
  2774. },
  2775. makeScale: function ( x, y, z ) {
  2776. this.set(
  2777. x, 0, 0, 0,
  2778. 0, y, 0, 0,
  2779. 0, 0, z, 0,
  2780. 0, 0, 0, 1
  2781. );
  2782. return this;
  2783. },
  2784. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2785. var te = this.elements;
  2786. var x = 2 * near / ( right - left );
  2787. var y = 2 * near / ( top - bottom );
  2788. var a = ( right + left ) / ( right - left );
  2789. var b = ( top + bottom ) / ( top - bottom );
  2790. var c = - ( far + near ) / ( far - near );
  2791. var d = - 2 * far * near / ( far - near );
  2792. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2793. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2794. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2795. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2796. return this;
  2797. },
  2798. makePerspective: function ( fov, aspect, near, far ) {
  2799. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2800. var ymin = - ymax;
  2801. var xmin = ymin * aspect;
  2802. var xmax = ymax * aspect;
  2803. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2804. },
  2805. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2806. var te = this.elements;
  2807. var w = right - left;
  2808. var h = top - bottom;
  2809. var p = far - near;
  2810. var x = ( right + left ) / w;
  2811. var y = ( top + bottom ) / h;
  2812. var z = ( far + near ) / p;
  2813. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2814. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2815. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2816. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2817. return this;
  2818. },
  2819. clone: function () {
  2820. var te = this.elements;
  2821. return new THREE.Matrix4(
  2822. te[0], te[4], te[8], te[12],
  2823. te[1], te[5], te[9], te[13],
  2824. te[2], te[6], te[10], te[14],
  2825. te[3], te[7], te[11], te[15]
  2826. );
  2827. }
  2828. } );
  2829. /**
  2830. * @author bhouston / http://exocortex.com
  2831. */
  2832. THREE.Ray = function ( origin, direction ) {
  2833. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2834. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2835. };
  2836. THREE.extend( THREE.Ray.prototype, {
  2837. set: function ( origin, direction ) {
  2838. this.origin.copy( origin );
  2839. this.direction.copy( direction );
  2840. return this;
  2841. },
  2842. copy: function ( ray ) {
  2843. this.origin.copy( ray.origin );
  2844. this.direction.copy( ray.direction );
  2845. return this;
  2846. },
  2847. at: function( t, optionalTarget ) {
  2848. var result = optionalTarget || new THREE.Vector3();
  2849. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2850. },
  2851. recast: function() {
  2852. var v1 = new THREE.Vector3();
  2853. return function ( t ) {
  2854. this.origin.copy( this.at( t, v1 ) );
  2855. return this;
  2856. };
  2857. }(),
  2858. closestPointToPoint: function ( point, optionalTarget ) {
  2859. var result = optionalTarget || new THREE.Vector3();
  2860. result.subVectors( point, this.origin );
  2861. var directionDistance = result.dot( this.direction );
  2862. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2863. },
  2864. distanceToPoint: function() {
  2865. var v1 = new THREE.Vector3();
  2866. return function ( point ) {
  2867. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2868. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2869. return v1.distanceTo( point );
  2870. };
  2871. }(),
  2872. isIntersectionSphere: function( sphere ) {
  2873. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2874. },
  2875. isIntersectionPlane: function ( plane ) {
  2876. // check if the line and plane are non-perpendicular, if they
  2877. // eventually they will intersect.
  2878. var denominator = plane.normal.dot( this.direction );
  2879. if ( denominator != 0 ) {
  2880. return true;
  2881. }
  2882. // line is coplanar, return origin
  2883. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2884. return true;
  2885. }
  2886. return false;
  2887. },
  2888. distanceToPlane: function ( plane ) {
  2889. var denominator = plane.normal.dot( this.direction );
  2890. if ( denominator == 0 ) {
  2891. // line is coplanar, return origin
  2892. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2893. return 0;
  2894. }
  2895. // Unsure if this is the correct method to handle this case.
  2896. return undefined;
  2897. }
  2898. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2899. return t;
  2900. },
  2901. intersectPlane: function ( plane, optionalTarget ) {
  2902. var t = this.distanceToPlane( plane );
  2903. if ( t === undefined ) {
  2904. return undefined;
  2905. }
  2906. return this.at( t, optionalTarget );
  2907. },
  2908. applyMatrix4: function ( matrix4 ) {
  2909. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2910. this.origin.applyMatrix4( matrix4 );
  2911. this.direction.sub( this.origin );
  2912. return this;
  2913. },
  2914. equals: function ( ray ) {
  2915. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2916. },
  2917. clone: function () {
  2918. return new THREE.Ray().copy( this );
  2919. }
  2920. } );
  2921. /**
  2922. * @author bhouston / http://exocortex.com
  2923. * @author mrdoob / http://mrdoob.com/
  2924. */
  2925. THREE.Sphere = function ( center, radius ) {
  2926. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2927. this.radius = ( radius !== undefined ) ? radius : 0;
  2928. };
  2929. THREE.extend( THREE.Sphere.prototype, {
  2930. set: function ( center, radius ) {
  2931. this.center.copy( center );
  2932. this.radius = radius;
  2933. return this;
  2934. },
  2935. setFromCenterAndPoints: function ( center, points ) {
  2936. var maxRadiusSq = 0;
  2937. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2938. var radiusSq = center.distanceToSquared( points[ i ] );
  2939. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2940. }
  2941. this.center = center;
  2942. this.radius = Math.sqrt( maxRadiusSq );
  2943. return this;
  2944. },
  2945. copy: function ( sphere ) {
  2946. this.center.copy( sphere.center );
  2947. this.radius = sphere.radius;
  2948. return this;
  2949. },
  2950. empty: function () {
  2951. return ( this.radius <= 0 );
  2952. },
  2953. containsPoint: function ( point ) {
  2954. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2955. },
  2956. distanceToPoint: function ( point ) {
  2957. return ( point.distanceTo( this.center ) - this.radius );
  2958. },
  2959. intersectsSphere: function ( sphere ) {
  2960. var radiusSum = this.radius + sphere.radius;
  2961. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2962. },
  2963. clampPoint: function ( point, optionalTarget ) {
  2964. var deltaLengthSq = this.center.distanceToSquared( point );
  2965. var result = optionalTarget || new THREE.Vector3();
  2966. result.copy( point );
  2967. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2968. result.sub( this.center ).normalize();
  2969. result.multiplyScalar( this.radius ).add( this.center );
  2970. }
  2971. return result;
  2972. },
  2973. getBoundingBox: function ( optionalTarget ) {
  2974. var box = optionalTarget || new THREE.Box3();
  2975. box.set( this.center, this.center );
  2976. box.expandByScalar( this.radius );
  2977. return box;
  2978. },
  2979. applyMatrix4: function ( matrix ) {
  2980. this.center.applyMatrix4( matrix );
  2981. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2982. return this;
  2983. },
  2984. translate: function ( offset ) {
  2985. this.center.add( offset );
  2986. return this;
  2987. },
  2988. equals: function ( sphere ) {
  2989. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2990. },
  2991. clone: function () {
  2992. return new THREE.Sphere().copy( this );
  2993. }
  2994. } );
  2995. /**
  2996. * @author mrdoob / http://mrdoob.com/
  2997. * @author alteredq / http://alteredqualia.com/
  2998. * @author bhouston / http://exocortex.com
  2999. */
  3000. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3001. this.planes = [
  3002. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3003. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3004. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3005. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3006. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3007. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3008. ];
  3009. };
  3010. THREE.extend( THREE.Frustum.prototype, {
  3011. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3012. var planes = this.planes;
  3013. planes[0].copy( p0 );
  3014. planes[1].copy( p1 );
  3015. planes[2].copy( p2 );
  3016. planes[3].copy( p3 );
  3017. planes[4].copy( p4 );
  3018. planes[5].copy( p5 );
  3019. return this;
  3020. },
  3021. copy: function ( frustum ) {
  3022. var planes = this.planes;
  3023. for( var i = 0; i < 6; i ++ ) {
  3024. planes[i].copy( frustum.planes[i] );
  3025. }
  3026. return this;
  3027. },
  3028. setFromMatrix: function ( m ) {
  3029. var planes = this.planes;
  3030. var me = m.elements;
  3031. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3032. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3033. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3034. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3035. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3036. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3037. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3038. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3039. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3040. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3041. return this;
  3042. },
  3043. intersectsObject: function () {
  3044. var center = new THREE.Vector3();
  3045. return function ( object ) {
  3046. // this method is expanded inlined for performance reasons.
  3047. var matrix = object.matrixWorld;
  3048. var planes = this.planes;
  3049. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3050. center.getPositionFromMatrix( matrix );
  3051. for ( var i = 0; i < 6; i ++ ) {
  3052. var distance = planes[ i ].distanceToPoint( center );
  3053. if ( distance < negRadius ) {
  3054. return false;
  3055. }
  3056. }
  3057. return true;
  3058. };
  3059. }(),
  3060. intersectsSphere: function ( sphere ) {
  3061. var planes = this.planes;
  3062. var center = sphere.center;
  3063. var negRadius = -sphere.radius;
  3064. for ( var i = 0; i < 6; i ++ ) {
  3065. var distance = planes[ i ].distanceToPoint( center );
  3066. if ( distance < negRadius ) {
  3067. return false;
  3068. }
  3069. }
  3070. return true;
  3071. },
  3072. containsPoint: function ( point ) {
  3073. var planes = this.planes;
  3074. for ( var i = 0; i < 6; i ++ ) {
  3075. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3076. return false;
  3077. }
  3078. }
  3079. return true;
  3080. },
  3081. clone: function () {
  3082. return new THREE.Frustum().copy( this );
  3083. }
  3084. } );
  3085. /**
  3086. * @author bhouston / http://exocortex.com
  3087. */
  3088. THREE.Plane = function ( normal, constant ) {
  3089. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3090. this.constant = ( constant !== undefined ) ? constant : 0;
  3091. };
  3092. THREE.extend( THREE.Plane.prototype, {
  3093. set: function ( normal, constant ) {
  3094. this.normal.copy( normal );
  3095. this.constant = constant;
  3096. return this;
  3097. },
  3098. setComponents: function ( x, y, z, w ) {
  3099. this.normal.set( x, y, z );
  3100. this.constant = w;
  3101. return this;
  3102. },
  3103. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3104. this.normal.copy( normal );
  3105. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3106. return this;
  3107. },
  3108. setFromCoplanarPoints: function() {
  3109. var v1 = new THREE.Vector3();
  3110. var v2 = new THREE.Vector3();
  3111. return function ( a, b, c ) {
  3112. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3113. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3114. this.setFromNormalAndCoplanarPoint( normal, a );
  3115. return this;
  3116. };
  3117. }(),
  3118. copy: function ( plane ) {
  3119. this.normal.copy( plane.normal );
  3120. this.constant = plane.constant;
  3121. return this;
  3122. },
  3123. normalize: function () {
  3124. // Note: will lead to a divide by zero if the plane is invalid.
  3125. var inverseNormalLength = 1.0 / this.normal.length();
  3126. this.normal.multiplyScalar( inverseNormalLength );
  3127. this.constant *= inverseNormalLength;
  3128. return this;
  3129. },
  3130. negate: function () {
  3131. this.constant *= -1;
  3132. this.normal.negate();
  3133. return this;
  3134. },
  3135. distanceToPoint: function ( point ) {
  3136. return this.normal.dot( point ) + this.constant;
  3137. },
  3138. distanceToSphere: function ( sphere ) {
  3139. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3140. },
  3141. projectPoint: function ( point, optionalTarget ) {
  3142. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3143. },
  3144. orthoPoint: function ( point, optionalTarget ) {
  3145. var perpendicularMagnitude = this.distanceToPoint( point );
  3146. var result = optionalTarget || new THREE.Vector3();
  3147. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3148. },
  3149. isIntersectionLine: function ( line ) {
  3150. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3151. var startSign = this.distanceToPoint( line.start );
  3152. var endSign = this.distanceToPoint( line.end );
  3153. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3154. },
  3155. intersectLine: function() {
  3156. var v1 = new THREE.Vector3();
  3157. return function ( line, optionalTarget ) {
  3158. var result = optionalTarget || new THREE.Vector3();
  3159. var direction = line.delta( v1 );
  3160. var denominator = this.normal.dot( direction );
  3161. if ( denominator == 0 ) {
  3162. // line is coplanar, return origin
  3163. if( this.distanceToPoint( line.start ) == 0 ) {
  3164. return result.copy( line.start );
  3165. }
  3166. // Unsure if this is the correct method to handle this case.
  3167. return undefined;
  3168. }
  3169. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3170. if( t < 0 || t > 1 ) {
  3171. return undefined;
  3172. }
  3173. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3174. };
  3175. }(),
  3176. coplanarPoint: function ( optionalTarget ) {
  3177. var result = optionalTarget || new THREE.Vector3();
  3178. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3179. },
  3180. applyMatrix4: function() {
  3181. var v1 = new THREE.Vector3();
  3182. var v2 = new THREE.Vector3();
  3183. return function ( matrix, optionalNormalMatrix ) {
  3184. // compute new normal based on theory here:
  3185. // http://www.songho.ca/opengl/gl_normaltransform.html
  3186. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3187. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3188. var newCoplanarPoint = this.coplanarPoint( v2 );
  3189. newCoplanarPoint.applyMatrix4( matrix );
  3190. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3191. return this;
  3192. };
  3193. }(),
  3194. translate: function ( offset ) {
  3195. this.constant = this.constant - offset.dot( this.normal );
  3196. return this;
  3197. },
  3198. equals: function ( plane ) {
  3199. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3200. },
  3201. clone: function () {
  3202. return new THREE.Plane().copy( this );
  3203. }
  3204. } );
  3205. /**
  3206. * @author alteredq / http://alteredqualia.com/
  3207. */
  3208. THREE.Math = {
  3209. // Clamp value to range <a, b>
  3210. clamp: function ( x, a, b ) {
  3211. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3212. },
  3213. // Clamp value to range <a, inf)
  3214. clampBottom: function ( x, a ) {
  3215. return x < a ? a : x;
  3216. },
  3217. // Linear mapping from range <a1, a2> to range <b1, b2>
  3218. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3219. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3220. },
  3221. // http://en.wikipedia.org/wiki/Smoothstep
  3222. smoothstep: function ( x, min, max ) {
  3223. if ( x <= min ) return 0;
  3224. if ( x >= max ) return 1;
  3225. x = ( x - min )/( max - min );
  3226. return x*x*(3 - 2*x);
  3227. },
  3228. smootherstep: function ( x, min, max ) {
  3229. if ( x <= min ) return 0;
  3230. if ( x >= max ) return 1;
  3231. x = ( x - min )/( max - min );
  3232. return x*x*x*(x*(x*6 - 15) + 10);
  3233. },
  3234. // Random float from <0, 1> with 16 bits of randomness
  3235. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3236. random16: function () {
  3237. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3238. },
  3239. // Random integer from <low, high> interval
  3240. randInt: function ( low, high ) {
  3241. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3242. },
  3243. // Random float from <low, high> interval
  3244. randFloat: function ( low, high ) {
  3245. return low + Math.random() * ( high - low );
  3246. },
  3247. // Random float from <-range/2, range/2> interval
  3248. randFloatSpread: function ( range ) {
  3249. return range * ( 0.5 - Math.random() );
  3250. },
  3251. sign: function ( x ) {
  3252. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3253. },
  3254. degToRad: function() {
  3255. var degreeToRadiansFactor = Math.PI / 180;
  3256. return function ( degrees ) {
  3257. return degrees * degreeToRadiansFactor;
  3258. };
  3259. }(),
  3260. radToDeg: function() {
  3261. var radianToDegreesFactor = 180 / Math.PI;
  3262. return function ( radians ) {
  3263. return radians * radianToDegreesFactor;
  3264. };
  3265. }()
  3266. };
  3267. /**
  3268. * Spline from Tween.js, slightly optimized (and trashed)
  3269. * http://sole.github.com/tween.js/examples/05_spline.html
  3270. *
  3271. * @author mrdoob / http://mrdoob.com/
  3272. * @author alteredq / http://alteredqualia.com/
  3273. */
  3274. THREE.Spline = function ( points ) {
  3275. this.points = points;
  3276. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3277. point, intPoint, weight, w2, w3,
  3278. pa, pb, pc, pd;
  3279. this.initFromArray = function( a ) {
  3280. this.points = [];
  3281. for ( var i = 0; i < a.length; i++ ) {
  3282. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3283. }
  3284. };
  3285. this.getPoint = function ( k ) {
  3286. point = ( this.points.length - 1 ) * k;
  3287. intPoint = Math.floor( point );
  3288. weight = point - intPoint;
  3289. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3290. c[ 1 ] = intPoint;
  3291. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3292. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3293. pa = this.points[ c[ 0 ] ];
  3294. pb = this.points[ c[ 1 ] ];
  3295. pc = this.points[ c[ 2 ] ];
  3296. pd = this.points[ c[ 3 ] ];
  3297. w2 = weight * weight;
  3298. w3 = weight * w2;
  3299. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3300. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3301. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3302. return v3;
  3303. };
  3304. this.getControlPointsArray = function () {
  3305. var i, p, l = this.points.length,
  3306. coords = [];
  3307. for ( i = 0; i < l; i ++ ) {
  3308. p = this.points[ i ];
  3309. coords[ i ] = [ p.x, p.y, p.z ];
  3310. }
  3311. return coords;
  3312. };
  3313. // approximate length by summing linear segments
  3314. this.getLength = function ( nSubDivisions ) {
  3315. var i, index, nSamples, position,
  3316. point = 0, intPoint = 0, oldIntPoint = 0,
  3317. oldPosition = new THREE.Vector3(),
  3318. tmpVec = new THREE.Vector3(),
  3319. chunkLengths = [],
  3320. totalLength = 0;
  3321. // first point has 0 length
  3322. chunkLengths[ 0 ] = 0;
  3323. if ( !nSubDivisions ) nSubDivisions = 100;
  3324. nSamples = this.points.length * nSubDivisions;
  3325. oldPosition.copy( this.points[ 0 ] );
  3326. for ( i = 1; i < nSamples; i ++ ) {
  3327. index = i / nSamples;
  3328. position = this.getPoint( index );
  3329. tmpVec.copy( position );
  3330. totalLength += tmpVec.distanceTo( oldPosition );
  3331. oldPosition.copy( position );
  3332. point = ( this.points.length - 1 ) * index;
  3333. intPoint = Math.floor( point );
  3334. if ( intPoint != oldIntPoint ) {
  3335. chunkLengths[ intPoint ] = totalLength;
  3336. oldIntPoint = intPoint;
  3337. }
  3338. }
  3339. // last point ends with total length
  3340. chunkLengths[ chunkLengths.length ] = totalLength;
  3341. return { chunks: chunkLengths, total: totalLength };
  3342. };
  3343. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3344. var i, j,
  3345. index, indexCurrent, indexNext,
  3346. linearDistance, realDistance,
  3347. sampling, position,
  3348. newpoints = [],
  3349. tmpVec = new THREE.Vector3(),
  3350. sl = this.getLength();
  3351. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3352. for ( i = 1; i < this.points.length; i++ ) {
  3353. //tmpVec.copy( this.points[ i - 1 ] );
  3354. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3355. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3356. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3357. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3358. indexNext = i / ( this.points.length - 1 );
  3359. for ( j = 1; j < sampling - 1; j++ ) {
  3360. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3361. position = this.getPoint( index );
  3362. newpoints.push( tmpVec.copy( position ).clone() );
  3363. }
  3364. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3365. }
  3366. this.points = newpoints;
  3367. };
  3368. // Catmull-Rom
  3369. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3370. var v0 = ( p2 - p0 ) * 0.5,
  3371. v1 = ( p3 - p1 ) * 0.5;
  3372. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3373. };
  3374. };
  3375. /**
  3376. * @author bhouston / http://exocortex.com
  3377. * @author mrdoob / http://mrdoob.com/
  3378. */
  3379. THREE.Triangle = function ( a, b, c ) {
  3380. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3381. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3382. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3383. };
  3384. THREE.Triangle.normal = function() {
  3385. var v0 = new THREE.Vector3();
  3386. return function( a, b, c, optionalTarget ) {
  3387. var result = optionalTarget || new THREE.Vector3();
  3388. result.subVectors( c, b );
  3389. v0.subVectors( a, b );
  3390. result.cross( v0 );
  3391. var resultLengthSq = result.lengthSq();
  3392. if( resultLengthSq > 0 ) {
  3393. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3394. }
  3395. return result.set( 0, 0, 0 );
  3396. };
  3397. }();
  3398. // static/instance method to calculate barycoordinates
  3399. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3400. THREE.Triangle.barycoordFromPoint = function() {
  3401. var v0 = new THREE.Vector3(),
  3402. v1 = new THREE.Vector3(),
  3403. v2 = new THREE.Vector3();
  3404. return function ( point, a, b, c, optionalTarget ) {
  3405. v0.subVectors( c, a );
  3406. v1.subVectors( b, a );
  3407. v2.subVectors( point, a );
  3408. var dot00 = v0.dot( v0 );
  3409. var dot01 = v0.dot( v1 );
  3410. var dot02 = v0.dot( v2 );
  3411. var dot11 = v1.dot( v1 );
  3412. var dot12 = v1.dot( v2 );
  3413. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3414. var result = optionalTarget || new THREE.Vector3();
  3415. // colinear or singular triangle
  3416. if( denom == 0 ) {
  3417. // arbitrary location outside of triangle?
  3418. // not sure if this is the best idea, maybe should be returning undefined
  3419. return result.set( -2, -1, -1 );
  3420. }
  3421. var invDenom = 1 / denom;
  3422. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3423. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3424. // barycoordinates must always sum to 1
  3425. return result.set( 1 - u - v, v, u );
  3426. };
  3427. }();
  3428. THREE.Triangle.containsPoint = function() {
  3429. var v1 = new THREE.Vector3();
  3430. return function ( point, a, b, c ) {
  3431. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3432. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3433. };
  3434. }();
  3435. THREE.extend( THREE.Triangle.prototype, {
  3436. constructor: THREE.Triangle,
  3437. set: function ( a, b, c ) {
  3438. this.a.copy( a );
  3439. this.b.copy( b );
  3440. this.c.copy( c );
  3441. return this;
  3442. },
  3443. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3444. this.a.copy( points[i0] );
  3445. this.b.copy( points[i1] );
  3446. this.c.copy( points[i2] );
  3447. return this;
  3448. },
  3449. copy: function ( triangle ) {
  3450. this.a.copy( triangle.a );
  3451. this.b.copy( triangle.b );
  3452. this.c.copy( triangle.c );
  3453. return this;
  3454. },
  3455. area: function() {
  3456. var v0 = new THREE.Vector3();
  3457. var v1 = new THREE.Vector3();
  3458. return function () {
  3459. v0.subVectors( this.c, this.b );
  3460. v1.subVectors( this.a, this.b );
  3461. return v0.cross( v1 ).length() * 0.5;
  3462. };
  3463. }(),
  3464. midpoint: function ( optionalTarget ) {
  3465. var result = optionalTarget || new THREE.Vector3();
  3466. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3467. },
  3468. normal: function ( optionalTarget ) {
  3469. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3470. },
  3471. plane: function ( optionalTarget ) {
  3472. var result = optionalTarget || new THREE.Plane();
  3473. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3474. },
  3475. barycoordFromPoint: function ( point, optionalTarget ) {
  3476. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3477. },
  3478. containsPoint: function ( point ) {
  3479. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3480. },
  3481. equals: function ( triangle ) {
  3482. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3483. },
  3484. clone: function () {
  3485. return new THREE.Triangle().copy( this );
  3486. }
  3487. } );
  3488. /**
  3489. * @author mrdoob / http://mrdoob.com/
  3490. */
  3491. THREE.Vertex = function ( v ) {
  3492. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3493. return v;
  3494. };
  3495. /**
  3496. * @author mrdoob / http://mrdoob.com/
  3497. */
  3498. THREE.UV = function ( u, v ) {
  3499. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3500. return new THREE.Vector2( u, v );
  3501. };
  3502. /**
  3503. * @author alteredq / http://alteredqualia.com/
  3504. */
  3505. THREE.Clock = function ( autoStart ) {
  3506. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3507. this.startTime = 0;
  3508. this.oldTime = 0;
  3509. this.elapsedTime = 0;
  3510. this.running = false;
  3511. };
  3512. THREE.extend( THREE.Clock.prototype, {
  3513. start: function () {
  3514. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3515. ? window.performance.now()
  3516. : Date.now();
  3517. this.oldTime = this.startTime;
  3518. this.running = true;
  3519. },
  3520. stop: function () {
  3521. this.getElapsedTime();
  3522. this.running = false;
  3523. },
  3524. getElapsedTime: function () {
  3525. this.getDelta();
  3526. return this.elapsedTime;
  3527. },
  3528. getDelta: function () {
  3529. var diff = 0;
  3530. if ( this.autoStart && ! this.running ) {
  3531. this.start();
  3532. }
  3533. if ( this.running ) {
  3534. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3535. ? window.performance.now()
  3536. : Date.now();
  3537. diff = 0.001 * ( newTime - this.oldTime );
  3538. this.oldTime = newTime;
  3539. this.elapsedTime += diff;
  3540. }
  3541. return diff;
  3542. }
  3543. } );
  3544. /**
  3545. * https://github.com/mrdoob/eventdispatcher.js/
  3546. */
  3547. THREE.EventDispatcher = function () {
  3548. var listeners = {};
  3549. this.addEventListener = function ( type, listener ) {
  3550. if ( listeners[ type ] === undefined ) {
  3551. listeners[ type ] = [];
  3552. }
  3553. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3554. listeners[ type ].push( listener );
  3555. }
  3556. };
  3557. this.removeEventListener = function ( type, listener ) {
  3558. var index = listeners[ type ].indexOf( listener );
  3559. if ( index !== - 1 ) {
  3560. listeners[ type ].splice( index, 1 );
  3561. }
  3562. };
  3563. this.dispatchEvent = function ( event ) {
  3564. var listenerArray = listeners[ event.type ];
  3565. if ( listenerArray !== undefined ) {
  3566. event.target = this;
  3567. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3568. listenerArray[ i ].call( this, event );
  3569. }
  3570. }
  3571. };
  3572. };
  3573. /**
  3574. * @author mrdoob / http://mrdoob.com/
  3575. * @author bhouston / http://exocortex.com/
  3576. */
  3577. ( function ( THREE ) {
  3578. THREE.Raycaster = function ( origin, direction, near, far ) {
  3579. this.ray = new THREE.Ray( origin, direction );
  3580. // normalized ray.direction required for accurate distance calculations
  3581. if( this.ray.direction.lengthSq() > 0 ) {
  3582. this.ray.direction.normalize();
  3583. }
  3584. this.near = near || 0;
  3585. this.far = far || Infinity;
  3586. };
  3587. var sphere = new THREE.Sphere();
  3588. var localRay = new THREE.Ray();
  3589. var facePlane = new THREE.Plane();
  3590. var intersectPoint = new THREE.Vector3();
  3591. var matrixPosition = new THREE.Vector3();
  3592. var inverseMatrix = new THREE.Matrix4();
  3593. var descSort = function ( a, b ) {
  3594. return a.distance - b.distance;
  3595. };
  3596. var intersectObject = function ( object, raycaster, intersects ) {
  3597. if ( object instanceof THREE.Particle ) {
  3598. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3599. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3600. if ( distance > object.scale.x ) {
  3601. return intersects;
  3602. }
  3603. intersects.push( {
  3604. distance: distance,
  3605. point: object.position,
  3606. face: null,
  3607. object: object
  3608. } );
  3609. } else if ( object instanceof THREE.Mesh ) {
  3610. // Checking boundingSphere distance to ray
  3611. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3612. sphere.set(
  3613. matrixPosition,
  3614. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3615. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3616. return intersects;
  3617. }
  3618. // Checking faces
  3619. var geometry = object.geometry;
  3620. var vertices = geometry.vertices;
  3621. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3622. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3623. var side = object.material.side;
  3624. var a, b, c, d;
  3625. var precision = raycaster.precision;
  3626. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3627. inverseMatrix.getInverse( object.matrixWorld );
  3628. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3629. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3630. var face = geometry.faces[ f ];
  3631. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3632. if ( material === undefined ) continue;
  3633. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3634. var planeDistance = localRay.distanceToPlane( facePlane );
  3635. // bail if raycaster and plane are parallel
  3636. if ( Math.abs( planeDistance ) < precision ) continue;
  3637. // if negative distance, then plane is behind raycaster
  3638. if ( planeDistance < 0 ) continue;
  3639. // check if we hit the wrong side of a single sided face
  3640. side = material.side;
  3641. if( side !== THREE.DoubleSide ) {
  3642. var planeSign = localRay.direction.dot( facePlane.normal );
  3643. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3644. }
  3645. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3646. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3647. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3648. if ( face instanceof THREE.Face3 ) {
  3649. a = vertices[ face.a ];
  3650. b = vertices[ face.b ];
  3651. c = vertices[ face.c ];
  3652. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3653. } else if ( face instanceof THREE.Face4 ) {
  3654. a = vertices[ face.a ];
  3655. b = vertices[ face.b ];
  3656. c = vertices[ face.c ];
  3657. d = vertices[ face.d ];
  3658. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3659. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3660. } else {
  3661. // This is added because if we call out of this if/else group when none of the cases
  3662. // match it will add a point to the intersection list erroneously.
  3663. throw Error( "face type not supported" );
  3664. }
  3665. intersects.push( {
  3666. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3667. point: raycaster.ray.at( planeDistance ),
  3668. face: face,
  3669. faceIndex: f,
  3670. object: object
  3671. } );
  3672. }
  3673. }
  3674. };
  3675. var intersectDescendants = function ( object, raycaster, intersects ) {
  3676. var descendants = object.getDescendants();
  3677. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3678. intersectObject( descendants[ i ], raycaster, intersects );
  3679. }
  3680. };
  3681. //
  3682. THREE.Raycaster.prototype.precision = 0.0001;
  3683. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3684. this.ray.set( origin, direction );
  3685. // normalized ray.direction required for accurate distance calculations
  3686. if( this.ray.direction.length() > 0 ) {
  3687. this.ray.direction.normalize();
  3688. }
  3689. };
  3690. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3691. var intersects = [];
  3692. if ( recursive === true ) {
  3693. intersectDescendants( object, this, intersects );
  3694. }
  3695. intersectObject( object, this, intersects );
  3696. intersects.sort( descSort );
  3697. return intersects;
  3698. };
  3699. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3700. var intersects = [];
  3701. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3702. intersectObject( objects[ i ], this, intersects );
  3703. if ( recursive === true ) {
  3704. intersectDescendants( objects[ i ], this, intersects );
  3705. }
  3706. }
  3707. intersects.sort( descSort );
  3708. return intersects;
  3709. };
  3710. }( THREE ) );
  3711. /**
  3712. * @author mrdoob / http://mrdoob.com/
  3713. * @author mikael emtinger / http://gomo.se/
  3714. * @author alteredq / http://alteredqualia.com/
  3715. */
  3716. THREE.Object3D = function () {
  3717. this.id = THREE.Object3DIdCount ++;
  3718. this.name = '';
  3719. this.properties = {};
  3720. this.parent = undefined;
  3721. this.children = [];
  3722. this.up = new THREE.Vector3( 0, 1, 0 );
  3723. this.position = new THREE.Vector3();
  3724. this.rotation = new THREE.Vector3();
  3725. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3726. this.scale = new THREE.Vector3( 1, 1, 1 );
  3727. this.renderDepth = null;
  3728. this.rotationAutoUpdate = true;
  3729. this.matrix = new THREE.Matrix4();
  3730. this.matrixWorld = new THREE.Matrix4();
  3731. this.matrixRotationWorld = new THREE.Matrix4();
  3732. this.matrixAutoUpdate = true;
  3733. this.matrixWorldNeedsUpdate = true;
  3734. this.quaternion = new THREE.Quaternion();
  3735. this.useQuaternion = false;
  3736. this.visible = true;
  3737. this.castShadow = false;
  3738. this.receiveShadow = false;
  3739. this.frustumCulled = true;
  3740. this._vector = new THREE.Vector3();
  3741. };
  3742. THREE.Object3D.prototype = {
  3743. constructor: THREE.Object3D,
  3744. applyMatrix: function ( matrix ) {
  3745. this.matrix.multiplyMatrices( matrix, this.matrix );
  3746. this.scale.getScaleFromMatrix( this.matrix );
  3747. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3748. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3749. this.position.getPositionFromMatrix( this.matrix );
  3750. },
  3751. translate: function ( distance, axis ) {
  3752. this.matrix.rotateAxis( axis );
  3753. this.position.add( axis.multiplyScalar( distance ) );
  3754. },
  3755. translateX: function ( distance ) {
  3756. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3757. },
  3758. translateY: function ( distance ) {
  3759. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3760. },
  3761. translateZ: function ( distance ) {
  3762. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3763. },
  3764. localToWorld: function ( vector ) {
  3765. return vector.applyMatrix4( this.matrixWorld );
  3766. },
  3767. worldToLocal: function ( vector ) {
  3768. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3769. },
  3770. lookAt: function ( vector ) {
  3771. // TODO: Add hierarchy support.
  3772. this.matrix.lookAt( vector, this.position, this.up );
  3773. if ( this.rotationAutoUpdate ) {
  3774. if ( this.useQuaternion === false ) {
  3775. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3776. } else {
  3777. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3778. }
  3779. }
  3780. },
  3781. add: function ( object ) {
  3782. if ( object === this ) {
  3783. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3784. return;
  3785. }
  3786. if ( object instanceof THREE.Object3D ) {
  3787. if ( object.parent !== undefined ) {
  3788. object.parent.remove( object );
  3789. }
  3790. object.parent = this;
  3791. this.children.push( object );
  3792. // add to scene
  3793. var scene = this;
  3794. while ( scene.parent !== undefined ) {
  3795. scene = scene.parent;
  3796. }
  3797. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3798. scene.__addObject( object );
  3799. }
  3800. }
  3801. },
  3802. remove: function ( object ) {
  3803. var index = this.children.indexOf( object );
  3804. if ( index !== - 1 ) {
  3805. object.parent = undefined;
  3806. this.children.splice( index, 1 );
  3807. // remove from scene
  3808. var scene = this;
  3809. while ( scene.parent !== undefined ) {
  3810. scene = scene.parent;
  3811. }
  3812. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3813. scene.__removeObject( object );
  3814. }
  3815. }
  3816. },
  3817. traverse: function ( callback ) {
  3818. callback( this );
  3819. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3820. this.children[ i ].traverse( callback );
  3821. }
  3822. },
  3823. getChildByName: function ( name, recursive ) {
  3824. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3825. var child = this.children[ i ];
  3826. if ( child.name === name ) {
  3827. return child;
  3828. }
  3829. if ( recursive === true ) {
  3830. child = child.getChildByName( name, recursive );
  3831. if ( child !== undefined ) {
  3832. return child;
  3833. }
  3834. }
  3835. }
  3836. return undefined;
  3837. },
  3838. getDescendants: function ( array ) {
  3839. if ( array === undefined ) array = [];
  3840. Array.prototype.push.apply( array, this.children );
  3841. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3842. this.children[ i ].getDescendants( array );
  3843. }
  3844. return array;
  3845. },
  3846. updateMatrix: function () {
  3847. this.matrix.setPosition( this.position );
  3848. if ( this.useQuaternion === false ) {
  3849. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3850. } else {
  3851. this.matrix.setRotationFromQuaternion( this.quaternion );
  3852. }
  3853. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3854. this.matrix.scale( this.scale );
  3855. }
  3856. this.matrixWorldNeedsUpdate = true;
  3857. },
  3858. updateMatrixWorld: function ( force ) {
  3859. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3860. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3861. if ( this.parent === undefined ) {
  3862. this.matrixWorld.copy( this.matrix );
  3863. } else {
  3864. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3865. }
  3866. this.matrixWorldNeedsUpdate = false;
  3867. force = true;
  3868. }
  3869. // update children
  3870. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3871. this.children[ i ].updateMatrixWorld( force );
  3872. }
  3873. },
  3874. clone: function ( object ) {
  3875. if ( object === undefined ) object = new THREE.Object3D();
  3876. object.name = this.name;
  3877. object.up.copy( this.up );
  3878. object.position.copy( this.position );
  3879. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3880. object.eulerOrder = this.eulerOrder;
  3881. object.scale.copy( this.scale );
  3882. object.renderDepth = this.renderDepth;
  3883. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3884. object.matrix.copy( this.matrix );
  3885. object.matrixWorld.copy( this.matrixWorld );
  3886. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3887. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3888. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3889. object.quaternion.copy( this.quaternion );
  3890. object.useQuaternion = this.useQuaternion;
  3891. object.visible = this.visible;
  3892. object.castShadow = this.castShadow;
  3893. object.receiveShadow = this.receiveShadow;
  3894. object.frustumCulled = this.frustumCulled;
  3895. for ( var i = 0; i < this.children.length; i ++ ) {
  3896. var child = this.children[ i ];
  3897. object.add( child.clone() );
  3898. }
  3899. return object;
  3900. }
  3901. };
  3902. THREE.Object3D.__m1 = new THREE.Matrix4();
  3903. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3904. THREE.Object3DIdCount = 0;
  3905. /**
  3906. * @author mrdoob / http://mrdoob.com/
  3907. * @author supereggbert / http://www.paulbrunt.co.uk/
  3908. * @author julianwa / https://github.com/julianwa
  3909. */
  3910. THREE.Projector = function () {
  3911. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3912. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3913. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3914. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3915. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3916. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3917. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3918. _vector3 = new THREE.Vector3(),
  3919. _vector4 = new THREE.Vector4(),
  3920. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3921. _boundingBox = new THREE.Box3(),
  3922. _points3 = new Array( 3 ),
  3923. _points4 = new Array( 4 ),
  3924. _viewMatrix = new THREE.Matrix4(),
  3925. _viewProjectionMatrix = new THREE.Matrix4(),
  3926. _modelMatrix,
  3927. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3928. _normalMatrix = new THREE.Matrix3(),
  3929. _normalViewMatrix = new THREE.Matrix3(),
  3930. _centroid = new THREE.Vector3(),
  3931. _frustum = new THREE.Frustum(),
  3932. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3933. _clippedVertex2PositionScreen = new THREE.Vector4();
  3934. this.projectVector = function ( vector, camera ) {
  3935. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3936. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3937. return vector.applyProjection( _viewProjectionMatrix );
  3938. };
  3939. this.unprojectVector = function ( vector, camera ) {
  3940. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3941. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3942. return vector.applyProjection( _viewProjectionMatrix );
  3943. };
  3944. this.pickingRay = function ( vector, camera ) {
  3945. // set two vectors with opposing z values
  3946. vector.z = -1.0;
  3947. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3948. this.unprojectVector( vector, camera );
  3949. this.unprojectVector( end, camera );
  3950. // find direction from vector to end
  3951. end.sub( vector ).normalize();
  3952. return new THREE.Raycaster( vector, end );
  3953. };
  3954. var projectGraph = function ( root, sortObjects ) {
  3955. _objectCount = 0;
  3956. _renderData.objects.length = 0;
  3957. _renderData.sprites.length = 0;
  3958. _renderData.lights.length = 0;
  3959. var projectObject = function ( parent ) {
  3960. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3961. var object = parent.children[ c ];
  3962. if ( object.visible === false ) continue;
  3963. if ( object instanceof THREE.Light ) {
  3964. _renderData.lights.push( object );
  3965. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3966. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3967. _object = getNextObjectInPool();
  3968. _object.object = object;
  3969. if ( object.renderDepth !== null ) {
  3970. _object.z = object.renderDepth;
  3971. } else {
  3972. _vector3.getPositionFromMatrix( object.matrixWorld );
  3973. _vector3.applyProjection( _viewProjectionMatrix );
  3974. _object.z = _vector3.z;
  3975. }
  3976. _renderData.objects.push( _object );
  3977. }
  3978. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3979. _object = getNextObjectInPool();
  3980. _object.object = object;
  3981. // TODO: Find an elegant and performant solution and remove this dupe code.
  3982. if ( object.renderDepth !== null ) {
  3983. _object.z = object.renderDepth;
  3984. } else {
  3985. _vector3.getPositionFromMatrix( object.matrixWorld );
  3986. _vector3.applyProjection( _viewProjectionMatrix );
  3987. _object.z = _vector3.z;
  3988. }
  3989. _renderData.sprites.push( _object );
  3990. } else {
  3991. _object = getNextObjectInPool();
  3992. _object.object = object;
  3993. if ( object.renderDepth !== null ) {
  3994. _object.z = object.renderDepth;
  3995. } else {
  3996. _vector3.getPositionFromMatrix( object.matrixWorld );
  3997. _vector3.applyProjection( _viewProjectionMatrix );
  3998. _object.z = _vector3.z;
  3999. }
  4000. _renderData.objects.push( _object );
  4001. }
  4002. projectObject( object );
  4003. }
  4004. };
  4005. projectObject( root );
  4006. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  4007. return _renderData;
  4008. };
  4009. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4010. var visible = false,
  4011. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4012. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4013. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4014. _face3Count = 0;
  4015. _face4Count = 0;
  4016. _lineCount = 0;
  4017. _particleCount = 0;
  4018. _renderData.elements.length = 0;
  4019. scene.updateMatrixWorld();
  4020. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4021. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4022. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4023. _normalViewMatrix.getInverse( _viewMatrix );
  4024. _normalViewMatrix.transpose();
  4025. _frustum.setFromMatrix( _viewProjectionMatrix );
  4026. _renderData = projectGraph( scene, sortObjects );
  4027. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4028. object = _renderData.objects[ o ].object;
  4029. _modelMatrix = object.matrixWorld;
  4030. _vertexCount = 0;
  4031. if ( object instanceof THREE.Mesh ) {
  4032. geometry = object.geometry;
  4033. vertices = geometry.vertices;
  4034. faces = geometry.faces;
  4035. faceVertexUvs = geometry.faceVertexUvs;
  4036. _normalMatrix.getInverse( _modelMatrix );
  4037. _normalMatrix.transpose();
  4038. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4039. objectMaterials = isFaceMaterial === true ? object.material : null;
  4040. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4041. _vertex = getNextVertexInPool();
  4042. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4043. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4044. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4045. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4046. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4047. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4048. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4049. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4050. }
  4051. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4052. face = faces[ f ];
  4053. var material = isFaceMaterial === true
  4054. ? objectMaterials.materials[ face.materialIndex ]
  4055. : object.material;
  4056. if ( material === undefined ) continue;
  4057. var side = material.side;
  4058. if ( face instanceof THREE.Face3 ) {
  4059. v1 = _vertexPool[ face.a ];
  4060. v2 = _vertexPool[ face.b ];
  4061. v3 = _vertexPool[ face.c ];
  4062. _points3[ 0 ] = v1.positionScreen;
  4063. _points3[ 1 ] = v2.positionScreen;
  4064. _points3[ 2 ] = v3.positionScreen;
  4065. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4066. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4067. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4068. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4069. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4070. _face = getNextFace3InPool();
  4071. _face.v1.copy( v1 );
  4072. _face.v2.copy( v2 );
  4073. _face.v3.copy( v3 );
  4074. } else {
  4075. continue;
  4076. }
  4077. } else {
  4078. continue;
  4079. }
  4080. } else if ( face instanceof THREE.Face4 ) {
  4081. v1 = _vertexPool[ face.a ];
  4082. v2 = _vertexPool[ face.b ];
  4083. v3 = _vertexPool[ face.c ];
  4084. v4 = _vertexPool[ face.d ];
  4085. _points4[ 0 ] = v1.positionScreen;
  4086. _points4[ 1 ] = v2.positionScreen;
  4087. _points4[ 2 ] = v3.positionScreen;
  4088. _points4[ 3 ] = v4.positionScreen;
  4089. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4090. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4091. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4092. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4093. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4094. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4095. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4096. _face = getNextFace4InPool();
  4097. _face.v1.copy( v1 );
  4098. _face.v2.copy( v2 );
  4099. _face.v3.copy( v3 );
  4100. _face.v4.copy( v4 );
  4101. } else {
  4102. continue;
  4103. }
  4104. } else {
  4105. continue;
  4106. }
  4107. }
  4108. _face.normalModel.copy( face.normal );
  4109. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4110. _face.normalModel.negate();
  4111. }
  4112. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4113. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4114. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4115. faceVertexNormals = face.vertexNormals;
  4116. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4117. var normalModel = _face.vertexNormalsModel[ n ];
  4118. normalModel.copy( faceVertexNormals[ n ] );
  4119. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4120. normalModel.negate();
  4121. }
  4122. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4123. var normalModelView = _face.vertexNormalsModelView[ n ];
  4124. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4125. }
  4126. _face.vertexNormalsLength = faceVertexNormals.length;
  4127. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4128. uvs = faceVertexUvs[ c ][ f ];
  4129. if ( uvs === undefined ) continue;
  4130. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4131. _face.uvs[ c ][ u ] = uvs[ u ];
  4132. }
  4133. }
  4134. _face.color = face.color;
  4135. _face.material = material;
  4136. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4137. _face.z = _centroid.z;
  4138. _renderData.elements.push( _face );
  4139. }
  4140. } else if ( object instanceof THREE.Line ) {
  4141. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4142. vertices = object.geometry.vertices;
  4143. v1 = getNextVertexInPool();
  4144. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4145. // Handle LineStrip and LinePieces
  4146. var step = object.type === THREE.LinePieces ? 2 : 1;
  4147. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4148. v1 = getNextVertexInPool();
  4149. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4150. if ( ( v + 1 ) % step > 0 ) continue;
  4151. v2 = _vertexPool[ _vertexCount - 2 ];
  4152. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4153. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4154. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4155. // Perform the perspective divide
  4156. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4157. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4158. _line = getNextLineInPool();
  4159. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4160. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4161. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4162. _line.material = object.material;
  4163. _renderData.elements.push( _line );
  4164. }
  4165. }
  4166. }
  4167. }
  4168. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4169. object = _renderData.sprites[ o ].object;
  4170. _modelMatrix = object.matrixWorld;
  4171. if ( object instanceof THREE.Particle ) {
  4172. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4173. _vector4.applyMatrix4( _viewProjectionMatrix );
  4174. _vector4.z /= _vector4.w;
  4175. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4176. _particle = getNextParticleInPool();
  4177. _particle.object = object;
  4178. _particle.x = _vector4.x / _vector4.w;
  4179. _particle.y = _vector4.y / _vector4.w;
  4180. _particle.z = _vector4.z;
  4181. _particle.rotation = object.rotation.z;
  4182. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4183. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4184. _particle.material = object.material;
  4185. _renderData.elements.push( _particle );
  4186. }
  4187. }
  4188. }
  4189. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4190. return _renderData;
  4191. };
  4192. // Pools
  4193. function getNextObjectInPool() {
  4194. if ( _objectCount === _objectPoolLength ) {
  4195. var object = new THREE.RenderableObject();
  4196. _objectPool.push( object );
  4197. _objectPoolLength ++;
  4198. _objectCount ++;
  4199. return object;
  4200. }
  4201. return _objectPool[ _objectCount ++ ];
  4202. }
  4203. function getNextVertexInPool() {
  4204. if ( _vertexCount === _vertexPoolLength ) {
  4205. var vertex = new THREE.RenderableVertex();
  4206. _vertexPool.push( vertex );
  4207. _vertexPoolLength ++;
  4208. _vertexCount ++;
  4209. return vertex;
  4210. }
  4211. return _vertexPool[ _vertexCount ++ ];
  4212. }
  4213. function getNextFace3InPool() {
  4214. if ( _face3Count === _face3PoolLength ) {
  4215. var face = new THREE.RenderableFace3();
  4216. _face3Pool.push( face );
  4217. _face3PoolLength ++;
  4218. _face3Count ++;
  4219. return face;
  4220. }
  4221. return _face3Pool[ _face3Count ++ ];
  4222. }
  4223. function getNextFace4InPool() {
  4224. if ( _face4Count === _face4PoolLength ) {
  4225. var face = new THREE.RenderableFace4();
  4226. _face4Pool.push( face );
  4227. _face4PoolLength ++;
  4228. _face4Count ++;
  4229. return face;
  4230. }
  4231. return _face4Pool[ _face4Count ++ ];
  4232. }
  4233. function getNextLineInPool() {
  4234. if ( _lineCount === _linePoolLength ) {
  4235. var line = new THREE.RenderableLine();
  4236. _linePool.push( line );
  4237. _linePoolLength ++;
  4238. _lineCount ++
  4239. return line;
  4240. }
  4241. return _linePool[ _lineCount ++ ];
  4242. }
  4243. function getNextParticleInPool() {
  4244. if ( _particleCount === _particlePoolLength ) {
  4245. var particle = new THREE.RenderableParticle();
  4246. _particlePool.push( particle );
  4247. _particlePoolLength ++;
  4248. _particleCount ++
  4249. return particle;
  4250. }
  4251. return _particlePool[ _particleCount ++ ];
  4252. }
  4253. //
  4254. function painterSort( a, b ) {
  4255. return b.z - a.z;
  4256. }
  4257. function clipLine( s1, s2 ) {
  4258. var alpha1 = 0, alpha2 = 1,
  4259. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4260. // Z = -1 and Z = +1, respectively.
  4261. bc1near = s1.z + s1.w,
  4262. bc2near = s2.z + s2.w,
  4263. bc1far = - s1.z + s1.w,
  4264. bc2far = - s2.z + s2.w;
  4265. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4266. // Both vertices lie entirely within all clip planes.
  4267. return true;
  4268. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4269. // Both vertices lie entirely outside one of the clip planes.
  4270. return false;
  4271. } else {
  4272. // The line segment spans at least one clip plane.
  4273. if ( bc1near < 0 ) {
  4274. // v1 lies outside the near plane, v2 inside
  4275. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4276. } else if ( bc2near < 0 ) {
  4277. // v2 lies outside the near plane, v1 inside
  4278. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4279. }
  4280. if ( bc1far < 0 ) {
  4281. // v1 lies outside the far plane, v2 inside
  4282. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4283. } else if ( bc2far < 0 ) {
  4284. // v2 lies outside the far plane, v2 inside
  4285. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4286. }
  4287. if ( alpha2 < alpha1 ) {
  4288. // The line segment spans two boundaries, but is outside both of them.
  4289. // (This can't happen when we're only clipping against just near/far but good
  4290. // to leave the check here for future usage if other clip planes are added.)
  4291. return false;
  4292. } else {
  4293. // Update the s1 and s2 vertices to match the clipped line segment.
  4294. s1.lerp( s2, alpha1 );
  4295. s2.lerp( s1, 1 - alpha2 );
  4296. return true;
  4297. }
  4298. }
  4299. }
  4300. };
  4301. /**
  4302. * @author mrdoob / http://mrdoob.com/
  4303. * @author alteredq / http://alteredqualia.com/
  4304. */
  4305. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4306. this.a = a;
  4307. this.b = b;
  4308. this.c = c;
  4309. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4310. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4311. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4312. this.vertexColors = color instanceof Array ? color : [];
  4313. this.vertexTangents = [];
  4314. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4315. this.centroid = new THREE.Vector3();
  4316. };
  4317. THREE.Face3.prototype = {
  4318. constructor: THREE.Face3,
  4319. clone: function () {
  4320. var face = new THREE.Face3( this.a, this.b, this.c );
  4321. face.normal.copy( this.normal );
  4322. face.color.copy( this.color );
  4323. face.centroid.copy( this.centroid );
  4324. face.materialIndex = this.materialIndex;
  4325. var i, il;
  4326. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4327. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4328. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4329. return face;
  4330. }
  4331. };
  4332. /**
  4333. * @author mrdoob / http://mrdoob.com/
  4334. * @author alteredq / http://alteredqualia.com/
  4335. */
  4336. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4337. this.a = a;
  4338. this.b = b;
  4339. this.c = c;
  4340. this.d = d;
  4341. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4342. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4343. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4344. this.vertexColors = color instanceof Array ? color : [];
  4345. this.vertexTangents = [];
  4346. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4347. this.centroid = new THREE.Vector3();
  4348. };
  4349. THREE.Face4.prototype = {
  4350. constructor: THREE.Face4,
  4351. clone: function () {
  4352. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4353. face.normal.copy( this.normal );
  4354. face.color.copy( this.color );
  4355. face.centroid.copy( this.centroid );
  4356. face.materialIndex = this.materialIndex;
  4357. var i, il;
  4358. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4359. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4360. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4361. return face;
  4362. }
  4363. };
  4364. /**
  4365. * @author mrdoob / http://mrdoob.com/
  4366. * @author kile / http://kile.stravaganza.org/
  4367. * @author alteredq / http://alteredqualia.com/
  4368. * @author mikael emtinger / http://gomo.se/
  4369. * @author zz85 / http://www.lab4games.net/zz85/blog
  4370. * @author bhouston / http://exocortex.com
  4371. */
  4372. THREE.Geometry = function () {
  4373. THREE.EventDispatcher.call( this );
  4374. this.id = THREE.GeometryIdCount ++;
  4375. this.name = '';
  4376. this.vertices = [];
  4377. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4378. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4379. this.faces = [];
  4380. this.faceUvs = [[]];
  4381. this.faceVertexUvs = [[]];
  4382. this.morphTargets = [];
  4383. this.morphColors = [];
  4384. this.morphNormals = [];
  4385. this.skinWeights = [];
  4386. this.skinIndices = [];
  4387. this.lineDistances = [];
  4388. this.boundingBox = null;
  4389. this.boundingSphere = null;
  4390. this.hasTangents = false;
  4391. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4392. // update flags
  4393. this.verticesNeedUpdate = false;
  4394. this.elementsNeedUpdate = false;
  4395. this.uvsNeedUpdate = false;
  4396. this.normalsNeedUpdate = false;
  4397. this.tangentsNeedUpdate = false;
  4398. this.colorsNeedUpdate = false;
  4399. this.lineDistancesNeedUpdate = false;
  4400. this.buffersNeedUpdate = false;
  4401. };
  4402. THREE.Geometry.prototype = {
  4403. constructor: THREE.Geometry,
  4404. applyMatrix: function ( matrix ) {
  4405. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4406. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4407. var vertex = this.vertices[ i ];
  4408. vertex.applyMatrix4( matrix );
  4409. }
  4410. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4411. var face = this.faces[ i ];
  4412. face.normal.applyMatrix3( normalMatrix ).normalize();
  4413. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4414. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4415. }
  4416. face.centroid.applyMatrix4( matrix );
  4417. }
  4418. },
  4419. computeCentroids: function () {
  4420. var f, fl, face;
  4421. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4422. face = this.faces[ f ];
  4423. face.centroid.set( 0, 0, 0 );
  4424. if ( face instanceof THREE.Face3 ) {
  4425. face.centroid.add( this.vertices[ face.a ] );
  4426. face.centroid.add( this.vertices[ face.b ] );
  4427. face.centroid.add( this.vertices[ face.c ] );
  4428. face.centroid.divideScalar( 3 );
  4429. } else if ( face instanceof THREE.Face4 ) {
  4430. face.centroid.add( this.vertices[ face.a ] );
  4431. face.centroid.add( this.vertices[ face.b ] );
  4432. face.centroid.add( this.vertices[ face.c ] );
  4433. face.centroid.add( this.vertices[ face.d ] );
  4434. face.centroid.divideScalar( 4 );
  4435. }
  4436. }
  4437. },
  4438. computeFaceNormals: function () {
  4439. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4440. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4441. var face = this.faces[ f ];
  4442. var vA = this.vertices[ face.a ];
  4443. var vB = this.vertices[ face.b ];
  4444. var vC = this.vertices[ face.c ];
  4445. cb.subVectors( vC, vB );
  4446. ab.subVectors( vA, vB );
  4447. cb.cross( ab );
  4448. cb.normalize();
  4449. face.normal.copy( cb );
  4450. }
  4451. },
  4452. computeVertexNormals: function ( areaWeighted ) {
  4453. var v, vl, f, fl, face, vertices;
  4454. // create internal buffers for reuse when calling this method repeatedly
  4455. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4456. if ( this.__tmpVertices === undefined ) {
  4457. this.__tmpVertices = new Array( this.vertices.length );
  4458. vertices = this.__tmpVertices;
  4459. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4460. vertices[ v ] = new THREE.Vector3();
  4461. }
  4462. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4463. face = this.faces[ f ];
  4464. if ( face instanceof THREE.Face3 ) {
  4465. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4466. } else if ( face instanceof THREE.Face4 ) {
  4467. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4468. }
  4469. }
  4470. } else {
  4471. vertices = this.__tmpVertices;
  4472. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4473. vertices[ v ].set( 0, 0, 0 );
  4474. }
  4475. }
  4476. if ( areaWeighted ) {
  4477. // vertex normals weighted by triangle areas
  4478. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4479. var vA, vB, vC, vD;
  4480. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4481. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4482. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4483. face = this.faces[ f ];
  4484. if ( face instanceof THREE.Face3 ) {
  4485. vA = this.vertices[ face.a ];
  4486. vB = this.vertices[ face.b ];
  4487. vC = this.vertices[ face.c ];
  4488. cb.subVectors( vC, vB );
  4489. ab.subVectors( vA, vB );
  4490. cb.cross( ab );
  4491. vertices[ face.a ].add( cb );
  4492. vertices[ face.b ].add( cb );
  4493. vertices[ face.c ].add( cb );
  4494. } else if ( face instanceof THREE.Face4 ) {
  4495. vA = this.vertices[ face.a ];
  4496. vB = this.vertices[ face.b ];
  4497. vC = this.vertices[ face.c ];
  4498. vD = this.vertices[ face.d ];
  4499. // abd
  4500. db.subVectors( vD, vB );
  4501. ab.subVectors( vA, vB );
  4502. db.cross( ab );
  4503. vertices[ face.a ].add( db );
  4504. vertices[ face.b ].add( db );
  4505. vertices[ face.d ].add( db );
  4506. // bcd
  4507. dc.subVectors( vD, vC );
  4508. bc.subVectors( vB, vC );
  4509. dc.cross( bc );
  4510. vertices[ face.b ].add( dc );
  4511. vertices[ face.c ].add( dc );
  4512. vertices[ face.d ].add( dc );
  4513. }
  4514. }
  4515. } else {
  4516. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4517. face = this.faces[ f ];
  4518. if ( face instanceof THREE.Face3 ) {
  4519. vertices[ face.a ].add( face.normal );
  4520. vertices[ face.b ].add( face.normal );
  4521. vertices[ face.c ].add( face.normal );
  4522. } else if ( face instanceof THREE.Face4 ) {
  4523. vertices[ face.a ].add( face.normal );
  4524. vertices[ face.b ].add( face.normal );
  4525. vertices[ face.c ].add( face.normal );
  4526. vertices[ face.d ].add( face.normal );
  4527. }
  4528. }
  4529. }
  4530. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4531. vertices[ v ].normalize();
  4532. }
  4533. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4534. face = this.faces[ f ];
  4535. if ( face instanceof THREE.Face3 ) {
  4536. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4537. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4538. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4539. } else if ( face instanceof THREE.Face4 ) {
  4540. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4541. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4542. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4543. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4544. }
  4545. }
  4546. },
  4547. computeMorphNormals: function () {
  4548. var i, il, f, fl, face;
  4549. // save original normals
  4550. // - create temp variables on first access
  4551. // otherwise just copy (for faster repeated calls)
  4552. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4553. face = this.faces[ f ];
  4554. if ( ! face.__originalFaceNormal ) {
  4555. face.__originalFaceNormal = face.normal.clone();
  4556. } else {
  4557. face.__originalFaceNormal.copy( face.normal );
  4558. }
  4559. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4560. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4561. if ( ! face.__originalVertexNormals[ i ] ) {
  4562. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4563. } else {
  4564. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4565. }
  4566. }
  4567. }
  4568. // use temp geometry to compute face and vertex normals for each morph
  4569. var tmpGeo = new THREE.Geometry();
  4570. tmpGeo.faces = this.faces;
  4571. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4572. // create on first access
  4573. if ( ! this.morphNormals[ i ] ) {
  4574. this.morphNormals[ i ] = {};
  4575. this.morphNormals[ i ].faceNormals = [];
  4576. this.morphNormals[ i ].vertexNormals = [];
  4577. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4578. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4579. var faceNormal, vertexNormals;
  4580. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4581. face = this.faces[ f ];
  4582. faceNormal = new THREE.Vector3();
  4583. if ( face instanceof THREE.Face3 ) {
  4584. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4585. } else {
  4586. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4587. }
  4588. dstNormalsFace.push( faceNormal );
  4589. dstNormalsVertex.push( vertexNormals );
  4590. }
  4591. }
  4592. var morphNormals = this.morphNormals[ i ];
  4593. // set vertices to morph target
  4594. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4595. // compute morph normals
  4596. tmpGeo.computeFaceNormals();
  4597. tmpGeo.computeVertexNormals();
  4598. // store morph normals
  4599. var faceNormal, vertexNormals;
  4600. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4601. face = this.faces[ f ];
  4602. faceNormal = morphNormals.faceNormals[ f ];
  4603. vertexNormals = morphNormals.vertexNormals[ f ];
  4604. faceNormal.copy( face.normal );
  4605. if ( face instanceof THREE.Face3 ) {
  4606. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4607. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4608. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4609. } else {
  4610. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4611. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4612. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4613. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4614. }
  4615. }
  4616. }
  4617. // restore original normals
  4618. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4619. face = this.faces[ f ];
  4620. face.normal = face.__originalFaceNormal;
  4621. face.vertexNormals = face.__originalVertexNormals;
  4622. }
  4623. },
  4624. computeTangents: function () {
  4625. // based on http://www.terathon.com/code/tangent.html
  4626. // tangents go to vertices
  4627. var f, fl, v, vl, i, il, vertexIndex,
  4628. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4629. x1, x2, y1, y2, z1, z2,
  4630. s1, s2, t1, t2, r, t, test,
  4631. tan1 = [], tan2 = [],
  4632. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4633. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4634. n = new THREE.Vector3(), w;
  4635. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4636. tan1[ v ] = new THREE.Vector3();
  4637. tan2[ v ] = new THREE.Vector3();
  4638. }
  4639. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4640. vA = context.vertices[ a ];
  4641. vB = context.vertices[ b ];
  4642. vC = context.vertices[ c ];
  4643. uvA = uv[ ua ];
  4644. uvB = uv[ ub ];
  4645. uvC = uv[ uc ];
  4646. x1 = vB.x - vA.x;
  4647. x2 = vC.x - vA.x;
  4648. y1 = vB.y - vA.y;
  4649. y2 = vC.y - vA.y;
  4650. z1 = vB.z - vA.z;
  4651. z2 = vC.z - vA.z;
  4652. s1 = uvB.x - uvA.x;
  4653. s2 = uvC.x - uvA.x;
  4654. t1 = uvB.y - uvA.y;
  4655. t2 = uvC.y - uvA.y;
  4656. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4657. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4658. ( t2 * y1 - t1 * y2 ) * r,
  4659. ( t2 * z1 - t1 * z2 ) * r );
  4660. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4661. ( s1 * y2 - s2 * y1 ) * r,
  4662. ( s1 * z2 - s2 * z1 ) * r );
  4663. tan1[ a ].add( sdir );
  4664. tan1[ b ].add( sdir );
  4665. tan1[ c ].add( sdir );
  4666. tan2[ a ].add( tdir );
  4667. tan2[ b ].add( tdir );
  4668. tan2[ c ].add( tdir );
  4669. }
  4670. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4671. face = this.faces[ f ];
  4672. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4673. if ( face instanceof THREE.Face3 ) {
  4674. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4675. } else if ( face instanceof THREE.Face4 ) {
  4676. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4677. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4678. }
  4679. }
  4680. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4681. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4682. face = this.faces[ f ];
  4683. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4684. n.copy( face.vertexNormals[ i ] );
  4685. vertexIndex = face[ faceIndex[ i ] ];
  4686. t = tan1[ vertexIndex ];
  4687. // Gram-Schmidt orthogonalize
  4688. tmp.copy( t );
  4689. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4690. // Calculate handedness
  4691. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4692. test = tmp2.dot( tan2[ vertexIndex ] );
  4693. w = (test < 0.0) ? -1.0 : 1.0;
  4694. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4695. }
  4696. }
  4697. this.hasTangents = true;
  4698. },
  4699. computeLineDistances: function ( ) {
  4700. var d = 0;
  4701. var vertices = this.vertices;
  4702. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4703. if ( i > 0 ) {
  4704. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4705. }
  4706. this.lineDistances[ i ] = d;
  4707. }
  4708. },
  4709. computeBoundingBox: function () {
  4710. if ( this.boundingBox === null ) {
  4711. this.boundingBox = new THREE.Box3();
  4712. }
  4713. this.boundingBox.setFromPoints( this.vertices );
  4714. },
  4715. computeBoundingSphere: function () {
  4716. if ( this.boundingSphere === null ) {
  4717. this.boundingSphere = new THREE.Sphere();
  4718. }
  4719. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4720. },
  4721. /*
  4722. * Checks for duplicate vertices with hashmap.
  4723. * Duplicated vertices are removed
  4724. * and faces' vertices are updated.
  4725. */
  4726. mergeVertices: function () {
  4727. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4728. var unique = [], changes = [];
  4729. var v, key;
  4730. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4731. var precision = Math.pow( 10, precisionPoints );
  4732. var i,il, face;
  4733. var indices, k, j, jl, u;
  4734. // reset cache of vertices as it now will be changing.
  4735. this.__tmpVertices = undefined;
  4736. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4737. v = this.vertices[ i ];
  4738. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4739. if ( verticesMap[ key ] === undefined ) {
  4740. verticesMap[ key ] = i;
  4741. unique.push( this.vertices[ i ] );
  4742. changes[ i ] = unique.length - 1;
  4743. } else {
  4744. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4745. changes[ i ] = changes[ verticesMap[ key ] ];
  4746. }
  4747. };
  4748. // if faces are completely degenerate after merging vertices, we
  4749. // have to remove them from the geometry.
  4750. var faceIndicesToRemove = [];
  4751. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4752. face = this.faces[ i ];
  4753. if ( face instanceof THREE.Face3 ) {
  4754. face.a = changes[ face.a ];
  4755. face.b = changes[ face.b ];
  4756. face.c = changes[ face.c ];
  4757. indices = [ face.a, face.b, face.c ];
  4758. var dupIndex = -1;
  4759. // if any duplicate vertices are found in a Face3
  4760. // we have to remove the face as nothing can be saved
  4761. for ( var n = 0; n < 3; n ++ ) {
  4762. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4763. dupIndex = n;
  4764. faceIndicesToRemove.push( i );
  4765. break;
  4766. }
  4767. }
  4768. } else if ( face instanceof THREE.Face4 ) {
  4769. face.a = changes[ face.a ];
  4770. face.b = changes[ face.b ];
  4771. face.c = changes[ face.c ];
  4772. face.d = changes[ face.d ];
  4773. // check dups in (a, b, c, d) and convert to -> face3
  4774. indices = [ face.a, face.b, face.c, face.d ];
  4775. var dupIndex = -1;
  4776. for ( var n = 0; n < 4; n ++ ) {
  4777. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4778. // if more than one duplicated vertex is found
  4779. // we can't generate any valid Face3's, thus
  4780. // we need to remove this face complete.
  4781. if ( dupIndex >= 0 ) {
  4782. faceIndicesToRemove.push( i );
  4783. }
  4784. dupIndex = n;
  4785. }
  4786. }
  4787. if ( dupIndex >= 0 ) {
  4788. indices.splice( dupIndex, 1 );
  4789. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4790. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4791. u = this.faceVertexUvs[ j ][ i ];
  4792. if ( u ) {
  4793. u.splice( dupIndex, 1 );
  4794. }
  4795. }
  4796. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4797. newFace.vertexNormals = face.vertexNormals;
  4798. newFace.vertexNormals.splice( dupIndex, 1 );
  4799. }
  4800. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4801. newFace.vertexColors = face.vertexColors;
  4802. newFace.vertexColors.splice( dupIndex, 1 );
  4803. }
  4804. this.faces[ i ] = newFace;
  4805. }
  4806. }
  4807. }
  4808. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4809. this.faces.splice( i, 1 );
  4810. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4811. this.faceVertexUvs[ j ].splice( i, 1 );
  4812. }
  4813. }
  4814. // Use unique set of vertices
  4815. var diff = this.vertices.length - unique.length;
  4816. this.vertices = unique;
  4817. return diff;
  4818. },
  4819. clone: function () {
  4820. var geometry = new THREE.Geometry();
  4821. var vertices = this.vertices;
  4822. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4823. geometry.vertices.push( vertices[ i ].clone() );
  4824. }
  4825. var faces = this.faces;
  4826. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4827. geometry.faces.push( faces[ i ].clone() );
  4828. }
  4829. var uvs = this.faceVertexUvs[ 0 ];
  4830. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4831. var uv = uvs[ i ], uvCopy = [];
  4832. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4833. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4834. }
  4835. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4836. }
  4837. return geometry;
  4838. },
  4839. dispose: function () {
  4840. this.dispatchEvent( { type: 'dispose' } );
  4841. }
  4842. };
  4843. THREE.GeometryIdCount = 0;
  4844. /**
  4845. * @author alteredq / http://alteredqualia.com/
  4846. */
  4847. THREE.BufferGeometry = function () {
  4848. THREE.EventDispatcher.call( this );
  4849. this.id = THREE.GeometryIdCount ++;
  4850. // attributes
  4851. this.attributes = {};
  4852. // attributes typed arrays are kept only if dynamic flag is set
  4853. this.dynamic = false;
  4854. // offsets for chunks when using indexed elements
  4855. this.offsets = [];
  4856. // boundings
  4857. this.boundingBox = null;
  4858. this.boundingSphere = null;
  4859. this.hasTangents = false;
  4860. // for compatibility
  4861. this.morphTargets = [];
  4862. };
  4863. THREE.BufferGeometry.prototype = {
  4864. constructor : THREE.BufferGeometry,
  4865. applyMatrix: function ( matrix ) {
  4866. var positionArray;
  4867. var normalArray;
  4868. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4869. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4870. if ( positionArray !== undefined ) {
  4871. matrix.multiplyVector3Array( positionArray );
  4872. this.verticesNeedUpdate = true;
  4873. }
  4874. if ( normalArray !== undefined ) {
  4875. var normalMatrix = new THREE.Matrix3();
  4876. normalMatrix.getInverse( matrix ).transpose();
  4877. normalMatrix.multiplyVector3Array( normalArray );
  4878. this.normalizeNormals();
  4879. this.normalsNeedUpdate = true;
  4880. }
  4881. },
  4882. computeBoundingBox: function () {
  4883. if ( this.boundingBox === null ) {
  4884. this.boundingBox = new THREE.Box3();
  4885. }
  4886. var positions = this.attributes[ "position" ].array;
  4887. if ( positions ) {
  4888. var bb = this.boundingBox;
  4889. var x, y, z;
  4890. if( positions.length >= 3 ) {
  4891. bb.min.x = bb.max.x = positions[ 0 ];
  4892. bb.min.y = bb.max.y = positions[ 1 ];
  4893. bb.min.z = bb.max.z = positions[ 2 ];
  4894. }
  4895. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4896. x = positions[ i ];
  4897. y = positions[ i + 1 ];
  4898. z = positions[ i + 2 ];
  4899. // bounding box
  4900. if ( x < bb.min.x ) {
  4901. bb.min.x = x;
  4902. } else if ( x > bb.max.x ) {
  4903. bb.max.x = x;
  4904. }
  4905. if ( y < bb.min.y ) {
  4906. bb.min.y = y;
  4907. } else if ( y > bb.max.y ) {
  4908. bb.max.y = y;
  4909. }
  4910. if ( z < bb.min.z ) {
  4911. bb.min.z = z;
  4912. } else if ( z > bb.max.z ) {
  4913. bb.max.z = z;
  4914. }
  4915. }
  4916. }
  4917. if ( positions === undefined || positions.length === 0 ) {
  4918. this.boundingBox.min.set( 0, 0, 0 );
  4919. this.boundingBox.max.set( 0, 0, 0 );
  4920. }
  4921. },
  4922. computeBoundingSphere: function () {
  4923. if ( this.boundingSphere === null ) {
  4924. this.boundingSphere = new THREE.Sphere();
  4925. }
  4926. var positions = this.attributes[ "position" ].array;
  4927. if ( positions ) {
  4928. var radiusSq, maxRadiusSq = 0;
  4929. var x, y, z;
  4930. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4931. x = positions[ i ];
  4932. y = positions[ i + 1 ];
  4933. z = positions[ i + 2 ];
  4934. radiusSq = x * x + y * y + z * z;
  4935. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4936. }
  4937. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4938. }
  4939. },
  4940. computeVertexNormals: function () {
  4941. if ( this.attributes[ "position" ] ) {
  4942. var i, il;
  4943. var j, jl;
  4944. var nVertexElements = this.attributes[ "position" ].array.length;
  4945. if ( this.attributes[ "normal" ] === undefined ) {
  4946. this.attributes[ "normal" ] = {
  4947. itemSize: 3,
  4948. array: new Float32Array( nVertexElements ),
  4949. numItems: nVertexElements
  4950. };
  4951. } else {
  4952. // reset existing normals to zero
  4953. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4954. this.attributes[ "normal" ].array[ i ] = 0;
  4955. }
  4956. }
  4957. var positions = this.attributes[ "position" ].array;
  4958. var normals = this.attributes[ "normal" ].array;
  4959. var vA, vB, vC, x, y, z,
  4960. pA = new THREE.Vector3(),
  4961. pB = new THREE.Vector3(),
  4962. pC = new THREE.Vector3(),
  4963. cb = new THREE.Vector3(),
  4964. ab = new THREE.Vector3();
  4965. // indexed elements
  4966. if ( this.attributes[ "index" ] ) {
  4967. var indices = this.attributes[ "index" ].array;
  4968. var offsets = this.offsets;
  4969. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4970. var start = offsets[ j ].start;
  4971. var count = offsets[ j ].count;
  4972. var index = offsets[ j ].index;
  4973. for ( i = start, il = start + count; i < il; i += 3 ) {
  4974. vA = index + indices[ i ];
  4975. vB = index + indices[ i + 1 ];
  4976. vC = index + indices[ i + 2 ];
  4977. x = positions[ vA * 3 ];
  4978. y = positions[ vA * 3 + 1 ];
  4979. z = positions[ vA * 3 + 2 ];
  4980. pA.set( x, y, z );
  4981. x = positions[ vB * 3 ];
  4982. y = positions[ vB * 3 + 1 ];
  4983. z = positions[ vB * 3 + 2 ];
  4984. pB.set( x, y, z );
  4985. x = positions[ vC * 3 ];
  4986. y = positions[ vC * 3 + 1 ];
  4987. z = positions[ vC * 3 + 2 ];
  4988. pC.set( x, y, z );
  4989. cb.subVectors( pC, pB );
  4990. ab.subVectors( pA, pB );
  4991. cb.cross( ab );
  4992. normals[ vA * 3 ] += cb.x;
  4993. normals[ vA * 3 + 1 ] += cb.y;
  4994. normals[ vA * 3 + 2 ] += cb.z;
  4995. normals[ vB * 3 ] += cb.x;
  4996. normals[ vB * 3 + 1 ] += cb.y;
  4997. normals[ vB * 3 + 2 ] += cb.z;
  4998. normals[ vC * 3 ] += cb.x;
  4999. normals[ vC * 3 + 1 ] += cb.y;
  5000. normals[ vC * 3 + 2 ] += cb.z;
  5001. }
  5002. }
  5003. // non-indexed elements (unconnected triangle soup)
  5004. } else {
  5005. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5006. x = positions[ i ];
  5007. y = positions[ i + 1 ];
  5008. z = positions[ i + 2 ];
  5009. pA.set( x, y, z );
  5010. x = positions[ i + 3 ];
  5011. y = positions[ i + 4 ];
  5012. z = positions[ i + 5 ];
  5013. pB.set( x, y, z );
  5014. x = positions[ i + 6 ];
  5015. y = positions[ i + 7 ];
  5016. z = positions[ i + 8 ];
  5017. pC.set( x, y, z );
  5018. cb.subVectors( pC, pB );
  5019. ab.subVectors( pA, pB );
  5020. cb.cross( ab );
  5021. normals[ i ] = cb.x;
  5022. normals[ i + 1 ] = cb.y;
  5023. normals[ i + 2 ] = cb.z;
  5024. normals[ i + 3 ] = cb.x;
  5025. normals[ i + 4 ] = cb.y;
  5026. normals[ i + 5 ] = cb.z;
  5027. normals[ i + 6 ] = cb.x;
  5028. normals[ i + 7 ] = cb.y;
  5029. normals[ i + 8 ] = cb.z;
  5030. }
  5031. }
  5032. this.normalizeNormals();
  5033. this.normalsNeedUpdate = true;
  5034. }
  5035. },
  5036. normalizeNormals: function () {
  5037. var normals = this.attributes[ "normal" ].array;
  5038. var x, y, z, n;
  5039. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5040. x = normals[ i ];
  5041. y = normals[ i + 1 ];
  5042. z = normals[ i + 2 ];
  5043. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5044. normals[ i ] *= n;
  5045. normals[ i + 1 ] *= n;
  5046. normals[ i + 2 ] *= n;
  5047. }
  5048. },
  5049. computeTangents: function () {
  5050. // based on http://www.terathon.com/code/tangent.html
  5051. // (per vertex tangents)
  5052. if ( this.attributes[ "index" ] === undefined ||
  5053. this.attributes[ "position" ] === undefined ||
  5054. this.attributes[ "normal" ] === undefined ||
  5055. this.attributes[ "uv" ] === undefined ) {
  5056. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5057. return;
  5058. }
  5059. var indices = this.attributes[ "index" ].array;
  5060. var positions = this.attributes[ "position" ].array;
  5061. var normals = this.attributes[ "normal" ].array;
  5062. var uvs = this.attributes[ "uv" ].array;
  5063. var nVertices = positions.length / 3;
  5064. if ( this.attributes[ "tangent" ] === undefined ) {
  5065. var nTangentElements = 4 * nVertices;
  5066. this.attributes[ "tangent" ] = {
  5067. itemSize: 4,
  5068. array: new Float32Array( nTangentElements ),
  5069. numItems: nTangentElements
  5070. };
  5071. }
  5072. var tangents = this.attributes[ "tangent" ].array;
  5073. var tan1 = [], tan2 = [];
  5074. for ( var k = 0; k < nVertices; k ++ ) {
  5075. tan1[ k ] = new THREE.Vector3();
  5076. tan2[ k ] = new THREE.Vector3();
  5077. }
  5078. var xA, yA, zA,
  5079. xB, yB, zB,
  5080. xC, yC, zC,
  5081. uA, vA,
  5082. uB, vB,
  5083. uC, vC,
  5084. x1, x2, y1, y2, z1, z2,
  5085. s1, s2, t1, t2, r;
  5086. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5087. function handleTriangle( a, b, c ) {
  5088. xA = positions[ a * 3 ];
  5089. yA = positions[ a * 3 + 1 ];
  5090. zA = positions[ a * 3 + 2 ];
  5091. xB = positions[ b * 3 ];
  5092. yB = positions[ b * 3 + 1 ];
  5093. zB = positions[ b * 3 + 2 ];
  5094. xC = positions[ c * 3 ];
  5095. yC = positions[ c * 3 + 1 ];
  5096. zC = positions[ c * 3 + 2 ];
  5097. uA = uvs[ a * 2 ];
  5098. vA = uvs[ a * 2 + 1 ];
  5099. uB = uvs[ b * 2 ];
  5100. vB = uvs[ b * 2 + 1 ];
  5101. uC = uvs[ c * 2 ];
  5102. vC = uvs[ c * 2 + 1 ];
  5103. x1 = xB - xA;
  5104. x2 = xC - xA;
  5105. y1 = yB - yA;
  5106. y2 = yC - yA;
  5107. z1 = zB - zA;
  5108. z2 = zC - zA;
  5109. s1 = uB - uA;
  5110. s2 = uC - uA;
  5111. t1 = vB - vA;
  5112. t2 = vC - vA;
  5113. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5114. sdir.set(
  5115. ( t2 * x1 - t1 * x2 ) * r,
  5116. ( t2 * y1 - t1 * y2 ) * r,
  5117. ( t2 * z1 - t1 * z2 ) * r
  5118. );
  5119. tdir.set(
  5120. ( s1 * x2 - s2 * x1 ) * r,
  5121. ( s1 * y2 - s2 * y1 ) * r,
  5122. ( s1 * z2 - s2 * z1 ) * r
  5123. );
  5124. tan1[ a ].add( sdir );
  5125. tan1[ b ].add( sdir );
  5126. tan1[ c ].add( sdir );
  5127. tan2[ a ].add( tdir );
  5128. tan2[ b ].add( tdir );
  5129. tan2[ c ].add( tdir );
  5130. }
  5131. var i, il;
  5132. var j, jl;
  5133. var iA, iB, iC;
  5134. var offsets = this.offsets;
  5135. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5136. var start = offsets[ j ].start;
  5137. var count = offsets[ j ].count;
  5138. var index = offsets[ j ].index;
  5139. for ( i = start, il = start + count; i < il; i += 3 ) {
  5140. iA = index + indices[ i ];
  5141. iB = index + indices[ i + 1 ];
  5142. iC = index + indices[ i + 2 ];
  5143. handleTriangle( iA, iB, iC );
  5144. }
  5145. }
  5146. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5147. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5148. var w, t, test;
  5149. function handleVertex( v ) {
  5150. n.x = normals[ v * 3 ];
  5151. n.y = normals[ v * 3 + 1 ];
  5152. n.z = normals[ v * 3 + 2 ];
  5153. n2.copy( n );
  5154. t = tan1[ v ];
  5155. // Gram-Schmidt orthogonalize
  5156. tmp.copy( t );
  5157. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5158. // Calculate handedness
  5159. tmp2.crossVectors( n2, t );
  5160. test = tmp2.dot( tan2[ v ] );
  5161. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5162. tangents[ v * 4 ] = tmp.x;
  5163. tangents[ v * 4 + 1 ] = tmp.y;
  5164. tangents[ v * 4 + 2 ] = tmp.z;
  5165. tangents[ v * 4 + 3 ] = w;
  5166. }
  5167. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5168. var start = offsets[ j ].start;
  5169. var count = offsets[ j ].count;
  5170. var index = offsets[ j ].index;
  5171. for ( i = start, il = start + count; i < il; i += 3 ) {
  5172. iA = index + indices[ i ];
  5173. iB = index + indices[ i + 1 ];
  5174. iC = index + indices[ i + 2 ];
  5175. handleVertex( iA );
  5176. handleVertex( iB );
  5177. handleVertex( iC );
  5178. }
  5179. }
  5180. this.hasTangents = true;
  5181. this.tangentsNeedUpdate = true;
  5182. },
  5183. dispose: function () {
  5184. this.dispatchEvent( { type: 'dispose' } );
  5185. }
  5186. };
  5187. /**
  5188. * @author mrdoob / http://mrdoob.com/
  5189. * @author mikael emtinger / http://gomo.se/
  5190. */
  5191. THREE.Camera = function () {
  5192. THREE.Object3D.call( this );
  5193. this.matrixWorldInverse = new THREE.Matrix4();
  5194. this.projectionMatrix = new THREE.Matrix4();
  5195. this.projectionMatrixInverse = new THREE.Matrix4();
  5196. };
  5197. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5198. THREE.Camera.prototype.lookAt = function ( vector ) {
  5199. // TODO: Add hierarchy support.
  5200. this.matrix.lookAt( this.position, vector, this.up );
  5201. if ( this.rotationAutoUpdate === true ) {
  5202. if ( this.useQuaternion === false ) {
  5203. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5204. } else {
  5205. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5206. }
  5207. }
  5208. };
  5209. /**
  5210. * @author alteredq / http://alteredqualia.com/
  5211. */
  5212. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5213. THREE.Camera.call( this );
  5214. this.left = left;
  5215. this.right = right;
  5216. this.top = top;
  5217. this.bottom = bottom;
  5218. this.near = ( near !== undefined ) ? near : 0.1;
  5219. this.far = ( far !== undefined ) ? far : 2000;
  5220. this.updateProjectionMatrix();
  5221. };
  5222. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5223. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5224. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5225. };
  5226. /**
  5227. * @author mrdoob / http://mrdoob.com/
  5228. * @author greggman / http://games.greggman.com/
  5229. * @author zz85 / http://www.lab4games.net/zz85/blog
  5230. */
  5231. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5232. THREE.Camera.call( this );
  5233. this.fov = fov !== undefined ? fov : 50;
  5234. this.aspect = aspect !== undefined ? aspect : 1;
  5235. this.near = near !== undefined ? near : 0.1;
  5236. this.far = far !== undefined ? far : 2000;
  5237. this.updateProjectionMatrix();
  5238. };
  5239. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5240. /**
  5241. * Uses Focal Length (in mm) to estimate and set FOV
  5242. * 35mm (fullframe) camera is used if frame size is not specified;
  5243. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5244. */
  5245. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5246. if ( frameHeight === undefined ) frameHeight = 24;
  5247. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5248. this.updateProjectionMatrix();
  5249. }
  5250. /**
  5251. * Sets an offset in a larger frustum. This is useful for multi-window or
  5252. * multi-monitor/multi-machine setups.
  5253. *
  5254. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5255. * the monitors are in grid like this
  5256. *
  5257. * +---+---+---+
  5258. * | A | B | C |
  5259. * +---+---+---+
  5260. * | D | E | F |
  5261. * +---+---+---+
  5262. *
  5263. * then for each monitor you would call it like this
  5264. *
  5265. * var w = 1920;
  5266. * var h = 1080;
  5267. * var fullWidth = w * 3;
  5268. * var fullHeight = h * 2;
  5269. *
  5270. * --A--
  5271. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5272. * --B--
  5273. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5274. * --C--
  5275. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5276. * --D--
  5277. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5278. * --E--
  5279. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5280. * --F--
  5281. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5282. *
  5283. * Note there is no reason monitors have to be the same size or in a grid.
  5284. */
  5285. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5286. this.fullWidth = fullWidth;
  5287. this.fullHeight = fullHeight;
  5288. this.x = x;
  5289. this.y = y;
  5290. this.width = width;
  5291. this.height = height;
  5292. this.updateProjectionMatrix();
  5293. };
  5294. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5295. if ( this.fullWidth ) {
  5296. var aspect = this.fullWidth / this.fullHeight;
  5297. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5298. var bottom = -top;
  5299. var left = aspect * bottom;
  5300. var right = aspect * top;
  5301. var width = Math.abs( right - left );
  5302. var height = Math.abs( top - bottom );
  5303. this.projectionMatrix.makeFrustum(
  5304. left + this.x * width / this.fullWidth,
  5305. left + ( this.x + this.width ) * width / this.fullWidth,
  5306. top - ( this.y + this.height ) * height / this.fullHeight,
  5307. top - this.y * height / this.fullHeight,
  5308. this.near,
  5309. this.far
  5310. );
  5311. } else {
  5312. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5313. }
  5314. };
  5315. /**
  5316. * @author mrdoob / http://mrdoob.com/
  5317. * @author alteredq / http://alteredqualia.com/
  5318. */
  5319. THREE.Light = function ( hex ) {
  5320. THREE.Object3D.call( this );
  5321. this.color = new THREE.Color( hex );
  5322. };
  5323. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5324. /**
  5325. * @author mrdoob / http://mrdoob.com/
  5326. */
  5327. THREE.AmbientLight = function ( hex ) {
  5328. THREE.Light.call( this, hex );
  5329. };
  5330. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5331. /**
  5332. * @author MPanknin / http://www.redplant.de/
  5333. * @author alteredq / http://alteredqualia.com/
  5334. */
  5335. THREE.AreaLight = function ( hex, intensity ) {
  5336. THREE.Light.call( this, hex );
  5337. this.normal = new THREE.Vector3( 0, -1, 0 );
  5338. this.right = new THREE.Vector3( 1, 0, 0 );
  5339. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5340. this.width = 1.0;
  5341. this.height = 1.0;
  5342. this.constantAttenuation = 1.5;
  5343. this.linearAttenuation = 0.5;
  5344. this.quadraticAttenuation = 0.1;
  5345. };
  5346. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5347. /**
  5348. * @author mrdoob / http://mrdoob.com/
  5349. * @author alteredq / http://alteredqualia.com/
  5350. */
  5351. THREE.DirectionalLight = function ( hex, intensity ) {
  5352. THREE.Light.call( this, hex );
  5353. this.position = new THREE.Vector3( 0, 1, 0 );
  5354. this.target = new THREE.Object3D();
  5355. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5356. this.castShadow = false;
  5357. this.onlyShadow = false;
  5358. //
  5359. this.shadowCameraNear = 50;
  5360. this.shadowCameraFar = 5000;
  5361. this.shadowCameraLeft = -500;
  5362. this.shadowCameraRight = 500;
  5363. this.shadowCameraTop = 500;
  5364. this.shadowCameraBottom = -500;
  5365. this.shadowCameraVisible = false;
  5366. this.shadowBias = 0;
  5367. this.shadowDarkness = 0.5;
  5368. this.shadowMapWidth = 512;
  5369. this.shadowMapHeight = 512;
  5370. //
  5371. this.shadowCascade = false;
  5372. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5373. this.shadowCascadeCount = 2;
  5374. this.shadowCascadeBias = [ 0, 0, 0 ];
  5375. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5376. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5377. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5378. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5379. this.shadowCascadeArray = [];
  5380. //
  5381. this.shadowMap = null;
  5382. this.shadowMapSize = null;
  5383. this.shadowCamera = null;
  5384. this.shadowMatrix = null;
  5385. };
  5386. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5387. /**
  5388. * @author alteredq / http://alteredqualia.com/
  5389. */
  5390. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5391. THREE.Light.call( this, skyColorHex );
  5392. this.groundColor = new THREE.Color( groundColorHex );
  5393. this.position = new THREE.Vector3( 0, 100, 0 );
  5394. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5395. };
  5396. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5397. /**
  5398. * @author mrdoob / http://mrdoob.com/
  5399. */
  5400. THREE.PointLight = function ( hex, intensity, distance ) {
  5401. THREE.Light.call( this, hex );
  5402. this.position = new THREE.Vector3( 0, 0, 0 );
  5403. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5404. this.distance = ( distance !== undefined ) ? distance : 0;
  5405. };
  5406. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5407. /**
  5408. * @author alteredq / http://alteredqualia.com/
  5409. */
  5410. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5411. THREE.Light.call( this, hex );
  5412. this.position = new THREE.Vector3( 0, 1, 0 );
  5413. this.target = new THREE.Object3D();
  5414. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5415. this.distance = ( distance !== undefined ) ? distance : 0;
  5416. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5417. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5418. this.castShadow = false;
  5419. this.onlyShadow = false;
  5420. //
  5421. this.shadowCameraNear = 50;
  5422. this.shadowCameraFar = 5000;
  5423. this.shadowCameraFov = 50;
  5424. this.shadowCameraVisible = false;
  5425. this.shadowBias = 0;
  5426. this.shadowDarkness = 0.5;
  5427. this.shadowMapWidth = 512;
  5428. this.shadowMapHeight = 512;
  5429. //
  5430. this.shadowMap = null;
  5431. this.shadowMapSize = null;
  5432. this.shadowCamera = null;
  5433. this.shadowMatrix = null;
  5434. };
  5435. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5436. /**
  5437. * @author alteredq / http://alteredqualia.com/
  5438. */
  5439. THREE.Loader = function ( showStatus ) {
  5440. this.showStatus = showStatus;
  5441. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5442. this.onLoadStart = function () {};
  5443. this.onLoadProgress = function () {};
  5444. this.onLoadComplete = function () {};
  5445. };
  5446. THREE.Loader.prototype = {
  5447. constructor: THREE.Loader,
  5448. crossOrigin: 'anonymous',
  5449. addStatusElement: function () {
  5450. var e = document.createElement( "div" );
  5451. e.style.position = "absolute";
  5452. e.style.right = "0px";
  5453. e.style.top = "0px";
  5454. e.style.fontSize = "0.8em";
  5455. e.style.textAlign = "left";
  5456. e.style.background = "rgba(0,0,0,0.25)";
  5457. e.style.color = "#fff";
  5458. e.style.width = "120px";
  5459. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5460. e.style.zIndex = 1000;
  5461. e.innerHTML = "Loading ...";
  5462. return e;
  5463. },
  5464. updateProgress: function ( progress ) {
  5465. var message = "Loaded ";
  5466. if ( progress.total ) {
  5467. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5468. } else {
  5469. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5470. }
  5471. this.statusDomElement.innerHTML = message;
  5472. },
  5473. extractUrlBase: function ( url ) {
  5474. var parts = url.split( '/' );
  5475. parts.pop();
  5476. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5477. },
  5478. initMaterials: function ( materials, texturePath ) {
  5479. var array = [];
  5480. for ( var i = 0; i < materials.length; ++ i ) {
  5481. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5482. }
  5483. return array;
  5484. },
  5485. needsTangents: function ( materials ) {
  5486. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5487. var m = materials[ i ];
  5488. if ( m instanceof THREE.ShaderMaterial ) return true;
  5489. }
  5490. return false;
  5491. },
  5492. createMaterial: function ( m, texturePath ) {
  5493. var _this = this;
  5494. function is_pow2( n ) {
  5495. var l = Math.log( n ) / Math.LN2;
  5496. return Math.floor( l ) == l;
  5497. }
  5498. function nearest_pow2( n ) {
  5499. var l = Math.log( n ) / Math.LN2;
  5500. return Math.pow( 2, Math.round( l ) );
  5501. }
  5502. function load_image( where, url ) {
  5503. var image = new Image();
  5504. image.onload = function () {
  5505. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5506. var width = nearest_pow2( this.width );
  5507. var height = nearest_pow2( this.height );
  5508. where.image.width = width;
  5509. where.image.height = height;
  5510. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5511. } else {
  5512. where.image = this;
  5513. }
  5514. where.needsUpdate = true;
  5515. };
  5516. image.crossOrigin = _this.crossOrigin;
  5517. image.src = url;
  5518. }
  5519. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5520. var isCompressed = /\.dds$/i.test( sourceFile );
  5521. var fullPath = texturePath + "/" + sourceFile;
  5522. if ( isCompressed ) {
  5523. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5524. where[ name ] = texture;
  5525. } else {
  5526. var texture = document.createElement( 'canvas' );
  5527. where[ name ] = new THREE.Texture( texture );
  5528. }
  5529. where[ name ].sourceFile = sourceFile;
  5530. if( repeat ) {
  5531. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5532. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5533. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5534. }
  5535. if ( offset ) {
  5536. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5537. }
  5538. if ( wrap ) {
  5539. var wrapMap = {
  5540. "repeat": THREE.RepeatWrapping,
  5541. "mirror": THREE.MirroredRepeatWrapping
  5542. }
  5543. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5544. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5545. }
  5546. if ( anisotropy ) {
  5547. where[ name ].anisotropy = anisotropy;
  5548. }
  5549. if ( ! isCompressed ) {
  5550. load_image( where[ name ], fullPath );
  5551. }
  5552. }
  5553. function rgb2hex( rgb ) {
  5554. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5555. }
  5556. // defaults
  5557. var mtype = "MeshLambertMaterial";
  5558. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5559. // parameters from model file
  5560. if ( m.shading ) {
  5561. var shading = m.shading.toLowerCase();
  5562. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5563. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5564. }
  5565. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5566. mpars.blending = THREE[ m.blending ];
  5567. }
  5568. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5569. mpars.transparent = m.transparent;
  5570. }
  5571. if ( m.depthTest !== undefined ) {
  5572. mpars.depthTest = m.depthTest;
  5573. }
  5574. if ( m.depthWrite !== undefined ) {
  5575. mpars.depthWrite = m.depthWrite;
  5576. }
  5577. if ( m.visible !== undefined ) {
  5578. mpars.visible = m.visible;
  5579. }
  5580. if ( m.flipSided !== undefined ) {
  5581. mpars.side = THREE.BackSide;
  5582. }
  5583. if ( m.doubleSided !== undefined ) {
  5584. mpars.side = THREE.DoubleSide;
  5585. }
  5586. if ( m.wireframe !== undefined ) {
  5587. mpars.wireframe = m.wireframe;
  5588. }
  5589. if ( m.vertexColors !== undefined ) {
  5590. if ( m.vertexColors === "face" ) {
  5591. mpars.vertexColors = THREE.FaceColors;
  5592. } else if ( m.vertexColors ) {
  5593. mpars.vertexColors = THREE.VertexColors;
  5594. }
  5595. }
  5596. // colors
  5597. if ( m.colorDiffuse ) {
  5598. mpars.color = rgb2hex( m.colorDiffuse );
  5599. } else if ( m.DbgColor ) {
  5600. mpars.color = m.DbgColor;
  5601. }
  5602. if ( m.colorSpecular ) {
  5603. mpars.specular = rgb2hex( m.colorSpecular );
  5604. }
  5605. if ( m.colorAmbient ) {
  5606. mpars.ambient = rgb2hex( m.colorAmbient );
  5607. }
  5608. // modifiers
  5609. if ( m.transparency ) {
  5610. mpars.opacity = m.transparency;
  5611. }
  5612. if ( m.specularCoef ) {
  5613. mpars.shininess = m.specularCoef;
  5614. }
  5615. // textures
  5616. if ( m.mapDiffuse && texturePath ) {
  5617. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5618. }
  5619. if ( m.mapLight && texturePath ) {
  5620. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5621. }
  5622. if ( m.mapBump && texturePath ) {
  5623. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5624. }
  5625. if ( m.mapNormal && texturePath ) {
  5626. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5627. }
  5628. if ( m.mapSpecular && texturePath ) {
  5629. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5630. }
  5631. //
  5632. if ( m.mapBumpScale ) {
  5633. mpars.bumpScale = m.mapBumpScale;
  5634. }
  5635. // special case for normal mapped material
  5636. if ( m.mapNormal ) {
  5637. var shader = THREE.ShaderLib[ "normalmap" ];
  5638. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5639. uniforms[ "tNormal" ].value = mpars.normalMap;
  5640. if ( m.mapNormalFactor ) {
  5641. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5642. }
  5643. if ( mpars.map ) {
  5644. uniforms[ "tDiffuse" ].value = mpars.map;
  5645. uniforms[ "enableDiffuse" ].value = true;
  5646. }
  5647. if ( mpars.specularMap ) {
  5648. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5649. uniforms[ "enableSpecular" ].value = true;
  5650. }
  5651. if ( mpars.lightMap ) {
  5652. uniforms[ "tAO" ].value = mpars.lightMap;
  5653. uniforms[ "enableAO" ].value = true;
  5654. }
  5655. // for the moment don't handle displacement texture
  5656. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5657. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5658. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5659. uniforms[ "uShininess" ].value = mpars.shininess;
  5660. if ( mpars.opacity !== undefined ) {
  5661. uniforms[ "uOpacity" ].value = mpars.opacity;
  5662. }
  5663. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5664. var material = new THREE.ShaderMaterial( parameters );
  5665. if ( mpars.transparent ) {
  5666. material.transparent = true;
  5667. }
  5668. } else {
  5669. var material = new THREE[ mtype ]( mpars );
  5670. }
  5671. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5672. return material;
  5673. }
  5674. };
  5675. /**
  5676. * @author mrdoob / http://mrdoob.com/
  5677. */
  5678. THREE.ImageLoader = function () {
  5679. THREE.EventDispatcher.call( this );
  5680. this.crossOrigin = null;
  5681. };
  5682. THREE.ImageLoader.prototype = {
  5683. constructor: THREE.ImageLoader,
  5684. load: function ( url, image ) {
  5685. var scope = this;
  5686. if ( image === undefined ) image = new Image();
  5687. image.addEventListener( 'load', function () {
  5688. scope.dispatchEvent( { type: 'load', content: image } );
  5689. }, false );
  5690. image.addEventListener( 'error', function () {
  5691. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5692. }, false );
  5693. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5694. image.src = url;
  5695. }
  5696. }
  5697. /**
  5698. * @author mrdoob / http://mrdoob.com/
  5699. * @author alteredq / http://alteredqualia.com/
  5700. */
  5701. THREE.JSONLoader = function ( showStatus ) {
  5702. THREE.Loader.call( this, showStatus );
  5703. this.withCredentials = false;
  5704. };
  5705. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5706. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5707. var scope = this;
  5708. // todo: unify load API to for easier SceneLoader use
  5709. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5710. this.onLoadStart();
  5711. this.loadAjaxJSON( this, url, callback, texturePath );
  5712. };
  5713. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5714. var xhr = new XMLHttpRequest();
  5715. var length = 0;
  5716. xhr.onreadystatechange = function () {
  5717. if ( xhr.readyState === xhr.DONE ) {
  5718. if ( xhr.status === 200 || xhr.status === 0 ) {
  5719. if ( xhr.responseText ) {
  5720. var json = JSON.parse( xhr.responseText );
  5721. context.createModel( json, callback, texturePath );
  5722. } else {
  5723. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5724. }
  5725. // in context of more complex asset initialization
  5726. // do not block on single failed file
  5727. // maybe should go even one more level up
  5728. context.onLoadComplete();
  5729. } else {
  5730. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5731. }
  5732. } else if ( xhr.readyState === xhr.LOADING ) {
  5733. if ( callbackProgress ) {
  5734. if ( length === 0 ) {
  5735. length = xhr.getResponseHeader( "Content-Length" );
  5736. }
  5737. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5738. }
  5739. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5740. length = xhr.getResponseHeader( "Content-Length" );
  5741. }
  5742. };
  5743. xhr.open( "GET", url, true );
  5744. xhr.withCredentials = this.withCredentials;
  5745. xhr.send( null );
  5746. };
  5747. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5748. var scope = this,
  5749. geometry = new THREE.Geometry(),
  5750. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5751. parseModel( scale );
  5752. parseSkin();
  5753. parseMorphing( scale );
  5754. geometry.computeCentroids();
  5755. geometry.computeFaceNormals();
  5756. function parseModel( scale ) {
  5757. function isBitSet( value, position ) {
  5758. return value & ( 1 << position );
  5759. }
  5760. var i, j, fi,
  5761. offset, zLength, nVertices,
  5762. colorIndex, normalIndex, uvIndex, materialIndex,
  5763. type,
  5764. isQuad,
  5765. hasMaterial,
  5766. hasFaceUv, hasFaceVertexUv,
  5767. hasFaceNormal, hasFaceVertexNormal,
  5768. hasFaceColor, hasFaceVertexColor,
  5769. vertex, face, color, normal,
  5770. uvLayer, uvs, u, v,
  5771. faces = json.faces,
  5772. vertices = json.vertices,
  5773. normals = json.normals,
  5774. colors = json.colors,
  5775. nUvLayers = 0;
  5776. // disregard empty arrays
  5777. for ( i = 0; i < json.uvs.length; i++ ) {
  5778. if ( json.uvs[ i ].length ) nUvLayers ++;
  5779. }
  5780. for ( i = 0; i < nUvLayers; i++ ) {
  5781. geometry.faceUvs[ i ] = [];
  5782. geometry.faceVertexUvs[ i ] = [];
  5783. }
  5784. offset = 0;
  5785. zLength = vertices.length;
  5786. while ( offset < zLength ) {
  5787. vertex = new THREE.Vector3();
  5788. vertex.x = vertices[ offset ++ ] * scale;
  5789. vertex.y = vertices[ offset ++ ] * scale;
  5790. vertex.z = vertices[ offset ++ ] * scale;
  5791. geometry.vertices.push( vertex );
  5792. }
  5793. offset = 0;
  5794. zLength = faces.length;
  5795. while ( offset < zLength ) {
  5796. type = faces[ offset ++ ];
  5797. isQuad = isBitSet( type, 0 );
  5798. hasMaterial = isBitSet( type, 1 );
  5799. hasFaceUv = isBitSet( type, 2 );
  5800. hasFaceVertexUv = isBitSet( type, 3 );
  5801. hasFaceNormal = isBitSet( type, 4 );
  5802. hasFaceVertexNormal = isBitSet( type, 5 );
  5803. hasFaceColor = isBitSet( type, 6 );
  5804. hasFaceVertexColor = isBitSet( type, 7 );
  5805. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5806. if ( isQuad ) {
  5807. face = new THREE.Face4();
  5808. face.a = faces[ offset ++ ];
  5809. face.b = faces[ offset ++ ];
  5810. face.c = faces[ offset ++ ];
  5811. face.d = faces[ offset ++ ];
  5812. nVertices = 4;
  5813. } else {
  5814. face = new THREE.Face3();
  5815. face.a = faces[ offset ++ ];
  5816. face.b = faces[ offset ++ ];
  5817. face.c = faces[ offset ++ ];
  5818. nVertices = 3;
  5819. }
  5820. if ( hasMaterial ) {
  5821. materialIndex = faces[ offset ++ ];
  5822. face.materialIndex = materialIndex;
  5823. }
  5824. // to get face <=> uv index correspondence
  5825. fi = geometry.faces.length;
  5826. if ( hasFaceUv ) {
  5827. for ( i = 0; i < nUvLayers; i++ ) {
  5828. uvLayer = json.uvs[ i ];
  5829. uvIndex = faces[ offset ++ ];
  5830. u = uvLayer[ uvIndex * 2 ];
  5831. v = uvLayer[ uvIndex * 2 + 1 ];
  5832. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5833. }
  5834. }
  5835. if ( hasFaceVertexUv ) {
  5836. for ( i = 0; i < nUvLayers; i++ ) {
  5837. uvLayer = json.uvs[ i ];
  5838. uvs = [];
  5839. for ( j = 0; j < nVertices; j ++ ) {
  5840. uvIndex = faces[ offset ++ ];
  5841. u = uvLayer[ uvIndex * 2 ];
  5842. v = uvLayer[ uvIndex * 2 + 1 ];
  5843. uvs[ j ] = new THREE.Vector2( u, v );
  5844. }
  5845. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5846. }
  5847. }
  5848. if ( hasFaceNormal ) {
  5849. normalIndex = faces[ offset ++ ] * 3;
  5850. normal = new THREE.Vector3();
  5851. normal.x = normals[ normalIndex ++ ];
  5852. normal.y = normals[ normalIndex ++ ];
  5853. normal.z = normals[ normalIndex ];
  5854. face.normal = normal;
  5855. }
  5856. if ( hasFaceVertexNormal ) {
  5857. for ( i = 0; i < nVertices; i++ ) {
  5858. normalIndex = faces[ offset ++ ] * 3;
  5859. normal = new THREE.Vector3();
  5860. normal.x = normals[ normalIndex ++ ];
  5861. normal.y = normals[ normalIndex ++ ];
  5862. normal.z = normals[ normalIndex ];
  5863. face.vertexNormals.push( normal );
  5864. }
  5865. }
  5866. if ( hasFaceColor ) {
  5867. colorIndex = faces[ offset ++ ];
  5868. color = new THREE.Color( colors[ colorIndex ] );
  5869. face.color = color;
  5870. }
  5871. if ( hasFaceVertexColor ) {
  5872. for ( i = 0; i < nVertices; i++ ) {
  5873. colorIndex = faces[ offset ++ ];
  5874. color = new THREE.Color( colors[ colorIndex ] );
  5875. face.vertexColors.push( color );
  5876. }
  5877. }
  5878. geometry.faces.push( face );
  5879. }
  5880. };
  5881. function parseSkin() {
  5882. var i, l, x, y, z, w, a, b, c, d;
  5883. if ( json.skinWeights ) {
  5884. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5885. x = json.skinWeights[ i ];
  5886. y = json.skinWeights[ i + 1 ];
  5887. z = 0;
  5888. w = 0;
  5889. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5890. }
  5891. }
  5892. if ( json.skinIndices ) {
  5893. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5894. a = json.skinIndices[ i ];
  5895. b = json.skinIndices[ i + 1 ];
  5896. c = 0;
  5897. d = 0;
  5898. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5899. }
  5900. }
  5901. geometry.bones = json.bones;
  5902. geometry.animation = json.animation;
  5903. };
  5904. function parseMorphing( scale ) {
  5905. if ( json.morphTargets !== undefined ) {
  5906. var i, l, v, vl, dstVertices, srcVertices;
  5907. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5908. geometry.morphTargets[ i ] = {};
  5909. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5910. geometry.morphTargets[ i ].vertices = [];
  5911. dstVertices = geometry.morphTargets[ i ].vertices;
  5912. srcVertices = json.morphTargets [ i ].vertices;
  5913. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5914. var vertex = new THREE.Vector3();
  5915. vertex.x = srcVertices[ v ] * scale;
  5916. vertex.y = srcVertices[ v + 1 ] * scale;
  5917. vertex.z = srcVertices[ v + 2 ] * scale;
  5918. dstVertices.push( vertex );
  5919. }
  5920. }
  5921. }
  5922. if ( json.morphColors !== undefined ) {
  5923. var i, l, c, cl, dstColors, srcColors, color;
  5924. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5925. geometry.morphColors[ i ] = {};
  5926. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5927. geometry.morphColors[ i ].colors = [];
  5928. dstColors = geometry.morphColors[ i ].colors;
  5929. srcColors = json.morphColors [ i ].colors;
  5930. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5931. color = new THREE.Color( 0xffaa00 );
  5932. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5933. dstColors.push( color );
  5934. }
  5935. }
  5936. }
  5937. };
  5938. var materials = this.initMaterials( json.materials, texturePath );
  5939. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5940. callback( geometry, materials );
  5941. };
  5942. /**
  5943. * @author mrdoob / http://mrdoob.com/
  5944. */
  5945. THREE.LoadingMonitor = function () {
  5946. THREE.EventDispatcher.call( this );
  5947. var scope = this;
  5948. var loaded = 0;
  5949. var total = 0;
  5950. var onLoad = function ( event ) {
  5951. loaded ++;
  5952. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5953. if ( loaded === total ) {
  5954. scope.dispatchEvent( { type: 'load' } );
  5955. }
  5956. };
  5957. this.add = function ( loader ) {
  5958. total ++;
  5959. loader.addEventListener( 'load', onLoad, false );
  5960. };
  5961. };
  5962. /**
  5963. * @author alteredq / http://alteredqualia.com/
  5964. */
  5965. THREE.SceneLoader = function () {
  5966. this.onLoadStart = function () {};
  5967. this.onLoadProgress = function() {};
  5968. this.onLoadComplete = function () {};
  5969. this.callbackSync = function () {};
  5970. this.callbackProgress = function () {};
  5971. this.geometryHandlerMap = {};
  5972. this.hierarchyHandlerMap = {};
  5973. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5974. };
  5975. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5976. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5977. var scope = this;
  5978. var xhr = new XMLHttpRequest();
  5979. xhr.onreadystatechange = function () {
  5980. if ( xhr.readyState === 4 ) {
  5981. if ( xhr.status === 200 || xhr.status === 0 ) {
  5982. var json = JSON.parse( xhr.responseText );
  5983. scope.parse( json, callbackFinished, url );
  5984. } else {
  5985. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5986. }
  5987. }
  5988. };
  5989. xhr.open( "GET", url, true );
  5990. xhr.send( null );
  5991. };
  5992. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5993. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5994. };
  5995. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5996. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5997. };
  5998. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5999. var scope = this;
  6000. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6001. var geometry, material, camera, fog,
  6002. texture, images, color,
  6003. light, hex, intensity,
  6004. counter_models, counter_textures,
  6005. total_models, total_textures,
  6006. result;
  6007. var target_array = [];
  6008. var data = json;
  6009. // async geometry loaders
  6010. for ( var typeID in this.geometryHandlerMap ) {
  6011. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6012. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6013. }
  6014. // async hierachy loaders
  6015. for ( var typeID in this.hierarchyHandlerMap ) {
  6016. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6017. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6018. }
  6019. counter_models = 0;
  6020. counter_textures = 0;
  6021. result = {
  6022. scene: new THREE.Scene(),
  6023. geometries: {},
  6024. face_materials: {},
  6025. materials: {},
  6026. textures: {},
  6027. objects: {},
  6028. cameras: {},
  6029. lights: {},
  6030. fogs: {},
  6031. empties: {},
  6032. groups: {}
  6033. };
  6034. if ( data.transform ) {
  6035. var position = data.transform.position,
  6036. rotation = data.transform.rotation,
  6037. scale = data.transform.scale;
  6038. if ( position )
  6039. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6040. if ( rotation )
  6041. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6042. if ( scale )
  6043. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6044. if ( position || rotation || scale ) {
  6045. result.scene.updateMatrix();
  6046. result.scene.updateMatrixWorld();
  6047. }
  6048. }
  6049. function get_url( source_url, url_type ) {
  6050. if ( url_type == "relativeToHTML" ) {
  6051. return source_url;
  6052. } else {
  6053. return urlBase + "/" + source_url;
  6054. }
  6055. };
  6056. // toplevel loader function, delegates to handle_children
  6057. function handle_objects() {
  6058. handle_children( result.scene, data.objects );
  6059. }
  6060. // handle all the children from the loaded json and attach them to given parent
  6061. function handle_children( parent, children ) {
  6062. var mat, dst, pos, rot, scl, quat;
  6063. for ( var objID in children ) {
  6064. // check by id if child has already been handled,
  6065. // if not, create new object
  6066. if ( result.objects[ objID ] === undefined ) {
  6067. var objJSON = children[ objID ];
  6068. var object = null;
  6069. // meshes
  6070. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6071. if ( objJSON.loading === undefined ) {
  6072. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6073. "position": 1, "rotation": 1, "scale" : 1,
  6074. "visible": 1, "children": 1, "properties": 1,
  6075. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6076. var loaderParameters = {};
  6077. for ( var parType in objJSON ) {
  6078. if ( ! ( parType in reservedTypes ) ) {
  6079. loaderParameters[ parType ] = objJSON[ parType ];
  6080. }
  6081. }
  6082. material = result.materials[ objJSON.material ];
  6083. objJSON.loading = true;
  6084. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6085. // ColladaLoader
  6086. if ( loader.options ) {
  6087. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6088. // UTF8Loader
  6089. // OBJLoader
  6090. } else {
  6091. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6092. }
  6093. }
  6094. } else if ( objJSON.geometry !== undefined ) {
  6095. geometry = result.geometries[ objJSON.geometry ];
  6096. // geometry already loaded
  6097. if ( geometry ) {
  6098. var needsTangents = false;
  6099. material = result.materials[ objJSON.material ];
  6100. needsTangents = material instanceof THREE.ShaderMaterial;
  6101. pos = objJSON.position;
  6102. rot = objJSON.rotation;
  6103. scl = objJSON.scale;
  6104. mat = objJSON.matrix;
  6105. quat = objJSON.quaternion;
  6106. // use materials from the model file
  6107. // if there is no material specified in the object
  6108. if ( ! objJSON.material ) {
  6109. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6110. }
  6111. // use materials from the model file
  6112. // if there is just empty face material
  6113. // (must create new material as each model has its own face material)
  6114. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6115. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6116. }
  6117. if ( material instanceof THREE.MeshFaceMaterial ) {
  6118. for ( var i = 0; i < material.materials.length; i ++ ) {
  6119. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6120. }
  6121. }
  6122. if ( needsTangents ) {
  6123. geometry.computeTangents();
  6124. }
  6125. if ( objJSON.skin ) {
  6126. object = new THREE.SkinnedMesh( geometry, material );
  6127. } else if ( objJSON.morph ) {
  6128. object = new THREE.MorphAnimMesh( geometry, material );
  6129. if ( objJSON.duration !== undefined ) {
  6130. object.duration = objJSON.duration;
  6131. }
  6132. if ( objJSON.time !== undefined ) {
  6133. object.time = objJSON.time;
  6134. }
  6135. if ( objJSON.mirroredLoop !== undefined ) {
  6136. object.mirroredLoop = objJSON.mirroredLoop;
  6137. }
  6138. if ( material.morphNormals ) {
  6139. geometry.computeMorphNormals();
  6140. }
  6141. } else {
  6142. object = new THREE.Mesh( geometry, material );
  6143. }
  6144. object.name = objID;
  6145. if ( mat ) {
  6146. object.matrixAutoUpdate = false;
  6147. object.matrix.set(
  6148. mat[0], mat[1], mat[2], mat[3],
  6149. mat[4], mat[5], mat[6], mat[7],
  6150. mat[8], mat[9], mat[10], mat[11],
  6151. mat[12], mat[13], mat[14], mat[15]
  6152. );
  6153. } else {
  6154. object.position.set( pos[0], pos[1], pos[2] );
  6155. if ( quat ) {
  6156. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6157. object.useQuaternion = true;
  6158. } else {
  6159. object.rotation.set( rot[0], rot[1], rot[2] );
  6160. }
  6161. object.scale.set( scl[0], scl[1], scl[2] );
  6162. }
  6163. object.visible = objJSON.visible;
  6164. object.castShadow = objJSON.castShadow;
  6165. object.receiveShadow = objJSON.receiveShadow;
  6166. parent.add( object );
  6167. result.objects[ objID ] = object;
  6168. }
  6169. // lights
  6170. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6171. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6172. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6173. if ( objJSON.type === "DirectionalLight" ) {
  6174. pos = objJSON.direction;
  6175. light = new THREE.DirectionalLight( hex, intensity );
  6176. light.position.set( pos[0], pos[1], pos[2] );
  6177. if ( objJSON.target ) {
  6178. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6179. // kill existing default target
  6180. // otherwise it gets added to scene when parent gets added
  6181. light.target = null;
  6182. }
  6183. } else if ( objJSON.type === "PointLight" ) {
  6184. pos = objJSON.position;
  6185. dst = objJSON.distance;
  6186. light = new THREE.PointLight( hex, intensity, dst );
  6187. light.position.set( pos[0], pos[1], pos[2] );
  6188. } else if ( objJSON.type === "AmbientLight" ) {
  6189. light = new THREE.AmbientLight( hex );
  6190. }
  6191. parent.add( light );
  6192. light.name = objID;
  6193. result.lights[ objID ] = light;
  6194. result.objects[ objID ] = light;
  6195. // cameras
  6196. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6197. if ( objJSON.type === "PerspectiveCamera" ) {
  6198. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6199. } else if ( objJSON.type === "OrthographicCamera" ) {
  6200. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6201. }
  6202. pos = objJSON.position;
  6203. camera.position.set( pos[0], pos[1], pos[2] );
  6204. parent.add( camera );
  6205. camera.name = objID;
  6206. result.cameras[ objID ] = camera;
  6207. result.objects[ objID ] = camera;
  6208. // pure Object3D
  6209. } else {
  6210. pos = objJSON.position;
  6211. rot = objJSON.rotation;
  6212. scl = objJSON.scale;
  6213. quat = objJSON.quaternion;
  6214. object = new THREE.Object3D();
  6215. object.name = objID;
  6216. object.position.set( pos[0], pos[1], pos[2] );
  6217. if ( quat ) {
  6218. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6219. object.useQuaternion = true;
  6220. } else {
  6221. object.rotation.set( rot[0], rot[1], rot[2] );
  6222. }
  6223. object.scale.set( scl[0], scl[1], scl[2] );
  6224. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6225. parent.add( object );
  6226. result.objects[ objID ] = object;
  6227. result.empties[ objID ] = object;
  6228. }
  6229. if ( object ) {
  6230. if ( objJSON.properties !== undefined ) {
  6231. for ( var key in objJSON.properties ) {
  6232. var value = objJSON.properties[ key ];
  6233. object.properties[ key ] = value;
  6234. }
  6235. }
  6236. if ( objJSON.groups !== undefined ) {
  6237. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6238. var groupID = objJSON.groups[ i ];
  6239. if ( result.groups[ groupID ] === undefined ) {
  6240. result.groups[ groupID ] = [];
  6241. }
  6242. result.groups[ groupID ].push( objID );
  6243. }
  6244. }
  6245. if ( objJSON.children !== undefined ) {
  6246. handle_children( object, objJSON.children );
  6247. }
  6248. }
  6249. }
  6250. }
  6251. };
  6252. function handle_mesh( geo, mat, id ) {
  6253. result.geometries[ id ] = geo;
  6254. result.face_materials[ id ] = mat;
  6255. handle_objects();
  6256. };
  6257. function handle_hierarchy( node, id, parent, material, obj ) {
  6258. var p = obj.position;
  6259. var r = obj.rotation;
  6260. var q = obj.quaternion;
  6261. var s = obj.scale;
  6262. node.position.set( p[0], p[1], p[2] );
  6263. if ( q ) {
  6264. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6265. node.useQuaternion = true;
  6266. } else {
  6267. node.rotation.set( r[0], r[1], r[2] );
  6268. }
  6269. node.scale.set( s[0], s[1], s[2] );
  6270. // override children materials
  6271. // if object material was specified in JSON explicitly
  6272. if ( material ) {
  6273. node.traverse( function ( child ) {
  6274. child.material = material;
  6275. } );
  6276. }
  6277. // override children visibility
  6278. // with root node visibility as specified in JSON
  6279. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6280. node.traverse( function ( child ) {
  6281. child.visible = visible;
  6282. } );
  6283. parent.add( node );
  6284. node.name = id;
  6285. result.objects[ id ] = node;
  6286. handle_objects();
  6287. };
  6288. function create_callback_geometry( id ) {
  6289. return function( geo, mat ) {
  6290. handle_mesh( geo, mat, id );
  6291. counter_models -= 1;
  6292. scope.onLoadComplete();
  6293. async_callback_gate();
  6294. }
  6295. };
  6296. function create_callback_hierachy( id, parent, material, obj ) {
  6297. return function( event ) {
  6298. var result;
  6299. // loaders which use EventDispatcher
  6300. if ( event.content ) {
  6301. result = event.content;
  6302. // ColladaLoader
  6303. } else if ( event.dae ) {
  6304. result = event.scene;
  6305. // UTF8Loader
  6306. } else {
  6307. result = event;
  6308. }
  6309. handle_hierarchy( result, id, parent, material, obj );
  6310. counter_models -= 1;
  6311. scope.onLoadComplete();
  6312. async_callback_gate();
  6313. }
  6314. };
  6315. function create_callback_embed( id ) {
  6316. return function( geo, mat ) {
  6317. result.geometries[ id ] = geo;
  6318. result.face_materials[ id ] = mat;
  6319. }
  6320. };
  6321. function async_callback_gate() {
  6322. var progress = {
  6323. totalModels : total_models,
  6324. totalTextures : total_textures,
  6325. loadedModels : total_models - counter_models,
  6326. loadedTextures : total_textures - counter_textures
  6327. };
  6328. scope.callbackProgress( progress, result );
  6329. scope.onLoadProgress();
  6330. if ( counter_models === 0 && counter_textures === 0 ) {
  6331. finalize();
  6332. callbackFinished( result );
  6333. }
  6334. };
  6335. function finalize() {
  6336. // take care of targets which could be asynchronously loaded objects
  6337. for ( var i = 0; i < target_array.length; i ++ ) {
  6338. var ta = target_array[ i ];
  6339. var target = result.objects[ ta.targetName ];
  6340. if ( target ) {
  6341. ta.object.target = target;
  6342. } else {
  6343. // if there was error and target of specified name doesn't exist in the scene file
  6344. // create instead dummy target
  6345. // (target must be added to scene explicitly as parent is already added)
  6346. ta.object.target = new THREE.Object3D();
  6347. result.scene.add( ta.object.target );
  6348. }
  6349. ta.object.target.properties.targetInverse = ta.object;
  6350. }
  6351. };
  6352. var callbackTexture = function ( count ) {
  6353. counter_textures -= count;
  6354. async_callback_gate();
  6355. scope.onLoadComplete();
  6356. };
  6357. // must use this instead of just directly calling callbackTexture
  6358. // because of closure in the calling context loop
  6359. var generateTextureCallback = function ( count ) {
  6360. return function() {
  6361. callbackTexture( count );
  6362. };
  6363. };
  6364. // first go synchronous elements
  6365. // fogs
  6366. var fogID, fogJSON;
  6367. for ( fogID in data.fogs ) {
  6368. fogJSON = data.fogs[ fogID ];
  6369. if ( fogJSON.type === "linear" ) {
  6370. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6371. } else if ( fogJSON.type === "exp2" ) {
  6372. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6373. }
  6374. color = fogJSON.color;
  6375. fog.color.setRGB( color[0], color[1], color[2] );
  6376. result.fogs[ fogID ] = fog;
  6377. }
  6378. // now come potentially asynchronous elements
  6379. // geometries
  6380. // count how many geometries will be loaded asynchronously
  6381. var geoID, geoJSON;
  6382. for ( geoID in data.geometries ) {
  6383. geoJSON = data.geometries[ geoID ];
  6384. if ( geoJSON.type in this.geometryHandlerMap ) {
  6385. counter_models += 1;
  6386. scope.onLoadStart();
  6387. }
  6388. }
  6389. // count how many hierarchies will be loaded asynchronously
  6390. var objID, objJSON;
  6391. for ( objID in data.objects ) {
  6392. objJSON = data.objects[ objID ];
  6393. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6394. counter_models += 1;
  6395. scope.onLoadStart();
  6396. }
  6397. }
  6398. total_models = counter_models;
  6399. for ( geoID in data.geometries ) {
  6400. geoJSON = data.geometries[ geoID ];
  6401. if ( geoJSON.type === "cube" ) {
  6402. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6403. result.geometries[ geoID ] = geometry;
  6404. } else if ( geoJSON.type === "plane" ) {
  6405. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6406. result.geometries[ geoID ] = geometry;
  6407. } else if ( geoJSON.type === "sphere" ) {
  6408. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6409. result.geometries[ geoID ] = geometry;
  6410. } else if ( geoJSON.type === "cylinder" ) {
  6411. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6412. result.geometries[ geoID ] = geometry;
  6413. } else if ( geoJSON.type === "torus" ) {
  6414. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6415. result.geometries[ geoID ] = geometry;
  6416. } else if ( geoJSON.type === "icosahedron" ) {
  6417. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6418. result.geometries[ geoID ] = geometry;
  6419. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6420. var loaderParameters = {};
  6421. for ( var parType in geoJSON ) {
  6422. if ( parType !== "type" && parType !== "url" ) {
  6423. loaderParameters[ parType ] = geoJSON[ parType ];
  6424. }
  6425. }
  6426. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6427. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6428. } else if ( geoJSON.type === "embedded" ) {
  6429. var modelJson = data.embeds[ geoJSON.id ],
  6430. texture_path = "";
  6431. // pass metadata along to jsonLoader so it knows the format version
  6432. modelJson.metadata = data.metadata;
  6433. if ( modelJson ) {
  6434. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6435. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6436. }
  6437. }
  6438. }
  6439. // textures
  6440. // count how many textures will be loaded asynchronously
  6441. var textureID, textureJSON;
  6442. for ( textureID in data.textures ) {
  6443. textureJSON = data.textures[ textureID ];
  6444. if ( textureJSON.url instanceof Array ) {
  6445. counter_textures += textureJSON.url.length;
  6446. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6447. scope.onLoadStart();
  6448. }
  6449. } else {
  6450. counter_textures += 1;
  6451. scope.onLoadStart();
  6452. }
  6453. }
  6454. total_textures = counter_textures;
  6455. for ( textureID in data.textures ) {
  6456. textureJSON = data.textures[ textureID ];
  6457. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6458. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6459. }
  6460. if ( textureJSON.url instanceof Array ) {
  6461. var count = textureJSON.url.length;
  6462. var url_array = [];
  6463. for( var i = 0; i < count; i ++ ) {
  6464. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6465. }
  6466. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6467. if ( isCompressed ) {
  6468. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6469. } else {
  6470. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6471. }
  6472. } else {
  6473. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6474. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6475. var textureCallback = generateTextureCallback( 1 );
  6476. if ( isCompressed ) {
  6477. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6478. } else {
  6479. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6480. }
  6481. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6482. texture.minFilter = THREE[ textureJSON.minFilter ];
  6483. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6484. texture.magFilter = THREE[ textureJSON.magFilter ];
  6485. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6486. if ( textureJSON.repeat ) {
  6487. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6488. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6489. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6490. }
  6491. if ( textureJSON.offset ) {
  6492. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6493. }
  6494. // handle wrap after repeat so that default repeat can be overriden
  6495. if ( textureJSON.wrap ) {
  6496. var wrapMap = {
  6497. "repeat" : THREE.RepeatWrapping,
  6498. "mirror" : THREE.MirroredRepeatWrapping
  6499. }
  6500. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6501. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6502. }
  6503. }
  6504. result.textures[ textureID ] = texture;
  6505. }
  6506. // materials
  6507. var matID, matJSON;
  6508. var parID;
  6509. for ( matID in data.materials ) {
  6510. matJSON = data.materials[ matID ];
  6511. for ( parID in matJSON.parameters ) {
  6512. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6513. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6514. } else if ( parID === "shading" ) {
  6515. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6516. } else if ( parID === "side" ) {
  6517. if ( matJSON.parameters[ parID ] == "double" ) {
  6518. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6519. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6520. matJSON.parameters[ parID ] = THREE.BackSide;
  6521. } else {
  6522. matJSON.parameters[ parID ] = THREE.FrontSide;
  6523. }
  6524. } else if ( parID === "blending" ) {
  6525. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6526. } else if ( parID === "combine" ) {
  6527. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6528. } else if ( parID === "vertexColors" ) {
  6529. if ( matJSON.parameters[ parID ] == "face" ) {
  6530. matJSON.parameters[ parID ] = THREE.FaceColors;
  6531. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6532. } else if ( matJSON.parameters[ parID ] ) {
  6533. matJSON.parameters[ parID ] = THREE.VertexColors;
  6534. }
  6535. } else if ( parID === "wrapRGB" ) {
  6536. var v3 = matJSON.parameters[ parID ];
  6537. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6538. }
  6539. }
  6540. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6541. matJSON.parameters.transparent = true;
  6542. }
  6543. if ( matJSON.parameters.normalMap ) {
  6544. var shader = THREE.ShaderLib[ "normalmap" ];
  6545. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6546. var diffuse = matJSON.parameters.color;
  6547. var specular = matJSON.parameters.specular;
  6548. var ambient = matJSON.parameters.ambient;
  6549. var shininess = matJSON.parameters.shininess;
  6550. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6551. if ( matJSON.parameters.normalScale ) {
  6552. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6553. }
  6554. if ( matJSON.parameters.map ) {
  6555. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6556. uniforms[ "enableDiffuse" ].value = true;
  6557. }
  6558. if ( matJSON.parameters.envMap ) {
  6559. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6560. uniforms[ "enableReflection" ].value = true;
  6561. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6562. }
  6563. if ( matJSON.parameters.lightMap ) {
  6564. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6565. uniforms[ "enableAO" ].value = true;
  6566. }
  6567. if ( matJSON.parameters.specularMap ) {
  6568. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6569. uniforms[ "enableSpecular" ].value = true;
  6570. }
  6571. if ( matJSON.parameters.displacementMap ) {
  6572. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6573. uniforms[ "enableDisplacement" ].value = true;
  6574. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6575. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6576. }
  6577. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6578. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6579. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6580. uniforms[ "uShininess" ].value = shininess;
  6581. if ( matJSON.parameters.opacity ) {
  6582. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6583. }
  6584. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6585. material = new THREE.ShaderMaterial( parameters );
  6586. } else {
  6587. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6588. }
  6589. result.materials[ matID ] = material;
  6590. }
  6591. // second pass through all materials to initialize MeshFaceMaterials
  6592. // that could be referring to other materials out of order
  6593. for ( matID in data.materials ) {
  6594. matJSON = data.materials[ matID ];
  6595. if ( matJSON.parameters.materials ) {
  6596. var materialArray = [];
  6597. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6598. var label = matJSON.parameters.materials[ i ];
  6599. materialArray.push( result.materials[ label ] );
  6600. }
  6601. result.materials[ matID ].materials = materialArray;
  6602. }
  6603. }
  6604. // objects ( synchronous init of procedural primitives )
  6605. handle_objects();
  6606. // defaults
  6607. if ( result.cameras && data.defaults.camera ) {
  6608. result.currentCamera = result.cameras[ data.defaults.camera ];
  6609. }
  6610. if ( result.fogs && data.defaults.fog ) {
  6611. result.scene.fog = result.fogs[ data.defaults.fog ];
  6612. }
  6613. // synchronous callback
  6614. scope.callbackSync( result );
  6615. // just in case there are no async elements
  6616. async_callback_gate();
  6617. };
  6618. /**
  6619. * @author mrdoob / http://mrdoob.com/
  6620. */
  6621. THREE.TextureLoader = function () {
  6622. THREE.EventDispatcher.call( this );
  6623. this.crossOrigin = null;
  6624. };
  6625. THREE.TextureLoader.prototype = {
  6626. constructor: THREE.TextureLoader,
  6627. load: function ( url ) {
  6628. var scope = this;
  6629. var image = new Image();
  6630. image.addEventListener( 'load', function () {
  6631. var texture = new THREE.Texture( image );
  6632. texture.needsUpdate = true;
  6633. scope.dispatchEvent( { type: 'load', content: texture } );
  6634. }, false );
  6635. image.addEventListener( 'error', function () {
  6636. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6637. }, false );
  6638. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6639. image.src = url;
  6640. }
  6641. }
  6642. /**
  6643. * @author mrdoob / http://mrdoob.com/
  6644. * @author alteredq / http://alteredqualia.com/
  6645. */
  6646. THREE.Material = function () {
  6647. THREE.EventDispatcher.call( this );
  6648. this.id = THREE.MaterialIdCount ++;
  6649. this.name = '';
  6650. this.side = THREE.FrontSide;
  6651. this.opacity = 1;
  6652. this.transparent = false;
  6653. this.blending = THREE.NormalBlending;
  6654. this.blendSrc = THREE.SrcAlphaFactor;
  6655. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6656. this.blendEquation = THREE.AddEquation;
  6657. this.depthTest = true;
  6658. this.depthWrite = true;
  6659. this.polygonOffset = false;
  6660. this.polygonOffsetFactor = 0;
  6661. this.polygonOffsetUnits = 0;
  6662. this.alphaTest = 0;
  6663. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6664. this.visible = true;
  6665. this.needsUpdate = true;
  6666. };
  6667. THREE.Material.prototype.setValues = function ( values ) {
  6668. if ( values === undefined ) return;
  6669. for ( var key in values ) {
  6670. var newValue = values[ key ];
  6671. if ( newValue === undefined ) {
  6672. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6673. continue;
  6674. }
  6675. if ( key in this ) {
  6676. var currentValue = this[ key ];
  6677. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6678. currentValue.copy( newValue );
  6679. } else if ( currentValue instanceof THREE.Color ) {
  6680. currentValue.set( newValue );
  6681. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6682. currentValue.copy( newValue );
  6683. } else {
  6684. this[ key ] = newValue;
  6685. }
  6686. }
  6687. }
  6688. };
  6689. THREE.Material.prototype.clone = function ( material ) {
  6690. if ( material === undefined ) material = new THREE.Material();
  6691. material.name = this.name;
  6692. material.side = this.side;
  6693. material.opacity = this.opacity;
  6694. material.transparent = this.transparent;
  6695. material.blending = this.blending;
  6696. material.blendSrc = this.blendSrc;
  6697. material.blendDst = this.blendDst;
  6698. material.blendEquation = this.blendEquation;
  6699. material.depthTest = this.depthTest;
  6700. material.depthWrite = this.depthWrite;
  6701. material.polygonOffset = this.polygonOffset;
  6702. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6703. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6704. material.alphaTest = this.alphaTest;
  6705. material.overdraw = this.overdraw;
  6706. material.visible = this.visible;
  6707. return material;
  6708. };
  6709. THREE.Material.prototype.dispose = function () {
  6710. this.dispatchEvent( { type: 'dispose' } );
  6711. };
  6712. THREE.MaterialIdCount = 0;
  6713. /**
  6714. * @author mrdoob / http://mrdoob.com/
  6715. * @author alteredq / http://alteredqualia.com/
  6716. *
  6717. * parameters = {
  6718. * color: <hex>,
  6719. * opacity: <float>,
  6720. *
  6721. * blending: THREE.NormalBlending,
  6722. * depthTest: <bool>,
  6723. * depthWrite: <bool>,
  6724. *
  6725. * linewidth: <float>,
  6726. * linecap: "round",
  6727. * linejoin: "round",
  6728. *
  6729. * vertexColors: <bool>
  6730. *
  6731. * fog: <bool>
  6732. * }
  6733. */
  6734. THREE.LineBasicMaterial = function ( parameters ) {
  6735. THREE.Material.call( this );
  6736. this.color = new THREE.Color( 0xffffff );
  6737. this.linewidth = 1;
  6738. this.linecap = 'round';
  6739. this.linejoin = 'round';
  6740. this.vertexColors = false;
  6741. this.fog = true;
  6742. this.setValues( parameters );
  6743. };
  6744. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6745. THREE.LineBasicMaterial.prototype.clone = function () {
  6746. var material = new THREE.LineBasicMaterial();
  6747. THREE.Material.prototype.clone.call( this, material );
  6748. material.color.copy( this.color );
  6749. material.linewidth = this.linewidth;
  6750. material.linecap = this.linecap;
  6751. material.linejoin = this.linejoin;
  6752. material.vertexColors = this.vertexColors;
  6753. material.fog = this.fog;
  6754. return material;
  6755. };
  6756. /**
  6757. * @author alteredq / http://alteredqualia.com/
  6758. *
  6759. * parameters = {
  6760. * color: <hex>,
  6761. * opacity: <float>,
  6762. *
  6763. * blending: THREE.NormalBlending,
  6764. * depthTest: <bool>,
  6765. * depthWrite: <bool>,
  6766. *
  6767. * linewidth: <float>,
  6768. *
  6769. * scale: <float>,
  6770. * dashSize: <float>,
  6771. * gapSize: <float>,
  6772. *
  6773. * vertexColors: <bool>
  6774. *
  6775. * fog: <bool>
  6776. * }
  6777. */
  6778. THREE.LineDashedMaterial = function ( parameters ) {
  6779. THREE.Material.call( this );
  6780. this.color = new THREE.Color( 0xffffff );
  6781. this.linewidth = 1;
  6782. this.scale = 1;
  6783. this.dashSize = 3;
  6784. this.gapSize = 1;
  6785. this.vertexColors = false;
  6786. this.fog = true;
  6787. this.setValues( parameters );
  6788. };
  6789. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6790. THREE.LineDashedMaterial.prototype.clone = function () {
  6791. var material = new THREE.LineDashedMaterial();
  6792. THREE.Material.prototype.clone.call( this, material );
  6793. material.color.copy( this.color );
  6794. material.linewidth = this.linewidth;
  6795. material.scale = this.scale;
  6796. material.dashSize = this.dashSize;
  6797. material.gapSize = this.gapSize;
  6798. material.vertexColors = this.vertexColors;
  6799. material.fog = this.fog;
  6800. return material;
  6801. };
  6802. /**
  6803. * @author mrdoob / http://mrdoob.com/
  6804. * @author alteredq / http://alteredqualia.com/
  6805. *
  6806. * parameters = {
  6807. * color: <hex>,
  6808. * opacity: <float>,
  6809. * map: new THREE.Texture( <Image> ),
  6810. *
  6811. * lightMap: new THREE.Texture( <Image> ),
  6812. *
  6813. * specularMap: new THREE.Texture( <Image> ),
  6814. *
  6815. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6816. * combine: THREE.Multiply,
  6817. * reflectivity: <float>,
  6818. * refractionRatio: <float>,
  6819. *
  6820. * shading: THREE.SmoothShading,
  6821. * blending: THREE.NormalBlending,
  6822. * depthTest: <bool>,
  6823. * depthWrite: <bool>,
  6824. *
  6825. * wireframe: <boolean>,
  6826. * wireframeLinewidth: <float>,
  6827. *
  6828. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6829. *
  6830. * skinning: <bool>,
  6831. * morphTargets: <bool>,
  6832. *
  6833. * fog: <bool>
  6834. * }
  6835. */
  6836. THREE.MeshBasicMaterial = function ( parameters ) {
  6837. THREE.Material.call( this );
  6838. this.color = new THREE.Color( 0xffffff ); // emissive
  6839. this.map = null;
  6840. this.lightMap = null;
  6841. this.specularMap = null;
  6842. this.envMap = null;
  6843. this.combine = THREE.MultiplyOperation;
  6844. this.reflectivity = 1;
  6845. this.refractionRatio = 0.98;
  6846. this.fog = true;
  6847. this.shading = THREE.SmoothShading;
  6848. this.wireframe = false;
  6849. this.wireframeLinewidth = 1;
  6850. this.wireframeLinecap = 'round';
  6851. this.wireframeLinejoin = 'round';
  6852. this.vertexColors = THREE.NoColors;
  6853. this.skinning = false;
  6854. this.morphTargets = false;
  6855. this.setValues( parameters );
  6856. };
  6857. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6858. THREE.MeshBasicMaterial.prototype.clone = function () {
  6859. var material = new THREE.MeshBasicMaterial();
  6860. THREE.Material.prototype.clone.call( this, material );
  6861. material.color.copy( this.color );
  6862. material.map = this.map;
  6863. material.lightMap = this.lightMap;
  6864. material.specularMap = this.specularMap;
  6865. material.envMap = this.envMap;
  6866. material.combine = this.combine;
  6867. material.reflectivity = this.reflectivity;
  6868. material.refractionRatio = this.refractionRatio;
  6869. material.fog = this.fog;
  6870. material.shading = this.shading;
  6871. material.wireframe = this.wireframe;
  6872. material.wireframeLinewidth = this.wireframeLinewidth;
  6873. material.wireframeLinecap = this.wireframeLinecap;
  6874. material.wireframeLinejoin = this.wireframeLinejoin;
  6875. material.vertexColors = this.vertexColors;
  6876. material.skinning = this.skinning;
  6877. material.morphTargets = this.morphTargets;
  6878. return material;
  6879. };
  6880. /**
  6881. * @author mrdoob / http://mrdoob.com/
  6882. * @author alteredq / http://alteredqualia.com/
  6883. *
  6884. * parameters = {
  6885. * color: <hex>,
  6886. * ambient: <hex>,
  6887. * emissive: <hex>,
  6888. * opacity: <float>,
  6889. *
  6890. * map: new THREE.Texture( <Image> ),
  6891. *
  6892. * lightMap: new THREE.Texture( <Image> ),
  6893. *
  6894. * specularMap: new THREE.Texture( <Image> ),
  6895. *
  6896. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6897. * combine: THREE.Multiply,
  6898. * reflectivity: <float>,
  6899. * refractionRatio: <float>,
  6900. *
  6901. * shading: THREE.SmoothShading,
  6902. * blending: THREE.NormalBlending,
  6903. * depthTest: <bool>,
  6904. * depthWrite: <bool>,
  6905. *
  6906. * wireframe: <boolean>,
  6907. * wireframeLinewidth: <float>,
  6908. *
  6909. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6910. *
  6911. * skinning: <bool>,
  6912. * morphTargets: <bool>,
  6913. * morphNormals: <bool>,
  6914. *
  6915. * fog: <bool>
  6916. * }
  6917. */
  6918. THREE.MeshLambertMaterial = function ( parameters ) {
  6919. THREE.Material.call( this );
  6920. this.color = new THREE.Color( 0xffffff ); // diffuse
  6921. this.ambient = new THREE.Color( 0xffffff );
  6922. this.emissive = new THREE.Color( 0x000000 );
  6923. this.wrapAround = false;
  6924. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6925. this.map = null;
  6926. this.lightMap = null;
  6927. this.specularMap = null;
  6928. this.envMap = null;
  6929. this.combine = THREE.MultiplyOperation;
  6930. this.reflectivity = 1;
  6931. this.refractionRatio = 0.98;
  6932. this.fog = true;
  6933. this.shading = THREE.SmoothShading;
  6934. this.wireframe = false;
  6935. this.wireframeLinewidth = 1;
  6936. this.wireframeLinecap = 'round';
  6937. this.wireframeLinejoin = 'round';
  6938. this.vertexColors = THREE.NoColors;
  6939. this.skinning = false;
  6940. this.morphTargets = false;
  6941. this.morphNormals = false;
  6942. this.setValues( parameters );
  6943. };
  6944. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6945. THREE.MeshLambertMaterial.prototype.clone = function () {
  6946. var material = new THREE.MeshLambertMaterial();
  6947. THREE.Material.prototype.clone.call( this, material );
  6948. material.color.copy( this.color );
  6949. material.ambient.copy( this.ambient );
  6950. material.emissive.copy( this.emissive );
  6951. material.wrapAround = this.wrapAround;
  6952. material.wrapRGB.copy( this.wrapRGB );
  6953. material.map = this.map;
  6954. material.lightMap = this.lightMap;
  6955. material.specularMap = this.specularMap;
  6956. material.envMap = this.envMap;
  6957. material.combine = this.combine;
  6958. material.reflectivity = this.reflectivity;
  6959. material.refractionRatio = this.refractionRatio;
  6960. material.fog = this.fog;
  6961. material.shading = this.shading;
  6962. material.wireframe = this.wireframe;
  6963. material.wireframeLinewidth = this.wireframeLinewidth;
  6964. material.wireframeLinecap = this.wireframeLinecap;
  6965. material.wireframeLinejoin = this.wireframeLinejoin;
  6966. material.vertexColors = this.vertexColors;
  6967. material.skinning = this.skinning;
  6968. material.morphTargets = this.morphTargets;
  6969. material.morphNormals = this.morphNormals;
  6970. return material;
  6971. };
  6972. /**
  6973. * @author mrdoob / http://mrdoob.com/
  6974. * @author alteredq / http://alteredqualia.com/
  6975. *
  6976. * parameters = {
  6977. * color: <hex>,
  6978. * ambient: <hex>,
  6979. * emissive: <hex>,
  6980. * specular: <hex>,
  6981. * shininess: <float>,
  6982. * opacity: <float>,
  6983. *
  6984. * map: new THREE.Texture( <Image> ),
  6985. *
  6986. * lightMap: new THREE.Texture( <Image> ),
  6987. *
  6988. * bumpMap: new THREE.Texture( <Image> ),
  6989. * bumpScale: <float>,
  6990. *
  6991. * normalMap: new THREE.Texture( <Image> ),
  6992. * normalScale: <Vector2>,
  6993. *
  6994. * specularMap: new THREE.Texture( <Image> ),
  6995. *
  6996. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6997. * combine: THREE.Multiply,
  6998. * reflectivity: <float>,
  6999. * refractionRatio: <float>,
  7000. *
  7001. * shading: THREE.SmoothShading,
  7002. * blending: THREE.NormalBlending,
  7003. * depthTest: <bool>,
  7004. * depthWrite: <bool>,
  7005. *
  7006. * wireframe: <boolean>,
  7007. * wireframeLinewidth: <float>,
  7008. *
  7009. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7010. *
  7011. * skinning: <bool>,
  7012. * morphTargets: <bool>,
  7013. * morphNormals: <bool>,
  7014. *
  7015. * fog: <bool>
  7016. * }
  7017. */
  7018. THREE.MeshPhongMaterial = function ( parameters ) {
  7019. THREE.Material.call( this );
  7020. this.color = new THREE.Color( 0xffffff ); // diffuse
  7021. this.ambient = new THREE.Color( 0xffffff );
  7022. this.emissive = new THREE.Color( 0x000000 );
  7023. this.specular = new THREE.Color( 0x111111 );
  7024. this.shininess = 30;
  7025. this.metal = false;
  7026. this.perPixel = true;
  7027. this.wrapAround = false;
  7028. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7029. this.map = null;
  7030. this.lightMap = null;
  7031. this.bumpMap = null;
  7032. this.bumpScale = 1;
  7033. this.normalMap = null;
  7034. this.normalScale = new THREE.Vector2( 1, 1 );
  7035. this.specularMap = null;
  7036. this.envMap = null;
  7037. this.combine = THREE.MultiplyOperation;
  7038. this.reflectivity = 1;
  7039. this.refractionRatio = 0.98;
  7040. this.fog = true;
  7041. this.shading = THREE.SmoothShading;
  7042. this.wireframe = false;
  7043. this.wireframeLinewidth = 1;
  7044. this.wireframeLinecap = 'round';
  7045. this.wireframeLinejoin = 'round';
  7046. this.vertexColors = THREE.NoColors;
  7047. this.skinning = false;
  7048. this.morphTargets = false;
  7049. this.morphNormals = false;
  7050. this.setValues( parameters );
  7051. };
  7052. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7053. THREE.MeshPhongMaterial.prototype.clone = function () {
  7054. var material = new THREE.MeshPhongMaterial();
  7055. THREE.Material.prototype.clone.call( this, material );
  7056. material.color.copy( this.color );
  7057. material.ambient.copy( this.ambient );
  7058. material.emissive.copy( this.emissive );
  7059. material.specular.copy( this.specular );
  7060. material.shininess = this.shininess;
  7061. material.metal = this.metal;
  7062. material.perPixel = this.perPixel;
  7063. material.wrapAround = this.wrapAround;
  7064. material.wrapRGB.copy( this.wrapRGB );
  7065. material.map = this.map;
  7066. material.lightMap = this.lightMap;
  7067. material.bumpMap = this.bumpMap;
  7068. material.bumpScale = this.bumpScale;
  7069. material.normalMap = this.normalMap;
  7070. material.normalScale.copy( this.normalScale );
  7071. material.specularMap = this.specularMap;
  7072. material.envMap = this.envMap;
  7073. material.combine = this.combine;
  7074. material.reflectivity = this.reflectivity;
  7075. material.refractionRatio = this.refractionRatio;
  7076. material.fog = this.fog;
  7077. material.shading = this.shading;
  7078. material.wireframe = this.wireframe;
  7079. material.wireframeLinewidth = this.wireframeLinewidth;
  7080. material.wireframeLinecap = this.wireframeLinecap;
  7081. material.wireframeLinejoin = this.wireframeLinejoin;
  7082. material.vertexColors = this.vertexColors;
  7083. material.skinning = this.skinning;
  7084. material.morphTargets = this.morphTargets;
  7085. material.morphNormals = this.morphNormals;
  7086. return material;
  7087. };
  7088. /**
  7089. * @author mrdoob / http://mrdoob.com/
  7090. * @author alteredq / http://alteredqualia.com/
  7091. *
  7092. * parameters = {
  7093. * opacity: <float>,
  7094. *
  7095. * blending: THREE.NormalBlending,
  7096. * depthTest: <bool>,
  7097. * depthWrite: <bool>,
  7098. *
  7099. * wireframe: <boolean>,
  7100. * wireframeLinewidth: <float>
  7101. * }
  7102. */
  7103. THREE.MeshDepthMaterial = function ( parameters ) {
  7104. THREE.Material.call( this );
  7105. this.wireframe = false;
  7106. this.wireframeLinewidth = 1;
  7107. this.setValues( parameters );
  7108. };
  7109. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7110. THREE.MeshDepthMaterial.prototype.clone = function () {
  7111. var material = new THREE.LineBasicMaterial();
  7112. THREE.Material.prototype.clone.call( this, material );
  7113. material.wireframe = this.wireframe;
  7114. material.wireframeLinewidth = this.wireframeLinewidth;
  7115. return material;
  7116. };
  7117. /**
  7118. * @author mrdoob / http://mrdoob.com/
  7119. *
  7120. * parameters = {
  7121. * opacity: <float>,
  7122. *
  7123. * shading: THREE.FlatShading,
  7124. * blending: THREE.NormalBlending,
  7125. * depthTest: <bool>,
  7126. * depthWrite: <bool>,
  7127. *
  7128. * wireframe: <boolean>,
  7129. * wireframeLinewidth: <float>
  7130. * }
  7131. */
  7132. THREE.MeshNormalMaterial = function ( parameters ) {
  7133. THREE.Material.call( this, parameters );
  7134. this.shading = THREE.FlatShading;
  7135. this.wireframe = false;
  7136. this.wireframeLinewidth = 1;
  7137. this.setValues( parameters );
  7138. };
  7139. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7140. THREE.MeshNormalMaterial.prototype.clone = function () {
  7141. var material = new THREE.MeshNormalMaterial();
  7142. THREE.Material.prototype.clone.call( this, material );
  7143. material.shading = this.shading;
  7144. material.wireframe = this.wireframe;
  7145. material.wireframeLinewidth = this.wireframeLinewidth;
  7146. return material;
  7147. };
  7148. /**
  7149. * @author mrdoob / http://mrdoob.com/
  7150. */
  7151. THREE.MeshFaceMaterial = function ( materials ) {
  7152. this.materials = materials instanceof Array ? materials : [];
  7153. };
  7154. THREE.MeshFaceMaterial.prototype.clone = function () {
  7155. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7156. };
  7157. /**
  7158. * @author mrdoob / http://mrdoob.com/
  7159. * @author alteredq / http://alteredqualia.com/
  7160. *
  7161. * parameters = {
  7162. * color: <hex>,
  7163. * opacity: <float>,
  7164. * map: new THREE.Texture( <Image> ),
  7165. *
  7166. * size: <float>,
  7167. *
  7168. * blending: THREE.NormalBlending,
  7169. * depthTest: <bool>,
  7170. * depthWrite: <bool>,
  7171. *
  7172. * vertexColors: <bool>,
  7173. *
  7174. * fog: <bool>
  7175. * }
  7176. */
  7177. THREE.ParticleBasicMaterial = function ( parameters ) {
  7178. THREE.Material.call( this );
  7179. this.color = new THREE.Color( 0xffffff );
  7180. this.map = null;
  7181. this.size = 1;
  7182. this.sizeAttenuation = true;
  7183. this.vertexColors = false;
  7184. this.fog = true;
  7185. this.setValues( parameters );
  7186. };
  7187. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7188. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7189. var material = new THREE.ParticleBasicMaterial();
  7190. THREE.Material.prototype.clone.call( this, material );
  7191. material.color.copy( this.color );
  7192. material.map = this.map;
  7193. material.size = this.size;
  7194. material.sizeAttenuation = this.sizeAttenuation;
  7195. material.vertexColors = this.vertexColors;
  7196. material.fog = this.fog;
  7197. return material;
  7198. };
  7199. /**
  7200. * @author mrdoob / http://mrdoob.com/
  7201. *
  7202. * parameters = {
  7203. * color: <hex>,
  7204. * program: <function>,
  7205. * opacity: <float>,
  7206. * blending: THREE.NormalBlending
  7207. * }
  7208. */
  7209. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7210. THREE.Material.call( this );
  7211. this.color = new THREE.Color( 0xffffff );
  7212. this.program = function ( context, color ) {};
  7213. this.setValues( parameters );
  7214. };
  7215. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7216. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7217. var material = new THREE.ParticleCanvasMaterial();
  7218. THREE.Material.prototype.clone.call( this, material );
  7219. material.color.copy( this.color );
  7220. material.program = this.program;
  7221. return material;
  7222. };
  7223. /**
  7224. * @author alteredq / http://alteredqualia.com/
  7225. *
  7226. * parameters = {
  7227. * fragmentShader: <string>,
  7228. * vertexShader: <string>,
  7229. *
  7230. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7231. *
  7232. * defines: { "label" : "value" },
  7233. *
  7234. * shading: THREE.SmoothShading,
  7235. * blending: THREE.NormalBlending,
  7236. * depthTest: <bool>,
  7237. * depthWrite: <bool>,
  7238. *
  7239. * wireframe: <boolean>,
  7240. * wireframeLinewidth: <float>,
  7241. *
  7242. * lights: <bool>,
  7243. *
  7244. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7245. *
  7246. * skinning: <bool>,
  7247. * morphTargets: <bool>,
  7248. * morphNormals: <bool>,
  7249. *
  7250. * fog: <bool>
  7251. * }
  7252. */
  7253. THREE.ShaderMaterial = function ( parameters ) {
  7254. THREE.Material.call( this );
  7255. this.fragmentShader = "void main() {}";
  7256. this.vertexShader = "void main() {}";
  7257. this.uniforms = {};
  7258. this.defines = {};
  7259. this.attributes = null;
  7260. this.shading = THREE.SmoothShading;
  7261. this.wireframe = false;
  7262. this.wireframeLinewidth = 1;
  7263. this.fog = false; // set to use scene fog
  7264. this.lights = false; // set to use scene lights
  7265. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7266. this.skinning = false; // set to use skinning attribute streams
  7267. this.morphTargets = false; // set to use morph targets
  7268. this.morphNormals = false; // set to use morph normals
  7269. this.setValues( parameters );
  7270. };
  7271. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7272. THREE.ShaderMaterial.prototype.clone = function () {
  7273. var material = new THREE.ShaderMaterial();
  7274. THREE.Material.prototype.clone.call( this, material );
  7275. material.fragmentShader = this.fragmentShader;
  7276. material.vertexShader = this.vertexShader;
  7277. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7278. material.attributes = this.attributes;
  7279. material.defines = this.defines;
  7280. material.shading = this.shading;
  7281. material.wireframe = this.wireframe;
  7282. material.wireframeLinewidth = this.wireframeLinewidth;
  7283. material.fog = this.fog;
  7284. material.lights = this.lights;
  7285. material.vertexColors = this.vertexColors;
  7286. material.skinning = this.skinning;
  7287. material.morphTargets = this.morphTargets;
  7288. material.morphNormals = this.morphNormals;
  7289. return material;
  7290. };
  7291. /**
  7292. * @author alteredq / http://alteredqualia.com/
  7293. *
  7294. * parameters = {
  7295. * color: <hex>,
  7296. * opacity: <float>,
  7297. * map: new THREE.Texture( <Image> ),
  7298. *
  7299. * blending: THREE.NormalBlending,
  7300. * depthTest: <bool>,
  7301. * depthWrite: <bool>,
  7302. *
  7303. * useScreenCoordinates: <bool>,
  7304. * sizeAttenuation: <bool>,
  7305. * scaleByViewport: <bool>,
  7306. * alignment: THREE.SpriteAlignment.center,
  7307. *
  7308. * uvOffset: new THREE.Vector2(),
  7309. * uvScale: new THREE.Vector2(),
  7310. *
  7311. * fog: <bool>
  7312. * }
  7313. */
  7314. THREE.SpriteMaterial = function ( parameters ) {
  7315. THREE.Material.call( this );
  7316. // defaults
  7317. this.color = new THREE.Color( 0xffffff );
  7318. this.map = new THREE.Texture();
  7319. this.useScreenCoordinates = true;
  7320. this.depthTest = !this.useScreenCoordinates;
  7321. this.sizeAttenuation = !this.useScreenCoordinates;
  7322. this.scaleByViewport = !this.sizeAttenuation;
  7323. this.alignment = THREE.SpriteAlignment.center.clone();
  7324. this.fog = false;
  7325. this.uvOffset = new THREE.Vector2( 0, 0 );
  7326. this.uvScale = new THREE.Vector2( 1, 1 );
  7327. // set parameters
  7328. this.setValues( parameters );
  7329. // override coupled defaults if not specified explicitly by parameters
  7330. parameters = parameters || {};
  7331. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7332. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7333. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7334. };
  7335. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7336. THREE.SpriteMaterial.prototype.clone = function () {
  7337. var material = new THREE.SpriteMaterial();
  7338. THREE.Material.prototype.clone.call( this, material );
  7339. material.color.copy( this.color );
  7340. material.map = this.map;
  7341. material.useScreenCoordinates = this.useScreenCoordinates;
  7342. material.sizeAttenuation = this.sizeAttenuation;
  7343. material.scaleByViewport = this.scaleByViewport;
  7344. material.alignment.copy( this.alignment );
  7345. material.uvOffset.copy( this.uvOffset );
  7346. material.uvScale.copy( this.uvScale );
  7347. material.fog = this.fog;
  7348. return material;
  7349. };
  7350. // Alignment enums
  7351. THREE.SpriteAlignment = {};
  7352. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7353. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7354. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7355. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7356. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7357. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7358. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7359. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7360. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7361. /**
  7362. * @author mrdoob / http://mrdoob.com/
  7363. * @author alteredq / http://alteredqualia.com/
  7364. * @author szimek / https://github.com/szimek/
  7365. */
  7366. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7367. THREE.EventDispatcher.call( this );
  7368. this.id = THREE.TextureIdCount ++;
  7369. this.name = '';
  7370. this.image = image;
  7371. this.mipmaps = [];
  7372. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7373. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7374. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7375. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7376. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7377. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7378. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7379. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7380. this.offset = new THREE.Vector2( 0, 0 );
  7381. this.repeat = new THREE.Vector2( 1, 1 );
  7382. this.generateMipmaps = true;
  7383. this.premultiplyAlpha = false;
  7384. this.flipY = true;
  7385. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7386. this.needsUpdate = false;
  7387. this.onUpdate = null;
  7388. };
  7389. THREE.Texture.prototype = {
  7390. constructor: THREE.Texture,
  7391. clone: function ( texture ) {
  7392. if ( texture === undefined ) texture = new THREE.Texture();
  7393. texture.image = this.image;
  7394. texture.mipmaps = this.mipmaps.slice(0);
  7395. texture.mapping = this.mapping;
  7396. texture.wrapS = this.wrapS;
  7397. texture.wrapT = this.wrapT;
  7398. texture.magFilter = this.magFilter;
  7399. texture.minFilter = this.minFilter;
  7400. texture.anisotropy = this.anisotropy;
  7401. texture.format = this.format;
  7402. texture.type = this.type;
  7403. texture.offset.copy( this.offset );
  7404. texture.repeat.copy( this.repeat );
  7405. texture.generateMipmaps = this.generateMipmaps;
  7406. texture.premultiplyAlpha = this.premultiplyAlpha;
  7407. texture.flipY = this.flipY;
  7408. texture.unpackAlignment = this.unpackAlignment;
  7409. return texture;
  7410. },
  7411. dispose: function () {
  7412. this.dispatchEvent( { type: 'dispose' } );
  7413. }
  7414. };
  7415. THREE.TextureIdCount = 0;
  7416. /**
  7417. * @author alteredq / http://alteredqualia.com/
  7418. */
  7419. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7420. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7421. this.image = { width: width, height: height };
  7422. this.mipmaps = mipmaps;
  7423. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7424. };
  7425. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7426. THREE.CompressedTexture.prototype.clone = function () {
  7427. var texture = new THREE.CompressedTexture();
  7428. THREE.Texture.prototype.clone.call( this, texture );
  7429. return texture;
  7430. };
  7431. /**
  7432. * @author alteredq / http://alteredqualia.com/
  7433. */
  7434. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7435. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7436. this.image = { data: data, width: width, height: height };
  7437. };
  7438. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7439. THREE.DataTexture.prototype.clone = function () {
  7440. var texture = new THREE.DataTexture();
  7441. THREE.Texture.prototype.clone.call( this, texture );
  7442. return texture;
  7443. };
  7444. /**
  7445. * @author mrdoob / http://mrdoob.com/
  7446. */
  7447. THREE.Particle = function ( material ) {
  7448. THREE.Object3D.call( this );
  7449. this.material = material;
  7450. };
  7451. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7452. THREE.Particle.prototype.clone = function ( object ) {
  7453. if ( object === undefined ) object = new THREE.Particle( this.material );
  7454. THREE.Object3D.prototype.clone.call( this, object );
  7455. return object;
  7456. };
  7457. /**
  7458. * @author alteredq / http://alteredqualia.com/
  7459. */
  7460. THREE.ParticleSystem = function ( geometry, material ) {
  7461. THREE.Object3D.call( this );
  7462. this.geometry = geometry;
  7463. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7464. this.sortParticles = false;
  7465. if ( this.geometry ) {
  7466. // calc bound radius
  7467. if( this.geometry.boundingSphere === null ) {
  7468. this.geometry.computeBoundingSphere();
  7469. }
  7470. }
  7471. this.frustumCulled = false;
  7472. };
  7473. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7474. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7475. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7476. object.sortParticles = this.sortParticles;
  7477. THREE.Object3D.prototype.clone.call( this, object );
  7478. return object;
  7479. };
  7480. /**
  7481. * @author mrdoob / http://mrdoob.com/
  7482. */
  7483. THREE.Line = function ( geometry, material, type ) {
  7484. THREE.Object3D.call( this );
  7485. this.geometry = geometry;
  7486. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7487. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7488. if ( this.geometry ) {
  7489. if ( ! this.geometry.boundingSphere ) {
  7490. this.geometry.computeBoundingSphere();
  7491. }
  7492. }
  7493. };
  7494. THREE.LineStrip = 0;
  7495. THREE.LinePieces = 1;
  7496. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7497. THREE.Line.prototype.clone = function ( object ) {
  7498. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7499. THREE.Object3D.prototype.clone.call( this, object );
  7500. return object;
  7501. };
  7502. /**
  7503. * @author mrdoob / http://mrdoob.com/
  7504. * @author alteredq / http://alteredqualia.com/
  7505. * @author mikael emtinger / http://gomo.se/
  7506. * @author jonobr1 / http://jonobr1.com/
  7507. */
  7508. THREE.Mesh = function ( geometry, material ) {
  7509. THREE.Object3D.call( this );
  7510. this.geometry = geometry;
  7511. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7512. if ( this.geometry !== undefined ) {
  7513. if ( this.geometry.boundingSphere === null ) {
  7514. this.geometry.computeBoundingSphere();
  7515. }
  7516. this.updateMorphTargets();
  7517. }
  7518. };
  7519. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7520. THREE.Mesh.prototype.updateMorphTargets = function () {
  7521. if ( this.geometry.morphTargets.length > 0 ) {
  7522. this.morphTargetBase = -1;
  7523. this.morphTargetForcedOrder = [];
  7524. this.morphTargetInfluences = [];
  7525. this.morphTargetDictionary = {};
  7526. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7527. this.morphTargetInfluences.push( 0 );
  7528. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7529. }
  7530. }
  7531. };
  7532. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7533. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7534. return this.morphTargetDictionary[ name ];
  7535. }
  7536. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7537. return 0;
  7538. };
  7539. THREE.Mesh.prototype.clone = function ( object ) {
  7540. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7541. THREE.Object3D.prototype.clone.call( this, object );
  7542. return object;
  7543. };
  7544. /**
  7545. * @author mikael emtinger / http://gomo.se/
  7546. * @author alteredq / http://alteredqualia.com/
  7547. */
  7548. THREE.Bone = function( belongsToSkin ) {
  7549. THREE.Object3D.call( this );
  7550. this.skin = belongsToSkin;
  7551. this.skinMatrix = new THREE.Matrix4();
  7552. };
  7553. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7554. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7555. // update local
  7556. if ( this.matrixAutoUpdate ) {
  7557. forceUpdate |= this.updateMatrix();
  7558. }
  7559. // update skin matrix
  7560. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7561. if( parentSkinMatrix ) {
  7562. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7563. } else {
  7564. this.skinMatrix.copy( this.matrix );
  7565. }
  7566. this.matrixWorldNeedsUpdate = false;
  7567. forceUpdate = true;
  7568. }
  7569. // update children
  7570. var child, i, l = this.children.length;
  7571. for ( i = 0; i < l; i ++ ) {
  7572. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7573. }
  7574. };
  7575. /**
  7576. * @author mikael emtinger / http://gomo.se/
  7577. * @author alteredq / http://alteredqualia.com/
  7578. */
  7579. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7580. THREE.Mesh.call( this, geometry, material );
  7581. //
  7582. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7583. // init bones
  7584. this.identityMatrix = new THREE.Matrix4();
  7585. this.bones = [];
  7586. this.boneMatrices = [];
  7587. var b, bone, gbone, p, q, s;
  7588. if ( this.geometry && this.geometry.bones !== undefined ) {
  7589. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7590. gbone = this.geometry.bones[ b ];
  7591. p = gbone.pos;
  7592. q = gbone.rotq;
  7593. s = gbone.scl;
  7594. bone = this.addBone();
  7595. bone.name = gbone.name;
  7596. bone.position.set( p[0], p[1], p[2] );
  7597. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7598. bone.useQuaternion = true;
  7599. if ( s !== undefined ) {
  7600. bone.scale.set( s[0], s[1], s[2] );
  7601. } else {
  7602. bone.scale.set( 1, 1, 1 );
  7603. }
  7604. }
  7605. for ( b = 0; b < this.bones.length; b ++ ) {
  7606. gbone = this.geometry.bones[ b ];
  7607. bone = this.bones[ b ];
  7608. if ( gbone.parent === -1 ) {
  7609. this.add( bone );
  7610. } else {
  7611. this.bones[ gbone.parent ].add( bone );
  7612. }
  7613. }
  7614. //
  7615. var nBones = this.bones.length;
  7616. if ( this.useVertexTexture ) {
  7617. // layout (1 matrix = 4 pixels)
  7618. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7619. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7620. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7621. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7622. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7623. var size;
  7624. if ( nBones > 256 )
  7625. size = 64;
  7626. else if ( nBones > 64 )
  7627. size = 32;
  7628. else if ( nBones > 16 )
  7629. size = 16;
  7630. else
  7631. size = 8;
  7632. this.boneTextureWidth = size;
  7633. this.boneTextureHeight = size;
  7634. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7635. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7636. this.boneTexture.minFilter = THREE.NearestFilter;
  7637. this.boneTexture.magFilter = THREE.NearestFilter;
  7638. this.boneTexture.generateMipmaps = false;
  7639. this.boneTexture.flipY = false;
  7640. } else {
  7641. this.boneMatrices = new Float32Array( 16 * nBones );
  7642. }
  7643. this.pose();
  7644. }
  7645. };
  7646. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7647. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7648. if ( bone === undefined ) {
  7649. bone = new THREE.Bone( this );
  7650. }
  7651. this.bones.push( bone );
  7652. return bone;
  7653. };
  7654. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7655. this.matrixAutoUpdate && this.updateMatrix();
  7656. // update matrixWorld
  7657. if ( this.matrixWorldNeedsUpdate || force ) {
  7658. if ( this.parent ) {
  7659. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7660. } else {
  7661. this.matrixWorld.copy( this.matrix );
  7662. }
  7663. this.matrixWorldNeedsUpdate = false;
  7664. force = true;
  7665. }
  7666. // update children
  7667. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7668. var child = this.children[ i ];
  7669. if ( child instanceof THREE.Bone ) {
  7670. child.update( this.identityMatrix, false );
  7671. } else {
  7672. child.updateMatrixWorld( true );
  7673. }
  7674. }
  7675. // make a snapshot of the bones' rest position
  7676. if ( this.boneInverses == undefined ) {
  7677. this.boneInverses = [];
  7678. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7679. var inverse = new THREE.Matrix4();
  7680. inverse.getInverse( this.bones[ b ].skinMatrix );
  7681. this.boneInverses.push( inverse );
  7682. }
  7683. }
  7684. // flatten bone matrices to array
  7685. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7686. // compute the offset between the current and the original transform;
  7687. //TODO: we could get rid of this multiplication step if the skinMatrix
  7688. // was already representing the offset; however, this requires some
  7689. // major changes to the animation system
  7690. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7691. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7692. }
  7693. if ( this.useVertexTexture ) {
  7694. this.boneTexture.needsUpdate = true;
  7695. }
  7696. };
  7697. THREE.SkinnedMesh.prototype.pose = function () {
  7698. this.updateMatrixWorld( true );
  7699. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7700. // normalize weights
  7701. var sw = this.geometry.skinWeights[ i ];
  7702. var scale = 1.0 / sw.lengthManhattan();
  7703. if ( scale !== Infinity ) {
  7704. sw.multiplyScalar( scale );
  7705. } else {
  7706. sw.set( 1 ); // this will be normalized by the shader anyway
  7707. }
  7708. }
  7709. };
  7710. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7711. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7712. THREE.Mesh.prototype.clone.call( this, object );
  7713. return object;
  7714. };
  7715. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7716. /**
  7717. * @author alteredq / http://alteredqualia.com/
  7718. */
  7719. THREE.MorphAnimMesh = function ( geometry, material ) {
  7720. THREE.Mesh.call( this, geometry, material );
  7721. // API
  7722. this.duration = 1000; // milliseconds
  7723. this.mirroredLoop = false;
  7724. this.time = 0;
  7725. // internals
  7726. this.lastKeyframe = 0;
  7727. this.currentKeyframe = 0;
  7728. this.direction = 1;
  7729. this.directionBackwards = false;
  7730. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7731. };
  7732. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7733. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7734. this.startKeyframe = start;
  7735. this.endKeyframe = end;
  7736. this.length = this.endKeyframe - this.startKeyframe + 1;
  7737. };
  7738. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7739. this.direction = 1;
  7740. this.directionBackwards = false;
  7741. };
  7742. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7743. this.direction = -1;
  7744. this.directionBackwards = true;
  7745. };
  7746. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7747. var geometry = this.geometry;
  7748. if ( ! geometry.animations ) geometry.animations = {};
  7749. var firstAnimation, animations = geometry.animations;
  7750. var pattern = /([a-z]+)(\d+)/;
  7751. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7752. var morph = geometry.morphTargets[ i ];
  7753. var parts = morph.name.match( pattern );
  7754. if ( parts && parts.length > 1 ) {
  7755. var label = parts[ 1 ];
  7756. var num = parts[ 2 ];
  7757. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7758. var animation = animations[ label ];
  7759. if ( i < animation.start ) animation.start = i;
  7760. if ( i > animation.end ) animation.end = i;
  7761. if ( ! firstAnimation ) firstAnimation = label;
  7762. }
  7763. }
  7764. geometry.firstAnimation = firstAnimation;
  7765. };
  7766. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7767. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7768. this.geometry.animations[ label ] = { start: start, end: end };
  7769. };
  7770. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7771. var animation = this.geometry.animations[ label ];
  7772. if ( animation ) {
  7773. this.setFrameRange( animation.start, animation.end );
  7774. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7775. this.time = 0;
  7776. } else {
  7777. console.warn( "animation[" + label + "] undefined" );
  7778. }
  7779. };
  7780. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7781. var frameTime = this.duration / this.length;
  7782. this.time += this.direction * delta;
  7783. if ( this.mirroredLoop ) {
  7784. if ( this.time > this.duration || this.time < 0 ) {
  7785. this.direction *= -1;
  7786. if ( this.time > this.duration ) {
  7787. this.time = this.duration;
  7788. this.directionBackwards = true;
  7789. }
  7790. if ( this.time < 0 ) {
  7791. this.time = 0;
  7792. this.directionBackwards = false;
  7793. }
  7794. }
  7795. } else {
  7796. this.time = this.time % this.duration;
  7797. if ( this.time < 0 ) this.time += this.duration;
  7798. }
  7799. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7800. if ( keyframe !== this.currentKeyframe ) {
  7801. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7802. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7803. this.morphTargetInfluences[ keyframe ] = 0;
  7804. this.lastKeyframe = this.currentKeyframe;
  7805. this.currentKeyframe = keyframe;
  7806. }
  7807. var mix = ( this.time % frameTime ) / frameTime;
  7808. if ( this.directionBackwards ) {
  7809. mix = 1 - mix;
  7810. }
  7811. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7812. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7813. };
  7814. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7815. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7816. object.duration = this.duration;
  7817. object.mirroredLoop = this.mirroredLoop;
  7818. object.time = this.time;
  7819. object.lastKeyframe = this.lastKeyframe;
  7820. object.currentKeyframe = this.currentKeyframe;
  7821. object.direction = this.direction;
  7822. object.directionBackwards = this.directionBackwards;
  7823. THREE.Mesh.prototype.clone.call( this, object );
  7824. return object;
  7825. };
  7826. /**
  7827. * @author alteredq / http://alteredqualia.com/
  7828. */
  7829. THREE.Ribbon = function ( geometry, material ) {
  7830. THREE.Object3D.call( this );
  7831. this.geometry = geometry;
  7832. this.material = material;
  7833. };
  7834. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7835. THREE.Ribbon.prototype.clone = function ( object ) {
  7836. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7837. THREE.Object3D.prototype.clone.call( this, object );
  7838. return object;
  7839. };
  7840. /**
  7841. * @author mikael emtinger / http://gomo.se/
  7842. * @author alteredq / http://alteredqualia.com/
  7843. * @author mrdoob / http://mrdoob.com/
  7844. */
  7845. THREE.LOD = function () {
  7846. THREE.Object3D.call( this );
  7847. this.LODs = [];
  7848. };
  7849. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7850. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7851. if ( visibleAtDistance === undefined ) {
  7852. visibleAtDistance = 0;
  7853. }
  7854. visibleAtDistance = Math.abs( visibleAtDistance );
  7855. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7856. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7857. break;
  7858. }
  7859. }
  7860. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7861. this.add( object3D );
  7862. };
  7863. THREE.LOD.prototype.update = function ( camera ) {
  7864. if ( this.LODs.length > 1 ) {
  7865. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7866. var inverse = camera.matrixWorldInverse;
  7867. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7868. this.LODs[ 0 ].object3D.visible = true;
  7869. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7870. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7871. this.LODs[ l - 1 ].object3D.visible = false;
  7872. this.LODs[ l ].object3D.visible = true;
  7873. } else {
  7874. break;
  7875. }
  7876. }
  7877. for( ; l < this.LODs.length; l ++ ) {
  7878. this.LODs[ l ].object3D.visible = false;
  7879. }
  7880. }
  7881. };
  7882. THREE.LOD.prototype.clone = function () {
  7883. // TODO
  7884. };
  7885. /**
  7886. * @author mikael emtinger / http://gomo.se/
  7887. * @author alteredq / http://alteredqualia.com/
  7888. */
  7889. THREE.Sprite = function ( material ) {
  7890. THREE.Object3D.call( this );
  7891. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7892. this.rotation3d = this.rotation;
  7893. this.rotation = 0;
  7894. };
  7895. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7896. /*
  7897. * Custom update matrix
  7898. */
  7899. THREE.Sprite.prototype.updateMatrix = function () {
  7900. this.matrix.setPosition( this.position );
  7901. this.rotation3d.set( 0, 0, this.rotation );
  7902. this.matrix.setRotationFromEuler( this.rotation3d );
  7903. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7904. this.matrix.scale( this.scale );
  7905. }
  7906. this.matrixWorldNeedsUpdate = true;
  7907. };
  7908. THREE.Sprite.prototype.clone = function ( object ) {
  7909. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7910. THREE.Object3D.prototype.clone.call( this, object );
  7911. return object;
  7912. };
  7913. /**
  7914. * @author mrdoob / http://mrdoob.com/
  7915. */
  7916. THREE.Scene = function () {
  7917. THREE.Object3D.call( this );
  7918. this.fog = null;
  7919. this.overrideMaterial = null;
  7920. this.matrixAutoUpdate = false;
  7921. this.__objects = [];
  7922. this.__lights = [];
  7923. this.__objectsAdded = [];
  7924. this.__objectsRemoved = [];
  7925. };
  7926. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7927. THREE.Scene.prototype.__addObject = function ( object ) {
  7928. if ( object instanceof THREE.Light ) {
  7929. if ( this.__lights.indexOf( object ) === - 1 ) {
  7930. this.__lights.push( object );
  7931. }
  7932. if ( object.target && object.target.parent === undefined ) {
  7933. this.add( object.target );
  7934. }
  7935. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7936. if ( this.__objects.indexOf( object ) === - 1 ) {
  7937. this.__objects.push( object );
  7938. this.__objectsAdded.push( object );
  7939. // check if previously removed
  7940. var i = this.__objectsRemoved.indexOf( object );
  7941. if ( i !== -1 ) {
  7942. this.__objectsRemoved.splice( i, 1 );
  7943. }
  7944. }
  7945. }
  7946. for ( var c = 0; c < object.children.length; c ++ ) {
  7947. this.__addObject( object.children[ c ] );
  7948. }
  7949. };
  7950. THREE.Scene.prototype.__removeObject = function ( object ) {
  7951. if ( object instanceof THREE.Light ) {
  7952. var i = this.__lights.indexOf( object );
  7953. if ( i !== -1 ) {
  7954. this.__lights.splice( i, 1 );
  7955. }
  7956. } else if ( !( object instanceof THREE.Camera ) ) {
  7957. var i = this.__objects.indexOf( object );
  7958. if( i !== -1 ) {
  7959. this.__objects.splice( i, 1 );
  7960. this.__objectsRemoved.push( object );
  7961. // check if previously added
  7962. var ai = this.__objectsAdded.indexOf( object );
  7963. if ( ai !== -1 ) {
  7964. this.__objectsAdded.splice( ai, 1 );
  7965. }
  7966. }
  7967. }
  7968. for ( var c = 0; c < object.children.length; c ++ ) {
  7969. this.__removeObject( object.children[ c ] );
  7970. }
  7971. };
  7972. /**
  7973. * @author mrdoob / http://mrdoob.com/
  7974. * @author alteredq / http://alteredqualia.com/
  7975. */
  7976. THREE.Fog = function ( hex, near, far ) {
  7977. this.name = '';
  7978. this.color = new THREE.Color( hex );
  7979. this.near = ( near !== undefined ) ? near : 1;
  7980. this.far = ( far !== undefined ) ? far : 1000;
  7981. };
  7982. THREE.Fog.prototype.clone = function () {
  7983. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7984. };
  7985. /**
  7986. * @author mrdoob / http://mrdoob.com/
  7987. * @author alteredq / http://alteredqualia.com/
  7988. */
  7989. THREE.FogExp2 = function ( hex, density ) {
  7990. this.name = '';
  7991. this.color = new THREE.Color( hex );
  7992. this.density = ( density !== undefined ) ? density : 0.00025;
  7993. };
  7994. THREE.FogExp2.prototype.clone = function () {
  7995. return new THREE.FogExp2( this.color.getHex(), this.density );
  7996. };
  7997. /**
  7998. * @author mrdoob / http://mrdoob.com/
  7999. */
  8000. THREE.CanvasRenderer = function ( parameters ) {
  8001. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8002. var smoothstep = THREE.Math.smoothstep;
  8003. parameters = parameters || {};
  8004. var _this = this,
  8005. _renderData, _elements, _lights,
  8006. _projector = new THREE.Projector(),
  8007. _canvas = parameters.canvas !== undefined
  8008. ? parameters.canvas
  8009. : document.createElement( 'canvas' ),
  8010. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8011. _context = _canvas.getContext( '2d' ),
  8012. _clearColor = new THREE.Color( 0x000000 ),
  8013. _clearOpacity = 0,
  8014. _contextGlobalAlpha = 1,
  8015. _contextGlobalCompositeOperation = 0,
  8016. _contextStrokeStyle = null,
  8017. _contextFillStyle = null,
  8018. _contextLineWidth = null,
  8019. _contextLineCap = null,
  8020. _contextLineJoin = null,
  8021. _contextDashSize = null,
  8022. _contextGapSize = 0,
  8023. _v1, _v2, _v3, _v4,
  8024. _v5 = new THREE.RenderableVertex(),
  8025. _v6 = new THREE.RenderableVertex(),
  8026. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8027. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8028. _color = new THREE.Color(),
  8029. _color1 = new THREE.Color(),
  8030. _color2 = new THREE.Color(),
  8031. _color3 = new THREE.Color(),
  8032. _color4 = new THREE.Color(),
  8033. _diffuseColor = new THREE.Color(),
  8034. _emissiveColor = new THREE.Color(),
  8035. _lightColor = new THREE.Color(),
  8036. _patterns = {}, _imagedatas = {},
  8037. _near, _far,
  8038. _image, _uvs,
  8039. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8040. _clipBox = new THREE.Box2(),
  8041. _clearBox = new THREE.Box2(),
  8042. _elemBox = new THREE.Box2(),
  8043. _ambientLight = new THREE.Color(),
  8044. _directionalLights = new THREE.Color(),
  8045. _pointLights = new THREE.Color(),
  8046. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8047. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8048. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8049. _pixelMap = document.createElement( 'canvas' );
  8050. _pixelMap.width = _pixelMap.height = 2;
  8051. _pixelMapContext = _pixelMap.getContext( '2d' );
  8052. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8053. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8054. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8055. _pixelMapData = _pixelMapImage.data;
  8056. _gradientMap = document.createElement( 'canvas' );
  8057. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8058. _gradientMapContext = _gradientMap.getContext( '2d' );
  8059. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8060. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8061. _gradientMapQuality --; // Fix UVs
  8062. // dash+gap fallbacks for Firefox and everything else
  8063. if ( _context.setLineDash === undefined ) {
  8064. if ( _context.mozDash !== undefined ) {
  8065. _context.setLineDash = function ( values ) {
  8066. _context.mozDash = values[ 0 ] !== null ? values : null;
  8067. }
  8068. } else {
  8069. _context.setLineDash = function () {}
  8070. }
  8071. }
  8072. this.domElement = _canvas;
  8073. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8074. ? parameters.devicePixelRatio
  8075. : window.devicePixelRatio !== undefined
  8076. ? window.devicePixelRatio
  8077. : 1;
  8078. this.autoClear = true;
  8079. this.sortObjects = true;
  8080. this.sortElements = true;
  8081. this.info = {
  8082. render: {
  8083. vertices: 0,
  8084. faces: 0
  8085. }
  8086. }
  8087. // WebGLRenderer compatibility
  8088. this.supportsVertexTextures = function () {};
  8089. this.setFaceCulling = function () {};
  8090. this.setSize = function ( width, height ) {
  8091. _canvasWidth = width * this.devicePixelRatio;
  8092. _canvasHeight = height * this.devicePixelRatio;
  8093. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8094. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8095. _canvas.width = _canvasWidth;
  8096. _canvas.height = _canvasHeight;
  8097. _canvas.style.width = width + 'px';
  8098. _canvas.style.height = height + 'px';
  8099. _clipBox.set(
  8100. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8101. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8102. );
  8103. _clearBox.set(
  8104. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8105. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8106. );
  8107. _contextGlobalAlpha = 1;
  8108. _contextGlobalCompositeOperation = 0;
  8109. _contextStrokeStyle = null;
  8110. _contextFillStyle = null;
  8111. _contextLineWidth = null;
  8112. _contextLineCap = null;
  8113. _contextLineJoin = null;
  8114. };
  8115. this.setClearColor = function ( color, opacity ) {
  8116. _clearColor.copy( color );
  8117. _clearOpacity = opacity !== undefined ? opacity : 1;
  8118. _clearBox.set(
  8119. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8120. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8121. );
  8122. };
  8123. this.setClearColorHex = function ( hex, opacity ) {
  8124. _clearColor.setHex( hex );
  8125. _clearOpacity = opacity !== undefined ? opacity : 1;
  8126. _clearBox.set(
  8127. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8128. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8129. );
  8130. };
  8131. this.getMaxAnisotropy = function () {
  8132. return 0;
  8133. };
  8134. this.clear = function () {
  8135. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8136. if ( _clearBox.empty() === false ) {
  8137. _clearBox.intersect( _clipBox );
  8138. _clearBox.expandByScalar( 2 );
  8139. if ( _clearOpacity < 1 ) {
  8140. _context.clearRect(
  8141. _clearBox.min.x | 0,
  8142. _clearBox.min.y | 0,
  8143. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8144. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8145. );
  8146. }
  8147. if ( _clearOpacity > 0 ) {
  8148. setBlending( THREE.NormalBlending );
  8149. setOpacity( 1 );
  8150. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8151. _context.fillRect(
  8152. _clearBox.min.x | 0,
  8153. _clearBox.min.y | 0,
  8154. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8155. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8156. );
  8157. }
  8158. _clearBox.makeEmpty();
  8159. }
  8160. };
  8161. this.render = function ( scene, camera ) {
  8162. if ( camera instanceof THREE.Camera === false ) {
  8163. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8164. return;
  8165. }
  8166. if ( this.autoClear === true ) {
  8167. this.clear();
  8168. }
  8169. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8170. _this.info.render.vertices = 0;
  8171. _this.info.render.faces = 0;
  8172. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8173. _elements = _renderData.elements;
  8174. _lights = _renderData.lights;
  8175. /* DEBUG
  8176. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8177. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8178. */
  8179. calculateLights();
  8180. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8181. var element = _elements[ e ];
  8182. var material = element.material;
  8183. if ( material === undefined || material.visible === false ) continue;
  8184. _elemBox.makeEmpty();
  8185. if ( element instanceof THREE.RenderableParticle ) {
  8186. _v1 = element;
  8187. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8188. renderParticle( _v1, element, material );
  8189. } else if ( element instanceof THREE.RenderableLine ) {
  8190. _v1 = element.v1; _v2 = element.v2;
  8191. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8192. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8193. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8194. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8195. renderLine( _v1, _v2, element, material );
  8196. }
  8197. } else if ( element instanceof THREE.RenderableFace3 ) {
  8198. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8199. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8200. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8201. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8202. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8203. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8204. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8205. if ( material.overdraw === true ) {
  8206. expand( _v1.positionScreen, _v2.positionScreen );
  8207. expand( _v2.positionScreen, _v3.positionScreen );
  8208. expand( _v3.positionScreen, _v1.positionScreen );
  8209. }
  8210. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8211. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8212. } else if ( element instanceof THREE.RenderableFace4 ) {
  8213. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8214. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8215. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8216. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8217. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8218. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8219. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8220. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8221. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8222. _v5.positionScreen.copy( _v2.positionScreen );
  8223. _v6.positionScreen.copy( _v4.positionScreen );
  8224. if ( material.overdraw === true ) {
  8225. expand( _v1.positionScreen, _v2.positionScreen );
  8226. expand( _v2.positionScreen, _v4.positionScreen );
  8227. expand( _v4.positionScreen, _v1.positionScreen );
  8228. expand( _v3.positionScreen, _v5.positionScreen );
  8229. expand( _v3.positionScreen, _v6.positionScreen );
  8230. }
  8231. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8232. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8233. }
  8234. /* DEBUG
  8235. setLineWidth( 1 );
  8236. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8237. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8238. */
  8239. _clearBox.union( _elemBox );
  8240. }
  8241. /* DEBUG
  8242. setLineWidth( 1 );
  8243. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8244. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8245. */
  8246. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8247. //
  8248. function calculateLights() {
  8249. _ambientLight.setRGB( 0, 0, 0 );
  8250. _directionalLights.setRGB( 0, 0, 0 );
  8251. _pointLights.setRGB( 0, 0, 0 );
  8252. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8253. var light = _lights[ l ];
  8254. var lightColor = light.color;
  8255. if ( light instanceof THREE.AmbientLight ) {
  8256. _ambientLight.add( lightColor );
  8257. } else if ( light instanceof THREE.DirectionalLight ) {
  8258. // for particles
  8259. _directionalLights.add( lightColor );
  8260. } else if ( light instanceof THREE.PointLight ) {
  8261. // for particles
  8262. _pointLights.add( lightColor );
  8263. }
  8264. }
  8265. }
  8266. function calculateLight( position, normal, color ) {
  8267. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8268. var light = _lights[ l ];
  8269. _lightColor.copy( light.color );
  8270. if ( light instanceof THREE.DirectionalLight ) {
  8271. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8272. var amount = normal.dot( lightPosition );
  8273. if ( amount <= 0 ) continue;
  8274. amount *= light.intensity;
  8275. color.add( _lightColor.multiplyScalar( amount ) );
  8276. } else if ( light instanceof THREE.PointLight ) {
  8277. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8278. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8279. if ( amount <= 0 ) continue;
  8280. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8281. if ( amount == 0 ) continue;
  8282. amount *= light.intensity;
  8283. color.add( _lightColor.multiplyScalar( amount ) );
  8284. }
  8285. }
  8286. }
  8287. function renderParticle( v1, element, material ) {
  8288. setOpacity( material.opacity );
  8289. setBlending( material.blending );
  8290. var width, height, scaleX, scaleY,
  8291. bitmap, bitmapWidth, bitmapHeight;
  8292. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8293. if ( material.map === null ) {
  8294. scaleX = element.object.scale.x;
  8295. scaleY = element.object.scale.y;
  8296. // TODO: Be able to disable this
  8297. scaleX *= element.scale.x * _canvasWidthHalf;
  8298. scaleY *= element.scale.y * _canvasHeightHalf;
  8299. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8300. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8301. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8302. return;
  8303. }
  8304. setFillStyle( material.color.getStyle() );
  8305. _context.save();
  8306. _context.translate( v1.x, v1.y );
  8307. _context.rotate( - element.rotation );
  8308. _context.scale( scaleX, scaleY );
  8309. _context.fillRect( -1, -1, 2, 2 );
  8310. _context.restore();
  8311. } else {
  8312. bitmap = material.map.image;
  8313. bitmapWidth = bitmap.width >> 1;
  8314. bitmapHeight = bitmap.height >> 1;
  8315. scaleX = element.scale.x * _canvasWidthHalf;
  8316. scaleY = element.scale.y * _canvasHeightHalf;
  8317. width = scaleX * bitmapWidth;
  8318. height = scaleY * bitmapHeight;
  8319. // TODO: Rotations break this...
  8320. _elemBox.min.set( v1.x - width, v1.y - height );
  8321. _elemBox.max.set( v1.x + width, v1.y + height );
  8322. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8323. return;
  8324. }
  8325. _context.save();
  8326. _context.translate( v1.x, v1.y );
  8327. _context.rotate( - element.rotation );
  8328. _context.scale( scaleX, - scaleY );
  8329. _context.translate( - bitmapWidth, - bitmapHeight );
  8330. _context.drawImage( bitmap, 0, 0 );
  8331. _context.restore();
  8332. }
  8333. /* DEBUG
  8334. setStrokeStyle( 'rgb(255,255,0)' );
  8335. _context.beginPath();
  8336. _context.moveTo( v1.x - 10, v1.y );
  8337. _context.lineTo( v1.x + 10, v1.y );
  8338. _context.moveTo( v1.x, v1.y - 10 );
  8339. _context.lineTo( v1.x, v1.y + 10 );
  8340. _context.stroke();
  8341. */
  8342. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8343. width = element.scale.x * _canvasWidthHalf;
  8344. height = element.scale.y * _canvasHeightHalf;
  8345. _elemBox.min.set( v1.x - width, v1.y - height );
  8346. _elemBox.max.set( v1.x + width, v1.y + height );
  8347. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8348. return;
  8349. }
  8350. setStrokeStyle( material.color.getStyle() );
  8351. setFillStyle( material.color.getStyle() );
  8352. _context.save();
  8353. _context.translate( v1.x, v1.y );
  8354. _context.rotate( - element.rotation );
  8355. _context.scale( width, height );
  8356. material.program( _context );
  8357. _context.restore();
  8358. }
  8359. }
  8360. function renderLine( v1, v2, element, material ) {
  8361. setOpacity( material.opacity );
  8362. setBlending( material.blending );
  8363. _context.beginPath();
  8364. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8365. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8366. if ( material instanceof THREE.LineBasicMaterial ) {
  8367. setLineWidth( material.linewidth );
  8368. setLineCap( material.linecap );
  8369. setLineJoin( material.linejoin );
  8370. setStrokeStyle( material.color.getStyle() );
  8371. setDashAndGap( null, null );
  8372. _context.stroke();
  8373. _elemBox.expandByScalar( material.linewidth * 2 );
  8374. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8375. setLineWidth( material.linewidth );
  8376. setLineCap( material.linecap );
  8377. setLineJoin( material.linejoin );
  8378. setStrokeStyle( material.color.getStyle() );
  8379. setDashAndGap( material.dashSize, material.gapSize );
  8380. _context.stroke();
  8381. _elemBox.expandByScalar( material.linewidth * 2 );
  8382. }
  8383. }
  8384. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8385. _this.info.render.vertices += 3;
  8386. _this.info.render.faces ++;
  8387. setOpacity( material.opacity );
  8388. setBlending( material.blending );
  8389. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8390. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8391. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8392. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8393. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8394. _diffuseColor.copy( material.color );
  8395. _emissiveColor.copy( material.emissive );
  8396. if ( material.vertexColors === THREE.FaceColors ) {
  8397. _diffuseColor.multiply( element.color );
  8398. }
  8399. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8400. _color1.copy( _ambientLight );
  8401. _color2.copy( _ambientLight );
  8402. _color3.copy( _ambientLight );
  8403. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8404. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8405. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8406. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8407. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8408. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8409. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8410. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8411. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8412. } else {
  8413. _color.copy( _ambientLight );
  8414. calculateLight( element.centroidModel, element.normalModel, _color );
  8415. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8416. material.wireframe === true
  8417. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8418. : fillPath( _color );
  8419. }
  8420. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8421. if ( material.map !== null ) {
  8422. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8423. _uvs = element.uvs[ 0 ];
  8424. 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 );
  8425. }
  8426. } else if ( material.envMap !== null ) {
  8427. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8428. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8429. _uv1x = 0.5 * _vector3.x + 0.5;
  8430. _uv1y = 0.5 * _vector3.y + 0.5;
  8431. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8432. _uv2x = 0.5 * _vector3.x + 0.5;
  8433. _uv2y = 0.5 * _vector3.y + 0.5;
  8434. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8435. _uv3x = 0.5 * _vector3.x + 0.5;
  8436. _uv3y = 0.5 * _vector3.y + 0.5;
  8437. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8438. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8439. }*/
  8440. } else {
  8441. _color.copy( material.color );
  8442. if ( material.vertexColors === THREE.FaceColors ) {
  8443. _color.multiply( element.color );
  8444. }
  8445. material.wireframe === true
  8446. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8447. : fillPath( _color );
  8448. }
  8449. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8450. _near = camera.near;
  8451. _far = camera.far;
  8452. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8453. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8454. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8455. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8456. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8457. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8458. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8459. var normal;
  8460. if ( material.shading == THREE.FlatShading ) {
  8461. normal = element.normalModelView;
  8462. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8463. material.wireframe === true
  8464. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8465. : fillPath( _color );
  8466. } else if ( material.shading == THREE.SmoothShading ) {
  8467. normal = element.vertexNormalsModelView[ uv1 ];
  8468. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8469. normal = element.vertexNormalsModelView[ uv2 ];
  8470. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8471. normal = element.vertexNormalsModelView[ uv3 ];
  8472. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8473. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8474. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8475. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8476. }
  8477. }
  8478. }
  8479. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8480. _this.info.render.vertices += 4;
  8481. _this.info.render.faces ++;
  8482. setOpacity( material.opacity );
  8483. setBlending( material.blending );
  8484. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8485. // Let renderFace3() handle this
  8486. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8487. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8488. return;
  8489. }
  8490. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8491. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8492. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8493. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8494. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8495. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8496. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8497. _diffuseColor.copy( material.color );
  8498. _emissiveColor.copy( material.emissive );
  8499. if ( material.vertexColors === THREE.FaceColors ) {
  8500. _diffuseColor.multiply( element.color );
  8501. }
  8502. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8503. _color1.copy( _ambientLight );
  8504. _color2.copy( _ambientLight );
  8505. _color3.copy( _ambientLight );
  8506. _color4.copy( _ambientLight );
  8507. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8508. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8509. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8510. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8511. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8512. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8513. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8514. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8515. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8516. // TODO: UVs are incorrect, v4->v3?
  8517. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8518. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8519. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8520. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8521. } else {
  8522. _color.copy( _ambientLight );
  8523. calculateLight( element.centroidModel, element.normalModel, _color );
  8524. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8525. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8526. material.wireframe === true
  8527. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8528. : fillPath( _color );
  8529. }
  8530. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8531. _color.copy( material.color );
  8532. if ( material.vertexColors === THREE.FaceColors ) {
  8533. _color.multiply( element.color );
  8534. }
  8535. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8536. material.wireframe === true
  8537. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8538. : fillPath( _color );
  8539. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8540. var normal;
  8541. if ( material.shading == THREE.FlatShading ) {
  8542. normal = element.normalModelView;
  8543. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8544. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8545. material.wireframe === true
  8546. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8547. : fillPath( _color );
  8548. } else if ( material.shading == THREE.SmoothShading ) {
  8549. normal = element.vertexNormalsModelView[ 0 ];
  8550. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8551. normal = element.vertexNormalsModelView[ 1 ];
  8552. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8553. normal = element.vertexNormalsModelView[ 3 ];
  8554. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8555. normal = element.vertexNormalsModelView[ 2 ];
  8556. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8557. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8558. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8559. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8560. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8561. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8562. }
  8563. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8564. _near = camera.near;
  8565. _far = camera.far;
  8566. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8567. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8568. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8569. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8570. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8571. // TODO: UVs are incorrect, v4->v3?
  8572. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8573. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8574. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8575. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8576. }
  8577. }
  8578. //
  8579. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8580. _context.beginPath();
  8581. _context.moveTo( x0, y0 );
  8582. _context.lineTo( x1, y1 );
  8583. _context.lineTo( x2, y2 );
  8584. _context.closePath();
  8585. }
  8586. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8587. _context.beginPath();
  8588. _context.moveTo( x0, y0 );
  8589. _context.lineTo( x1, y1 );
  8590. _context.lineTo( x2, y2 );
  8591. _context.lineTo( x3, y3 );
  8592. _context.closePath();
  8593. }
  8594. function strokePath( color, linewidth, linecap, linejoin ) {
  8595. setLineWidth( linewidth );
  8596. setLineCap( linecap );
  8597. setLineJoin( linejoin );
  8598. setStrokeStyle( color.getStyle() );
  8599. _context.stroke();
  8600. _elemBox.expandByScalar( linewidth * 2 );
  8601. }
  8602. function fillPath( color ) {
  8603. setFillStyle( color.getStyle() );
  8604. _context.fill();
  8605. }
  8606. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8607. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8608. if ( texture.needsUpdate === true ) {
  8609. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8610. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8611. _patterns[ texture.id ] = _context.createPattern(
  8612. texture.image, repeatX === true && repeatY === true
  8613. ? 'repeat'
  8614. : repeatX === true && repeatY === false
  8615. ? 'repeat-x'
  8616. : repeatX === false && repeatY === true
  8617. ? 'repeat-y'
  8618. : 'no-repeat'
  8619. );
  8620. texture.needsUpdate = false;
  8621. }
  8622. _patterns[ texture.id ] === undefined
  8623. ? setFillStyle( 'rgba(0,0,0,1)' )
  8624. : setFillStyle( _patterns[ texture.id ] );
  8625. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8626. var a, b, c, d, e, f, det, idet,
  8627. offsetX = texture.offset.x / texture.repeat.x,
  8628. offsetY = texture.offset.y / texture.repeat.y,
  8629. width = texture.image.width * texture.repeat.x,
  8630. height = texture.image.height * texture.repeat.y;
  8631. u0 = ( u0 + offsetX ) * width;
  8632. v0 = ( 1.0 - v0 + offsetY ) * height;
  8633. u1 = ( u1 + offsetX ) * width;
  8634. v1 = ( 1.0 - v1 + offsetY ) * height;
  8635. u2 = ( u2 + offsetX ) * width;
  8636. v2 = ( 1.0 - v2 + offsetY ) * height;
  8637. x1 -= x0; y1 -= y0;
  8638. x2 -= x0; y2 -= y0;
  8639. u1 -= u0; v1 -= v0;
  8640. u2 -= u0; v2 -= v0;
  8641. det = u1 * v2 - u2 * v1;
  8642. if ( det === 0 ) {
  8643. if ( _imagedatas[ texture.id ] === undefined ) {
  8644. var canvas = document.createElement( 'canvas' )
  8645. canvas.width = texture.image.width;
  8646. canvas.height = texture.image.height;
  8647. var context = canvas.getContext( '2d' );
  8648. context.drawImage( texture.image, 0, 0 );
  8649. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8650. }
  8651. var data = _imagedatas[ texture.id ];
  8652. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8653. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8654. fillPath( _color );
  8655. return;
  8656. }
  8657. idet = 1 / det;
  8658. a = ( v2 * x1 - v1 * x2 ) * idet;
  8659. b = ( v2 * y1 - v1 * y2 ) * idet;
  8660. c = ( u1 * x2 - u2 * x1 ) * idet;
  8661. d = ( u1 * y2 - u2 * y1 ) * idet;
  8662. e = x0 - a * u0 - c * v0;
  8663. f = y0 - b * u0 - d * v0;
  8664. _context.save();
  8665. _context.transform( a, b, c, d, e, f );
  8666. _context.fill();
  8667. _context.restore();
  8668. }
  8669. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8670. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8671. var a, b, c, d, e, f, det, idet,
  8672. width = image.width - 1,
  8673. height = image.height - 1;
  8674. u0 *= width; v0 *= height;
  8675. u1 *= width; v1 *= height;
  8676. u2 *= width; v2 *= height;
  8677. x1 -= x0; y1 -= y0;
  8678. x2 -= x0; y2 -= y0;
  8679. u1 -= u0; v1 -= v0;
  8680. u2 -= u0; v2 -= v0;
  8681. det = u1 * v2 - u2 * v1;
  8682. idet = 1 / det;
  8683. a = ( v2 * x1 - v1 * x2 ) * idet;
  8684. b = ( v2 * y1 - v1 * y2 ) * idet;
  8685. c = ( u1 * x2 - u2 * x1 ) * idet;
  8686. d = ( u1 * y2 - u2 * y1 ) * idet;
  8687. e = x0 - a * u0 - c * v0;
  8688. f = y0 - b * u0 - d * v0;
  8689. _context.save();
  8690. _context.transform( a, b, c, d, e, f );
  8691. _context.clip();
  8692. _context.drawImage( image, 0, 0 );
  8693. _context.restore();
  8694. }
  8695. function getGradientTexture( color1, color2, color3, color4 ) {
  8696. // http://mrdoob.com/blog/post/710
  8697. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8698. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8699. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8700. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8701. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8702. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8703. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8704. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8705. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8706. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8707. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8708. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8709. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8710. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8711. return _gradientMap;
  8712. }
  8713. // Hide anti-alias gaps
  8714. function expand( v1, v2 ) {
  8715. var x = v2.x - v1.x, y = v2.y - v1.y,
  8716. det = x * x + y * y, idet;
  8717. if ( det === 0 ) return;
  8718. idet = 1 / Math.sqrt( det );
  8719. x *= idet; y *= idet;
  8720. v2.x += x; v2.y += y;
  8721. v1.x -= x; v1.y -= y;
  8722. }
  8723. };
  8724. // Context cached methods.
  8725. function setOpacity( value ) {
  8726. if ( _contextGlobalAlpha !== value ) {
  8727. _context.globalAlpha = value;
  8728. _contextGlobalAlpha = value;
  8729. }
  8730. }
  8731. function setBlending( value ) {
  8732. if ( _contextGlobalCompositeOperation !== value ) {
  8733. if ( value === THREE.NormalBlending ) {
  8734. _context.globalCompositeOperation = 'source-over';
  8735. } else if ( value === THREE.AdditiveBlending ) {
  8736. _context.globalCompositeOperation = 'lighter';
  8737. } else if ( value === THREE.SubtractiveBlending ) {
  8738. _context.globalCompositeOperation = 'darker';
  8739. }
  8740. _contextGlobalCompositeOperation = value;
  8741. }
  8742. }
  8743. function setLineWidth( value ) {
  8744. if ( _contextLineWidth !== value ) {
  8745. _context.lineWidth = value;
  8746. _contextLineWidth = value;
  8747. }
  8748. }
  8749. function setLineCap( value ) {
  8750. // "butt", "round", "square"
  8751. if ( _contextLineCap !== value ) {
  8752. _context.lineCap = value;
  8753. _contextLineCap = value;
  8754. }
  8755. }
  8756. function setLineJoin( value ) {
  8757. // "round", "bevel", "miter"
  8758. if ( _contextLineJoin !== value ) {
  8759. _context.lineJoin = value;
  8760. _contextLineJoin = value;
  8761. }
  8762. }
  8763. function setStrokeStyle( value ) {
  8764. if ( _contextStrokeStyle !== value ) {
  8765. _context.strokeStyle = value;
  8766. _contextStrokeStyle = value;
  8767. }
  8768. }
  8769. function setFillStyle( value ) {
  8770. if ( _contextFillStyle !== value ) {
  8771. _context.fillStyle = value;
  8772. _contextFillStyle = value;
  8773. }
  8774. }
  8775. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8776. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8777. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8778. _contextDashSize = dashSizeValue;
  8779. _contextGapSize = gapSizeValue;
  8780. }
  8781. }
  8782. };
  8783. /**
  8784. * @author alteredq / http://alteredqualia.com/
  8785. * @author mrdoob / http://mrdoob.com/
  8786. * @author mikael emtinger / http://gomo.se/
  8787. */
  8788. THREE.ShaderChunk = {
  8789. // FOG
  8790. fog_pars_fragment: [
  8791. "#ifdef USE_FOG",
  8792. "uniform vec3 fogColor;",
  8793. "#ifdef FOG_EXP2",
  8794. "uniform float fogDensity;",
  8795. "#else",
  8796. "uniform float fogNear;",
  8797. "uniform float fogFar;",
  8798. "#endif",
  8799. "#endif"
  8800. ].join("\n"),
  8801. fog_fragment: [
  8802. "#ifdef USE_FOG",
  8803. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8804. "#ifdef FOG_EXP2",
  8805. "const float LOG2 = 1.442695;",
  8806. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8807. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8808. "#else",
  8809. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8810. "#endif",
  8811. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8812. "#endif"
  8813. ].join("\n"),
  8814. // ENVIRONMENT MAP
  8815. envmap_pars_fragment: [
  8816. "#ifdef USE_ENVMAP",
  8817. "uniform float reflectivity;",
  8818. "uniform samplerCube envMap;",
  8819. "uniform float flipEnvMap;",
  8820. "uniform int combine;",
  8821. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8822. "uniform bool useRefract;",
  8823. "uniform float refractionRatio;",
  8824. "#else",
  8825. "varying vec3 vReflect;",
  8826. "#endif",
  8827. "#endif"
  8828. ].join("\n"),
  8829. envmap_fragment: [
  8830. "#ifdef USE_ENVMAP",
  8831. "vec3 reflectVec;",
  8832. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8833. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8834. "if ( useRefract ) {",
  8835. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8836. "} else { ",
  8837. "reflectVec = reflect( cameraToVertex, normal );",
  8838. "}",
  8839. "#else",
  8840. "reflectVec = vReflect;",
  8841. "#endif",
  8842. "#ifdef DOUBLE_SIDED",
  8843. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8844. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8845. "#else",
  8846. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8847. "#endif",
  8848. "#ifdef GAMMA_INPUT",
  8849. "cubeColor.xyz *= cubeColor.xyz;",
  8850. "#endif",
  8851. "if ( combine == 1 ) {",
  8852. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8853. "} else if ( combine == 2 ) {",
  8854. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8855. "} else {",
  8856. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8857. "}",
  8858. "#endif"
  8859. ].join("\n"),
  8860. envmap_pars_vertex: [
  8861. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8862. "varying vec3 vReflect;",
  8863. "uniform float refractionRatio;",
  8864. "uniform bool useRefract;",
  8865. "#endif"
  8866. ].join("\n"),
  8867. worldpos_vertex : [
  8868. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8869. "#ifdef USE_SKINNING",
  8870. "vec4 worldPosition = modelMatrix * skinned;",
  8871. "#endif",
  8872. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8873. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8874. "#endif",
  8875. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8876. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8877. "#endif",
  8878. "#endif"
  8879. ].join("\n"),
  8880. envmap_vertex : [
  8881. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8882. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8883. "worldNormal = normalize( worldNormal );",
  8884. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8885. "if ( useRefract ) {",
  8886. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8887. "} else {",
  8888. "vReflect = reflect( cameraToVertex, worldNormal );",
  8889. "}",
  8890. "#endif"
  8891. ].join("\n"),
  8892. // COLOR MAP (particles)
  8893. map_particle_pars_fragment: [
  8894. "#ifdef USE_MAP",
  8895. "uniform sampler2D map;",
  8896. "#endif"
  8897. ].join("\n"),
  8898. map_particle_fragment: [
  8899. "#ifdef USE_MAP",
  8900. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8901. "#endif"
  8902. ].join("\n"),
  8903. // COLOR MAP (triangles)
  8904. map_pars_vertex: [
  8905. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8906. "varying vec2 vUv;",
  8907. "uniform vec4 offsetRepeat;",
  8908. "#endif"
  8909. ].join("\n"),
  8910. map_pars_fragment: [
  8911. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8912. "varying vec2 vUv;",
  8913. "#endif",
  8914. "#ifdef USE_MAP",
  8915. "uniform sampler2D map;",
  8916. "#endif"
  8917. ].join("\n"),
  8918. map_vertex: [
  8919. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8920. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8921. "#endif"
  8922. ].join("\n"),
  8923. map_fragment: [
  8924. "#ifdef USE_MAP",
  8925. "vec4 texelColor = texture2D( map, vUv );",
  8926. "#ifdef GAMMA_INPUT",
  8927. "texelColor.xyz *= texelColor.xyz;",
  8928. "#endif",
  8929. "gl_FragColor = gl_FragColor * texelColor;",
  8930. "#endif"
  8931. ].join("\n"),
  8932. // LIGHT MAP
  8933. lightmap_pars_fragment: [
  8934. "#ifdef USE_LIGHTMAP",
  8935. "varying vec2 vUv2;",
  8936. "uniform sampler2D lightMap;",
  8937. "#endif"
  8938. ].join("\n"),
  8939. lightmap_pars_vertex: [
  8940. "#ifdef USE_LIGHTMAP",
  8941. "varying vec2 vUv2;",
  8942. "#endif"
  8943. ].join("\n"),
  8944. lightmap_fragment: [
  8945. "#ifdef USE_LIGHTMAP",
  8946. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8947. "#endif"
  8948. ].join("\n"),
  8949. lightmap_vertex: [
  8950. "#ifdef USE_LIGHTMAP",
  8951. "vUv2 = uv2;",
  8952. "#endif"
  8953. ].join("\n"),
  8954. // BUMP MAP
  8955. bumpmap_pars_fragment: [
  8956. "#ifdef USE_BUMPMAP",
  8957. "uniform sampler2D bumpMap;",
  8958. "uniform float bumpScale;",
  8959. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8960. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8961. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8962. "vec2 dHdxy_fwd() {",
  8963. "vec2 dSTdx = dFdx( vUv );",
  8964. "vec2 dSTdy = dFdy( vUv );",
  8965. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8966. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8967. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8968. "return vec2( dBx, dBy );",
  8969. "}",
  8970. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8971. "vec3 vSigmaX = dFdx( surf_pos );",
  8972. "vec3 vSigmaY = dFdy( surf_pos );",
  8973. "vec3 vN = surf_norm;", // normalized
  8974. "vec3 R1 = cross( vSigmaY, vN );",
  8975. "vec3 R2 = cross( vN, vSigmaX );",
  8976. "float fDet = dot( vSigmaX, R1 );",
  8977. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8978. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8979. "}",
  8980. "#endif"
  8981. ].join("\n"),
  8982. // NORMAL MAP
  8983. normalmap_pars_fragment: [
  8984. "#ifdef USE_NORMALMAP",
  8985. "uniform sampler2D normalMap;",
  8986. "uniform vec2 normalScale;",
  8987. // Per-Pixel Tangent Space Normal Mapping
  8988. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8989. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8990. "vec3 q0 = dFdx( eye_pos.xyz );",
  8991. "vec3 q1 = dFdy( eye_pos.xyz );",
  8992. "vec2 st0 = dFdx( vUv.st );",
  8993. "vec2 st1 = dFdy( vUv.st );",
  8994. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8995. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8996. "vec3 N = normalize( surf_norm );",
  8997. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8998. "mapN.xy = normalScale * mapN.xy;",
  8999. "mat3 tsn = mat3( S, T, N );",
  9000. "return normalize( tsn * mapN );",
  9001. "}",
  9002. "#endif"
  9003. ].join("\n"),
  9004. // SPECULAR MAP
  9005. specularmap_pars_fragment: [
  9006. "#ifdef USE_SPECULARMAP",
  9007. "uniform sampler2D specularMap;",
  9008. "#endif"
  9009. ].join("\n"),
  9010. specularmap_fragment: [
  9011. "float specularStrength;",
  9012. "#ifdef USE_SPECULARMAP",
  9013. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9014. "specularStrength = texelSpecular.r;",
  9015. "#else",
  9016. "specularStrength = 1.0;",
  9017. "#endif"
  9018. ].join("\n"),
  9019. // LIGHTS LAMBERT
  9020. lights_lambert_pars_vertex: [
  9021. "uniform vec3 ambient;",
  9022. "uniform vec3 diffuse;",
  9023. "uniform vec3 emissive;",
  9024. "uniform vec3 ambientLightColor;",
  9025. "#if MAX_DIR_LIGHTS > 0",
  9026. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9027. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9028. "#endif",
  9029. "#if MAX_HEMI_LIGHTS > 0",
  9030. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9031. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9032. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9033. "#endif",
  9034. "#if MAX_POINT_LIGHTS > 0",
  9035. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9036. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9037. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9038. "#endif",
  9039. "#if MAX_SPOT_LIGHTS > 0",
  9040. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9041. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9042. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9043. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9044. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9045. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9046. "#endif",
  9047. "#ifdef WRAP_AROUND",
  9048. "uniform vec3 wrapRGB;",
  9049. "#endif"
  9050. ].join("\n"),
  9051. lights_lambert_vertex: [
  9052. "vLightFront = vec3( 0.0 );",
  9053. "#ifdef DOUBLE_SIDED",
  9054. "vLightBack = vec3( 0.0 );",
  9055. "#endif",
  9056. "transformedNormal = normalize( transformedNormal );",
  9057. "#if MAX_DIR_LIGHTS > 0",
  9058. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9059. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9060. "vec3 dirVector = normalize( lDirection.xyz );",
  9061. "float dotProduct = dot( transformedNormal, dirVector );",
  9062. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9063. "#ifdef DOUBLE_SIDED",
  9064. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9065. "#ifdef WRAP_AROUND",
  9066. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9067. "#endif",
  9068. "#endif",
  9069. "#ifdef WRAP_AROUND",
  9070. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9071. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9072. "#ifdef DOUBLE_SIDED",
  9073. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9074. "#endif",
  9075. "#endif",
  9076. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9077. "#ifdef DOUBLE_SIDED",
  9078. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9079. "#endif",
  9080. "}",
  9081. "#endif",
  9082. "#if MAX_POINT_LIGHTS > 0",
  9083. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9084. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9085. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9086. "float lDistance = 1.0;",
  9087. "if ( pointLightDistance[ i ] > 0.0 )",
  9088. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9089. "lVector = normalize( lVector );",
  9090. "float dotProduct = dot( transformedNormal, lVector );",
  9091. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9092. "#ifdef DOUBLE_SIDED",
  9093. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9094. "#ifdef WRAP_AROUND",
  9095. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9096. "#endif",
  9097. "#endif",
  9098. "#ifdef WRAP_AROUND",
  9099. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9100. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9101. "#ifdef DOUBLE_SIDED",
  9102. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9103. "#endif",
  9104. "#endif",
  9105. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9106. "#ifdef DOUBLE_SIDED",
  9107. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9108. "#endif",
  9109. "}",
  9110. "#endif",
  9111. "#if MAX_SPOT_LIGHTS > 0",
  9112. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9113. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9114. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9115. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9116. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9117. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9118. "float lDistance = 1.0;",
  9119. "if ( spotLightDistance[ i ] > 0.0 )",
  9120. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9121. "lVector = normalize( lVector );",
  9122. "float dotProduct = dot( transformedNormal, lVector );",
  9123. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9124. "#ifdef DOUBLE_SIDED",
  9125. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9126. "#ifdef WRAP_AROUND",
  9127. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9128. "#endif",
  9129. "#endif",
  9130. "#ifdef WRAP_AROUND",
  9131. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9132. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9133. "#ifdef DOUBLE_SIDED",
  9134. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9135. "#endif",
  9136. "#endif",
  9137. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9138. "#ifdef DOUBLE_SIDED",
  9139. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9140. "#endif",
  9141. "}",
  9142. "}",
  9143. "#endif",
  9144. "#if MAX_HEMI_LIGHTS > 0",
  9145. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9146. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9147. "vec3 lVector = normalize( lDirection.xyz );",
  9148. "float dotProduct = dot( transformedNormal, lVector );",
  9149. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9150. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9151. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9152. "#ifdef DOUBLE_SIDED",
  9153. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9154. "#endif",
  9155. "}",
  9156. "#endif",
  9157. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9158. "#ifdef DOUBLE_SIDED",
  9159. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9160. "#endif"
  9161. ].join("\n"),
  9162. // LIGHTS PHONG
  9163. lights_phong_pars_vertex: [
  9164. "#ifndef PHONG_PER_PIXEL",
  9165. "#if MAX_POINT_LIGHTS > 0",
  9166. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9167. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9168. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9169. "#endif",
  9170. "#if MAX_SPOT_LIGHTS > 0",
  9171. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9172. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9173. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9174. "#endif",
  9175. "#endif",
  9176. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9177. "varying vec3 vWorldPosition;",
  9178. "#endif"
  9179. ].join("\n"),
  9180. lights_phong_vertex: [
  9181. "#ifndef PHONG_PER_PIXEL",
  9182. "#if MAX_POINT_LIGHTS > 0",
  9183. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9184. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9185. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9186. "float lDistance = 1.0;",
  9187. "if ( pointLightDistance[ i ] > 0.0 )",
  9188. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9189. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9190. "}",
  9191. "#endif",
  9192. "#if MAX_SPOT_LIGHTS > 0",
  9193. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9194. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9195. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9196. "float lDistance = 1.0;",
  9197. "if ( spotLightDistance[ i ] > 0.0 )",
  9198. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9199. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9200. "}",
  9201. "#endif",
  9202. "#endif",
  9203. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9204. "vWorldPosition = worldPosition.xyz;",
  9205. "#endif"
  9206. ].join("\n"),
  9207. lights_phong_pars_fragment: [
  9208. "uniform vec3 ambientLightColor;",
  9209. "#if MAX_DIR_LIGHTS > 0",
  9210. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9211. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9212. "#endif",
  9213. "#if MAX_HEMI_LIGHTS > 0",
  9214. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9215. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9216. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9217. "#endif",
  9218. "#if MAX_POINT_LIGHTS > 0",
  9219. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9220. "#ifdef PHONG_PER_PIXEL",
  9221. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9222. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9223. "#else",
  9224. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9225. "#endif",
  9226. "#endif",
  9227. "#if MAX_SPOT_LIGHTS > 0",
  9228. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9229. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9230. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9231. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9232. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9233. "#ifdef PHONG_PER_PIXEL",
  9234. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9235. "#else",
  9236. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9237. "#endif",
  9238. "#endif",
  9239. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9240. "varying vec3 vWorldPosition;",
  9241. "#endif",
  9242. "#ifdef WRAP_AROUND",
  9243. "uniform vec3 wrapRGB;",
  9244. "#endif",
  9245. "varying vec3 vViewPosition;",
  9246. "varying vec3 vNormal;"
  9247. ].join("\n"),
  9248. lights_phong_fragment: [
  9249. "vec3 normal = normalize( vNormal );",
  9250. "vec3 viewPosition = normalize( vViewPosition );",
  9251. "#ifdef DOUBLE_SIDED",
  9252. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9253. "#endif",
  9254. "#ifdef USE_NORMALMAP",
  9255. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9256. "#elif defined( USE_BUMPMAP )",
  9257. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9258. "#endif",
  9259. "#if MAX_POINT_LIGHTS > 0",
  9260. "vec3 pointDiffuse = vec3( 0.0 );",
  9261. "vec3 pointSpecular = vec3( 0.0 );",
  9262. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9263. "#ifdef PHONG_PER_PIXEL",
  9264. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9265. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9266. "float lDistance = 1.0;",
  9267. "if ( pointLightDistance[ i ] > 0.0 )",
  9268. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9269. "lVector = normalize( lVector );",
  9270. "#else",
  9271. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9272. "float lDistance = vPointLight[ i ].w;",
  9273. "#endif",
  9274. // diffuse
  9275. "float dotProduct = dot( normal, lVector );",
  9276. "#ifdef WRAP_AROUND",
  9277. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9278. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9279. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9280. "#else",
  9281. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9282. "#endif",
  9283. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9284. // specular
  9285. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9286. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9287. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9288. "#ifdef PHYSICALLY_BASED_SHADING",
  9289. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9290. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9291. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9292. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9293. "#else",
  9294. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9295. "#endif",
  9296. "}",
  9297. "#endif",
  9298. "#if MAX_SPOT_LIGHTS > 0",
  9299. "vec3 spotDiffuse = vec3( 0.0 );",
  9300. "vec3 spotSpecular = vec3( 0.0 );",
  9301. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9302. "#ifdef PHONG_PER_PIXEL",
  9303. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9304. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9305. "float lDistance = 1.0;",
  9306. "if ( spotLightDistance[ i ] > 0.0 )",
  9307. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9308. "lVector = normalize( lVector );",
  9309. "#else",
  9310. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9311. "float lDistance = vSpotLight[ i ].w;",
  9312. "#endif",
  9313. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9314. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9315. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9316. // diffuse
  9317. "float dotProduct = dot( normal, lVector );",
  9318. "#ifdef WRAP_AROUND",
  9319. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9320. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9321. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9322. "#else",
  9323. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9324. "#endif",
  9325. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9326. // specular
  9327. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9328. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9329. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9330. "#ifdef PHYSICALLY_BASED_SHADING",
  9331. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9332. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9333. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9334. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9335. "#else",
  9336. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9337. "#endif",
  9338. "}",
  9339. "}",
  9340. "#endif",
  9341. "#if MAX_DIR_LIGHTS > 0",
  9342. "vec3 dirDiffuse = vec3( 0.0 );",
  9343. "vec3 dirSpecular = vec3( 0.0 );" ,
  9344. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9345. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9346. "vec3 dirVector = normalize( lDirection.xyz );",
  9347. // diffuse
  9348. "float dotProduct = dot( normal, dirVector );",
  9349. "#ifdef WRAP_AROUND",
  9350. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9351. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9352. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9353. "#else",
  9354. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9355. "#endif",
  9356. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9357. // specular
  9358. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9359. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9360. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9361. "#ifdef PHYSICALLY_BASED_SHADING",
  9362. /*
  9363. // fresnel term from skin shader
  9364. "const float F0 = 0.128;",
  9365. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9366. "float exponential = pow( base, 5.0 );",
  9367. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9368. */
  9369. /*
  9370. // fresnel term from fresnel shader
  9371. "const float mFresnelBias = 0.08;",
  9372. "const float mFresnelScale = 0.3;",
  9373. "const float mFresnelPower = 5.0;",
  9374. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9375. */
  9376. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9377. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9378. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9379. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9380. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9381. "#else",
  9382. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9383. "#endif",
  9384. "}",
  9385. "#endif",
  9386. "#if MAX_HEMI_LIGHTS > 0",
  9387. "vec3 hemiDiffuse = vec3( 0.0 );",
  9388. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9389. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9390. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9391. "vec3 lVector = normalize( lDirection.xyz );",
  9392. // diffuse
  9393. "float dotProduct = dot( normal, lVector );",
  9394. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9395. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9396. "hemiDiffuse += diffuse * hemiColor;",
  9397. // specular (sky light)
  9398. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9399. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9400. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9401. // specular (ground light)
  9402. "vec3 lVectorGround = -lVector;",
  9403. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9404. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9405. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9406. "#ifdef PHYSICALLY_BASED_SHADING",
  9407. "float dotProductGround = dot( normal, lVectorGround );",
  9408. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9409. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9410. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9411. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9412. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9413. "#else",
  9414. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9415. "#endif",
  9416. "}",
  9417. "#endif",
  9418. "vec3 totalDiffuse = vec3( 0.0 );",
  9419. "vec3 totalSpecular = vec3( 0.0 );",
  9420. "#if MAX_DIR_LIGHTS > 0",
  9421. "totalDiffuse += dirDiffuse;",
  9422. "totalSpecular += dirSpecular;",
  9423. "#endif",
  9424. "#if MAX_HEMI_LIGHTS > 0",
  9425. "totalDiffuse += hemiDiffuse;",
  9426. "totalSpecular += hemiSpecular;",
  9427. "#endif",
  9428. "#if MAX_POINT_LIGHTS > 0",
  9429. "totalDiffuse += pointDiffuse;",
  9430. "totalSpecular += pointSpecular;",
  9431. "#endif",
  9432. "#if MAX_SPOT_LIGHTS > 0",
  9433. "totalDiffuse += spotDiffuse;",
  9434. "totalSpecular += spotSpecular;",
  9435. "#endif",
  9436. "#ifdef METAL",
  9437. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9438. "#else",
  9439. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9440. "#endif"
  9441. ].join("\n"),
  9442. // VERTEX COLORS
  9443. color_pars_fragment: [
  9444. "#ifdef USE_COLOR",
  9445. "varying vec3 vColor;",
  9446. "#endif"
  9447. ].join("\n"),
  9448. color_fragment: [
  9449. "#ifdef USE_COLOR",
  9450. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9451. "#endif"
  9452. ].join("\n"),
  9453. color_pars_vertex: [
  9454. "#ifdef USE_COLOR",
  9455. "varying vec3 vColor;",
  9456. "#endif"
  9457. ].join("\n"),
  9458. color_vertex: [
  9459. "#ifdef USE_COLOR",
  9460. "#ifdef GAMMA_INPUT",
  9461. "vColor = color * color;",
  9462. "#else",
  9463. "vColor = color;",
  9464. "#endif",
  9465. "#endif"
  9466. ].join("\n"),
  9467. // SKINNING
  9468. skinning_pars_vertex: [
  9469. "#ifdef USE_SKINNING",
  9470. "#ifdef BONE_TEXTURE",
  9471. "uniform sampler2D boneTexture;",
  9472. "mat4 getBoneMatrix( const in float i ) {",
  9473. "float j = i * 4.0;",
  9474. "float x = mod( j, N_BONE_PIXEL_X );",
  9475. "float y = floor( j / N_BONE_PIXEL_X );",
  9476. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9477. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9478. "y = dy * ( y + 0.5 );",
  9479. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9480. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9481. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9482. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9483. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9484. "return bone;",
  9485. "}",
  9486. "#else",
  9487. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9488. "mat4 getBoneMatrix( const in float i ) {",
  9489. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9490. "return bone;",
  9491. "}",
  9492. "#endif",
  9493. "#endif"
  9494. ].join("\n"),
  9495. skinbase_vertex: [
  9496. "#ifdef USE_SKINNING",
  9497. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9498. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9499. "#endif"
  9500. ].join("\n"),
  9501. skinning_vertex: [
  9502. "#ifdef USE_SKINNING",
  9503. "#ifdef USE_MORPHTARGETS",
  9504. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9505. "#else",
  9506. "vec4 skinVertex = vec4( position, 1.0 );",
  9507. "#endif",
  9508. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9509. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9510. "#endif"
  9511. ].join("\n"),
  9512. // MORPHING
  9513. morphtarget_pars_vertex: [
  9514. "#ifdef USE_MORPHTARGETS",
  9515. "#ifndef USE_MORPHNORMALS",
  9516. "uniform float morphTargetInfluences[ 8 ];",
  9517. "#else",
  9518. "uniform float morphTargetInfluences[ 4 ];",
  9519. "#endif",
  9520. "#endif"
  9521. ].join("\n"),
  9522. morphtarget_vertex: [
  9523. "#ifdef USE_MORPHTARGETS",
  9524. "vec3 morphed = vec3( 0.0 );",
  9525. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9526. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9527. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9528. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9529. "#ifndef USE_MORPHNORMALS",
  9530. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9531. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9532. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9533. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9534. "#endif",
  9535. "morphed += position;",
  9536. "#endif"
  9537. ].join("\n"),
  9538. default_vertex : [
  9539. "vec4 mvPosition;",
  9540. "#ifdef USE_SKINNING",
  9541. "mvPosition = modelViewMatrix * skinned;",
  9542. "#endif",
  9543. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9544. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9545. "#endif",
  9546. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9547. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9548. "#endif",
  9549. "gl_Position = projectionMatrix * mvPosition;"
  9550. ].join("\n"),
  9551. morphnormal_vertex: [
  9552. "#ifdef USE_MORPHNORMALS",
  9553. "vec3 morphedNormal = vec3( 0.0 );",
  9554. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9555. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9556. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9557. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9558. "morphedNormal += normal;",
  9559. "#endif"
  9560. ].join("\n"),
  9561. skinnormal_vertex: [
  9562. "#ifdef USE_SKINNING",
  9563. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9564. "skinMatrix += skinWeight.y * boneMatY;",
  9565. "#ifdef USE_MORPHNORMALS",
  9566. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9567. "#else",
  9568. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9569. "#endif",
  9570. "#endif"
  9571. ].join("\n"),
  9572. defaultnormal_vertex: [
  9573. "vec3 objectNormal;",
  9574. "#ifdef USE_SKINNING",
  9575. "objectNormal = skinnedNormal.xyz;",
  9576. "#endif",
  9577. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9578. "objectNormal = morphedNormal;",
  9579. "#endif",
  9580. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9581. "objectNormal = normal;",
  9582. "#endif",
  9583. "#ifdef FLIP_SIDED",
  9584. "objectNormal = -objectNormal;",
  9585. "#endif",
  9586. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9587. ].join("\n"),
  9588. // SHADOW MAP
  9589. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9590. // http://spidergl.org/example.php?id=6
  9591. // http://fabiensanglard.net/shadowmapping
  9592. shadowmap_pars_fragment: [
  9593. "#ifdef USE_SHADOWMAP",
  9594. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9595. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9596. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9597. "uniform float shadowBias[ MAX_SHADOWS ];",
  9598. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9599. "float unpackDepth( const in vec4 rgba_depth ) {",
  9600. "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 );",
  9601. "float depth = dot( rgba_depth, bit_shift );",
  9602. "return depth;",
  9603. "}",
  9604. "#endif"
  9605. ].join("\n"),
  9606. shadowmap_fragment: [
  9607. "#ifdef USE_SHADOWMAP",
  9608. "#ifdef SHADOWMAP_DEBUG",
  9609. "vec3 frustumColors[3];",
  9610. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9611. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9612. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9613. "#endif",
  9614. "#ifdef SHADOWMAP_CASCADE",
  9615. "int inFrustumCount = 0;",
  9616. "#endif",
  9617. "float fDepth;",
  9618. "vec3 shadowColor = vec3( 1.0 );",
  9619. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9620. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9621. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9622. // "if ( all( something, something ) )" using this instead
  9623. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9624. "bool inFrustum = all( inFrustumVec );",
  9625. // don't shadow pixels outside of light frustum
  9626. // use just first frustum (for cascades)
  9627. // don't shadow pixels behind far plane of light frustum
  9628. "#ifdef SHADOWMAP_CASCADE",
  9629. "inFrustumCount += int( inFrustum );",
  9630. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9631. "#else",
  9632. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9633. "#endif",
  9634. "bool frustumTest = all( frustumTestVec );",
  9635. "if ( frustumTest ) {",
  9636. "shadowCoord.z += shadowBias[ i ];",
  9637. "#if defined( SHADOWMAP_TYPE_PCF )",
  9638. // Percentage-close filtering
  9639. // (9 pixel kernel)
  9640. // http://fabiensanglard.net/shadowmappingPCF/
  9641. "float shadow = 0.0;",
  9642. /*
  9643. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9644. // must enroll loop manually
  9645. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9646. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9647. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9648. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9649. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9650. "float fDepth = unpackDepth( rgbaDepth );",
  9651. "if ( fDepth < shadowCoord.z )",
  9652. "shadow += 1.0;",
  9653. "}",
  9654. "shadow /= 9.0;",
  9655. */
  9656. "const float shadowDelta = 1.0 / 9.0;",
  9657. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9658. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9659. "float dx0 = -1.25 * xPixelOffset;",
  9660. "float dy0 = -1.25 * yPixelOffset;",
  9661. "float dx1 = 1.25 * xPixelOffset;",
  9662. "float dy1 = 1.25 * yPixelOffset;",
  9663. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9664. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9665. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9666. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9667. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9668. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9669. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9670. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9671. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9672. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9673. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9674. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9675. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9676. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9677. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9678. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9679. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9680. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9681. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9682. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9683. // Percentage-close filtering
  9684. // (9 pixel kernel)
  9685. // http://fabiensanglard.net/shadowmappingPCF/
  9686. "float shadow = 0.0;",
  9687. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9688. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9689. "float dx0 = -1.0 * xPixelOffset;",
  9690. "float dy0 = -1.0 * yPixelOffset;",
  9691. "float dx1 = 1.0 * xPixelOffset;",
  9692. "float dy1 = 1.0 * yPixelOffset;",
  9693. "mat3 shadowKernel;",
  9694. "mat3 depthKernel;",
  9695. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9696. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9697. "else shadowKernel[0][0] = 0.0;",
  9698. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9699. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9700. "else shadowKernel[0][1] = 0.0;",
  9701. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9702. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9703. "else shadowKernel[0][2] = 0.0;",
  9704. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9705. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9706. "else shadowKernel[1][0] = 0.0;",
  9707. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9708. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9709. "else shadowKernel[1][1] = 0.0;",
  9710. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9711. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9712. "else shadowKernel[1][2] = 0.0;",
  9713. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9714. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9715. "else shadowKernel[2][0] = 0.0;",
  9716. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9717. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9718. "else shadowKernel[2][1] = 0.0;",
  9719. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9720. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9721. "else shadowKernel[2][2] = 0.0;",
  9722. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9723. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9724. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9725. "vec4 shadowValues;",
  9726. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9727. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9728. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9729. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9730. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9731. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9732. "#else",
  9733. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9734. "float fDepth = unpackDepth( rgbaDepth );",
  9735. "if ( fDepth < shadowCoord.z )",
  9736. // spot with multiple shadows is darker
  9737. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9738. // spot with multiple shadows has the same color as single shadow spot
  9739. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9740. "#endif",
  9741. "}",
  9742. "#ifdef SHADOWMAP_DEBUG",
  9743. "#ifdef SHADOWMAP_CASCADE",
  9744. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9745. "#else",
  9746. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9747. "#endif",
  9748. "#endif",
  9749. "}",
  9750. "#ifdef GAMMA_OUTPUT",
  9751. "shadowColor *= shadowColor;",
  9752. "#endif",
  9753. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9754. "#endif"
  9755. ].join("\n"),
  9756. shadowmap_pars_vertex: [
  9757. "#ifdef USE_SHADOWMAP",
  9758. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9759. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9760. "#endif"
  9761. ].join("\n"),
  9762. shadowmap_vertex: [
  9763. "#ifdef USE_SHADOWMAP",
  9764. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9765. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9766. "}",
  9767. "#endif"
  9768. ].join("\n"),
  9769. // ALPHATEST
  9770. alphatest_fragment: [
  9771. "#ifdef ALPHATEST",
  9772. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9773. "#endif"
  9774. ].join("\n"),
  9775. // LINEAR SPACE
  9776. linear_to_gamma_fragment: [
  9777. "#ifdef GAMMA_OUTPUT",
  9778. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9779. "#endif"
  9780. ].join("\n")
  9781. };
  9782. THREE.UniformsUtils = {
  9783. merge: function ( uniforms ) {
  9784. var u, p, tmp, merged = {};
  9785. for ( u = 0; u < uniforms.length; u ++ ) {
  9786. tmp = this.clone( uniforms[ u ] );
  9787. for ( p in tmp ) {
  9788. merged[ p ] = tmp[ p ];
  9789. }
  9790. }
  9791. return merged;
  9792. },
  9793. clone: function ( uniforms_src ) {
  9794. var u, p, parameter, parameter_src, uniforms_dst = {};
  9795. for ( u in uniforms_src ) {
  9796. uniforms_dst[ u ] = {};
  9797. for ( p in uniforms_src[ u ] ) {
  9798. parameter_src = uniforms_src[ u ][ p ];
  9799. if ( parameter_src instanceof THREE.Color ||
  9800. parameter_src instanceof THREE.Vector2 ||
  9801. parameter_src instanceof THREE.Vector3 ||
  9802. parameter_src instanceof THREE.Vector4 ||
  9803. parameter_src instanceof THREE.Matrix4 ||
  9804. parameter_src instanceof THREE.Texture ) {
  9805. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9806. } else if ( parameter_src instanceof Array ) {
  9807. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9808. } else {
  9809. uniforms_dst[ u ][ p ] = parameter_src;
  9810. }
  9811. }
  9812. }
  9813. return uniforms_dst;
  9814. }
  9815. };
  9816. THREE.UniformsLib = {
  9817. common: {
  9818. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9819. "opacity" : { type: "f", value: 1.0 },
  9820. "map" : { type: "t", value: null },
  9821. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9822. "lightMap" : { type: "t", value: null },
  9823. "specularMap" : { type: "t", value: null },
  9824. "envMap" : { type: "t", value: null },
  9825. "flipEnvMap" : { type: "f", value: -1 },
  9826. "useRefract" : { type: "i", value: 0 },
  9827. "reflectivity" : { type: "f", value: 1.0 },
  9828. "refractionRatio" : { type: "f", value: 0.98 },
  9829. "combine" : { type: "i", value: 0 },
  9830. "morphTargetInfluences" : { type: "f", value: 0 }
  9831. },
  9832. bump: {
  9833. "bumpMap" : { type: "t", value: null },
  9834. "bumpScale" : { type: "f", value: 1 }
  9835. },
  9836. normalmap: {
  9837. "normalMap" : { type: "t", value: null },
  9838. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9839. },
  9840. fog : {
  9841. "fogDensity" : { type: "f", value: 0.00025 },
  9842. "fogNear" : { type: "f", value: 1 },
  9843. "fogFar" : { type: "f", value: 2000 },
  9844. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9845. },
  9846. lights: {
  9847. "ambientLightColor" : { type: "fv", value: [] },
  9848. "directionalLightDirection" : { type: "fv", value: [] },
  9849. "directionalLightColor" : { type: "fv", value: [] },
  9850. "hemisphereLightDirection" : { type: "fv", value: [] },
  9851. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9852. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9853. "pointLightColor" : { type: "fv", value: [] },
  9854. "pointLightPosition" : { type: "fv", value: [] },
  9855. "pointLightDistance" : { type: "fv1", value: [] },
  9856. "spotLightColor" : { type: "fv", value: [] },
  9857. "spotLightPosition" : { type: "fv", value: [] },
  9858. "spotLightDirection" : { type: "fv", value: [] },
  9859. "spotLightDistance" : { type: "fv1", value: [] },
  9860. "spotLightAngleCos" : { type: "fv1", value: [] },
  9861. "spotLightExponent" : { type: "fv1", value: [] }
  9862. },
  9863. particle: {
  9864. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9865. "opacity" : { type: "f", value: 1.0 },
  9866. "size" : { type: "f", value: 1.0 },
  9867. "scale" : { type: "f", value: 1.0 },
  9868. "map" : { type: "t", value: null },
  9869. "fogDensity" : { type: "f", value: 0.00025 },
  9870. "fogNear" : { type: "f", value: 1 },
  9871. "fogFar" : { type: "f", value: 2000 },
  9872. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9873. },
  9874. shadowmap: {
  9875. "shadowMap": { type: "tv", value: [] },
  9876. "shadowMapSize": { type: "v2v", value: [] },
  9877. "shadowBias" : { type: "fv1", value: [] },
  9878. "shadowDarkness": { type: "fv1", value: [] },
  9879. "shadowMatrix" : { type: "m4v", value: [] }
  9880. }
  9881. };
  9882. THREE.ShaderLib = {
  9883. 'basic': {
  9884. uniforms: THREE.UniformsUtils.merge( [
  9885. THREE.UniformsLib[ "common" ],
  9886. THREE.UniformsLib[ "fog" ],
  9887. THREE.UniformsLib[ "shadowmap" ]
  9888. ] ),
  9889. vertexShader: [
  9890. THREE.ShaderChunk[ "map_pars_vertex" ],
  9891. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9892. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9893. THREE.ShaderChunk[ "color_pars_vertex" ],
  9894. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9895. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9896. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9897. "void main() {",
  9898. THREE.ShaderChunk[ "map_vertex" ],
  9899. THREE.ShaderChunk[ "lightmap_vertex" ],
  9900. THREE.ShaderChunk[ "color_vertex" ],
  9901. THREE.ShaderChunk[ "skinbase_vertex" ],
  9902. "#ifdef USE_ENVMAP",
  9903. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9904. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9905. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9906. "#endif",
  9907. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9908. THREE.ShaderChunk[ "skinning_vertex" ],
  9909. THREE.ShaderChunk[ "default_vertex" ],
  9910. THREE.ShaderChunk[ "worldpos_vertex" ],
  9911. THREE.ShaderChunk[ "envmap_vertex" ],
  9912. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9913. "}"
  9914. ].join("\n"),
  9915. fragmentShader: [
  9916. "uniform vec3 diffuse;",
  9917. "uniform float opacity;",
  9918. THREE.ShaderChunk[ "color_pars_fragment" ],
  9919. THREE.ShaderChunk[ "map_pars_fragment" ],
  9920. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9921. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9922. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9923. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9924. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9925. "void main() {",
  9926. "gl_FragColor = vec4( diffuse, opacity );",
  9927. THREE.ShaderChunk[ "map_fragment" ],
  9928. THREE.ShaderChunk[ "alphatest_fragment" ],
  9929. THREE.ShaderChunk[ "specularmap_fragment" ],
  9930. THREE.ShaderChunk[ "lightmap_fragment" ],
  9931. THREE.ShaderChunk[ "color_fragment" ],
  9932. THREE.ShaderChunk[ "envmap_fragment" ],
  9933. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9934. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9935. THREE.ShaderChunk[ "fog_fragment" ],
  9936. "}"
  9937. ].join("\n")
  9938. },
  9939. 'lambert': {
  9940. uniforms: THREE.UniformsUtils.merge( [
  9941. THREE.UniformsLib[ "common" ],
  9942. THREE.UniformsLib[ "fog" ],
  9943. THREE.UniformsLib[ "lights" ],
  9944. THREE.UniformsLib[ "shadowmap" ],
  9945. {
  9946. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9947. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9948. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9949. }
  9950. ] ),
  9951. vertexShader: [
  9952. "#define LAMBERT",
  9953. "varying vec3 vLightFront;",
  9954. "#ifdef DOUBLE_SIDED",
  9955. "varying vec3 vLightBack;",
  9956. "#endif",
  9957. THREE.ShaderChunk[ "map_pars_vertex" ],
  9958. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9959. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9960. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9961. THREE.ShaderChunk[ "color_pars_vertex" ],
  9962. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9963. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9964. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9965. "void main() {",
  9966. THREE.ShaderChunk[ "map_vertex" ],
  9967. THREE.ShaderChunk[ "lightmap_vertex" ],
  9968. THREE.ShaderChunk[ "color_vertex" ],
  9969. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9970. THREE.ShaderChunk[ "skinbase_vertex" ],
  9971. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9972. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9973. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9974. THREE.ShaderChunk[ "skinning_vertex" ],
  9975. THREE.ShaderChunk[ "default_vertex" ],
  9976. THREE.ShaderChunk[ "worldpos_vertex" ],
  9977. THREE.ShaderChunk[ "envmap_vertex" ],
  9978. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9979. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9980. "}"
  9981. ].join("\n"),
  9982. fragmentShader: [
  9983. "uniform float opacity;",
  9984. "varying vec3 vLightFront;",
  9985. "#ifdef DOUBLE_SIDED",
  9986. "varying vec3 vLightBack;",
  9987. "#endif",
  9988. THREE.ShaderChunk[ "color_pars_fragment" ],
  9989. THREE.ShaderChunk[ "map_pars_fragment" ],
  9990. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9991. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9992. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9993. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9994. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9995. "void main() {",
  9996. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9997. THREE.ShaderChunk[ "map_fragment" ],
  9998. THREE.ShaderChunk[ "alphatest_fragment" ],
  9999. THREE.ShaderChunk[ "specularmap_fragment" ],
  10000. "#ifdef DOUBLE_SIDED",
  10001. //"float isFront = float( gl_FrontFacing );",
  10002. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10003. "if ( gl_FrontFacing )",
  10004. "gl_FragColor.xyz *= vLightFront;",
  10005. "else",
  10006. "gl_FragColor.xyz *= vLightBack;",
  10007. "#else",
  10008. "gl_FragColor.xyz *= vLightFront;",
  10009. "#endif",
  10010. THREE.ShaderChunk[ "lightmap_fragment" ],
  10011. THREE.ShaderChunk[ "color_fragment" ],
  10012. THREE.ShaderChunk[ "envmap_fragment" ],
  10013. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10014. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10015. THREE.ShaderChunk[ "fog_fragment" ],
  10016. "}"
  10017. ].join("\n")
  10018. },
  10019. 'phong': {
  10020. uniforms: THREE.UniformsUtils.merge( [
  10021. THREE.UniformsLib[ "common" ],
  10022. THREE.UniformsLib[ "bump" ],
  10023. THREE.UniformsLib[ "normalmap" ],
  10024. THREE.UniformsLib[ "fog" ],
  10025. THREE.UniformsLib[ "lights" ],
  10026. THREE.UniformsLib[ "shadowmap" ],
  10027. {
  10028. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10029. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10030. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10031. "shininess": { type: "f", value: 30 },
  10032. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10033. }
  10034. ] ),
  10035. vertexShader: [
  10036. "#define PHONG",
  10037. "varying vec3 vViewPosition;",
  10038. "varying vec3 vNormal;",
  10039. THREE.ShaderChunk[ "map_pars_vertex" ],
  10040. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10041. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10042. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10043. THREE.ShaderChunk[ "color_pars_vertex" ],
  10044. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10045. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10046. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10047. "void main() {",
  10048. THREE.ShaderChunk[ "map_vertex" ],
  10049. THREE.ShaderChunk[ "lightmap_vertex" ],
  10050. THREE.ShaderChunk[ "color_vertex" ],
  10051. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10052. THREE.ShaderChunk[ "skinbase_vertex" ],
  10053. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10054. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10055. "vNormal = normalize( transformedNormal );",
  10056. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10057. THREE.ShaderChunk[ "skinning_vertex" ],
  10058. THREE.ShaderChunk[ "default_vertex" ],
  10059. "vViewPosition = -mvPosition.xyz;",
  10060. THREE.ShaderChunk[ "worldpos_vertex" ],
  10061. THREE.ShaderChunk[ "envmap_vertex" ],
  10062. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10063. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10064. "}"
  10065. ].join("\n"),
  10066. fragmentShader: [
  10067. "uniform vec3 diffuse;",
  10068. "uniform float opacity;",
  10069. "uniform vec3 ambient;",
  10070. "uniform vec3 emissive;",
  10071. "uniform vec3 specular;",
  10072. "uniform float shininess;",
  10073. THREE.ShaderChunk[ "color_pars_fragment" ],
  10074. THREE.ShaderChunk[ "map_pars_fragment" ],
  10075. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10076. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10077. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10078. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10079. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10080. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10081. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10082. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10083. "void main() {",
  10084. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10085. THREE.ShaderChunk[ "map_fragment" ],
  10086. THREE.ShaderChunk[ "alphatest_fragment" ],
  10087. THREE.ShaderChunk[ "specularmap_fragment" ],
  10088. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10089. THREE.ShaderChunk[ "lightmap_fragment" ],
  10090. THREE.ShaderChunk[ "color_fragment" ],
  10091. THREE.ShaderChunk[ "envmap_fragment" ],
  10092. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10093. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10094. THREE.ShaderChunk[ "fog_fragment" ],
  10095. "}"
  10096. ].join("\n")
  10097. },
  10098. 'particle_basic': {
  10099. uniforms: THREE.UniformsUtils.merge( [
  10100. THREE.UniformsLib[ "particle" ],
  10101. THREE.UniformsLib[ "shadowmap" ]
  10102. ] ),
  10103. vertexShader: [
  10104. "uniform float size;",
  10105. "uniform float scale;",
  10106. THREE.ShaderChunk[ "color_pars_vertex" ],
  10107. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10108. "void main() {",
  10109. THREE.ShaderChunk[ "color_vertex" ],
  10110. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10111. "#ifdef USE_SIZEATTENUATION",
  10112. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10113. "#else",
  10114. "gl_PointSize = size;",
  10115. "#endif",
  10116. "gl_Position = projectionMatrix * mvPosition;",
  10117. THREE.ShaderChunk[ "worldpos_vertex" ],
  10118. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10119. "}"
  10120. ].join("\n"),
  10121. fragmentShader: [
  10122. "uniform vec3 psColor;",
  10123. "uniform float opacity;",
  10124. THREE.ShaderChunk[ "color_pars_fragment" ],
  10125. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10126. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10127. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10128. "void main() {",
  10129. "gl_FragColor = vec4( psColor, opacity );",
  10130. THREE.ShaderChunk[ "map_particle_fragment" ],
  10131. THREE.ShaderChunk[ "alphatest_fragment" ],
  10132. THREE.ShaderChunk[ "color_fragment" ],
  10133. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10134. THREE.ShaderChunk[ "fog_fragment" ],
  10135. "}"
  10136. ].join("\n")
  10137. },
  10138. 'dashed': {
  10139. uniforms: THREE.UniformsUtils.merge( [
  10140. THREE.UniformsLib[ "common" ],
  10141. THREE.UniformsLib[ "fog" ],
  10142. {
  10143. "scale": { type: "f", value: 1 },
  10144. "dashSize": { type: "f", value: 1 },
  10145. "totalSize": { type: "f", value: 2 }
  10146. }
  10147. ] ),
  10148. vertexShader: [
  10149. "uniform float scale;",
  10150. "attribute float lineDistance;",
  10151. "varying float vLineDistance;",
  10152. THREE.ShaderChunk[ "color_pars_vertex" ],
  10153. "void main() {",
  10154. THREE.ShaderChunk[ "color_vertex" ],
  10155. "vLineDistance = scale * lineDistance;",
  10156. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10157. "gl_Position = projectionMatrix * mvPosition;",
  10158. "}"
  10159. ].join("\n"),
  10160. fragmentShader: [
  10161. "uniform vec3 diffuse;",
  10162. "uniform float opacity;",
  10163. "uniform float dashSize;",
  10164. "uniform float totalSize;",
  10165. "varying float vLineDistance;",
  10166. THREE.ShaderChunk[ "color_pars_fragment" ],
  10167. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10168. "void main() {",
  10169. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10170. "discard;",
  10171. "}",
  10172. "gl_FragColor = vec4( diffuse, opacity );",
  10173. THREE.ShaderChunk[ "color_fragment" ],
  10174. THREE.ShaderChunk[ "fog_fragment" ],
  10175. "}"
  10176. ].join("\n")
  10177. },
  10178. 'depth': {
  10179. uniforms: {
  10180. "mNear": { type: "f", value: 1.0 },
  10181. "mFar" : { type: "f", value: 2000.0 },
  10182. "opacity" : { type: "f", value: 1.0 }
  10183. },
  10184. vertexShader: [
  10185. "void main() {",
  10186. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10187. "}"
  10188. ].join("\n"),
  10189. fragmentShader: [
  10190. "uniform float mNear;",
  10191. "uniform float mFar;",
  10192. "uniform float opacity;",
  10193. "void main() {",
  10194. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10195. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10196. "gl_FragColor = vec4( vec3( color ), opacity );",
  10197. "}"
  10198. ].join("\n")
  10199. },
  10200. 'normal': {
  10201. uniforms: {
  10202. "opacity" : { type: "f", value: 1.0 }
  10203. },
  10204. vertexShader: [
  10205. "varying vec3 vNormal;",
  10206. "void main() {",
  10207. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10208. "vNormal = normalize( normalMatrix * normal );",
  10209. "gl_Position = projectionMatrix * mvPosition;",
  10210. "}"
  10211. ].join("\n"),
  10212. fragmentShader: [
  10213. "uniform float opacity;",
  10214. "varying vec3 vNormal;",
  10215. "void main() {",
  10216. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10217. "}"
  10218. ].join("\n")
  10219. },
  10220. /* -------------------------------------------------------------------------
  10221. // Normal map shader
  10222. // - Blinn-Phong
  10223. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10224. // - point and directional lights (use with "lights: true" material option)
  10225. ------------------------------------------------------------------------- */
  10226. 'normalmap' : {
  10227. uniforms: THREE.UniformsUtils.merge( [
  10228. THREE.UniformsLib[ "fog" ],
  10229. THREE.UniformsLib[ "lights" ],
  10230. THREE.UniformsLib[ "shadowmap" ],
  10231. {
  10232. "enableAO" : { type: "i", value: 0 },
  10233. "enableDiffuse" : { type: "i", value: 0 },
  10234. "enableSpecular" : { type: "i", value: 0 },
  10235. "enableReflection": { type: "i", value: 0 },
  10236. "enableDisplacement": { type: "i", value: 0 },
  10237. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10238. "tDiffuse" : { type: "t", value: null },
  10239. "tCube" : { type: "t", value: null },
  10240. "tNormal" : { type: "t", value: null },
  10241. "tSpecular" : { type: "t", value: null },
  10242. "tAO" : { type: "t", value: null },
  10243. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10244. "uDisplacementBias": { type: "f", value: 0.0 },
  10245. "uDisplacementScale": { type: "f", value: 1.0 },
  10246. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10247. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10248. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10249. "uShininess": { type: "f", value: 30 },
  10250. "uOpacity": { type: "f", value: 1 },
  10251. "useRefract": { type: "i", value: 0 },
  10252. "uRefractionRatio": { type: "f", value: 0.98 },
  10253. "uReflectivity": { type: "f", value: 0.5 },
  10254. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10255. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10256. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10257. }
  10258. ] ),
  10259. fragmentShader: [
  10260. "uniform vec3 uAmbientColor;",
  10261. "uniform vec3 uDiffuseColor;",
  10262. "uniform vec3 uSpecularColor;",
  10263. "uniform float uShininess;",
  10264. "uniform float uOpacity;",
  10265. "uniform bool enableDiffuse;",
  10266. "uniform bool enableSpecular;",
  10267. "uniform bool enableAO;",
  10268. "uniform bool enableReflection;",
  10269. "uniform sampler2D tDiffuse;",
  10270. "uniform sampler2D tNormal;",
  10271. "uniform sampler2D tSpecular;",
  10272. "uniform sampler2D tAO;",
  10273. "uniform samplerCube tCube;",
  10274. "uniform vec2 uNormalScale;",
  10275. "uniform bool useRefract;",
  10276. "uniform float uRefractionRatio;",
  10277. "uniform float uReflectivity;",
  10278. "varying vec3 vTangent;",
  10279. "varying vec3 vBinormal;",
  10280. "varying vec3 vNormal;",
  10281. "varying vec2 vUv;",
  10282. "uniform vec3 ambientLightColor;",
  10283. "#if MAX_DIR_LIGHTS > 0",
  10284. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10285. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10286. "#endif",
  10287. "#if MAX_HEMI_LIGHTS > 0",
  10288. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10289. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10290. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10291. "#endif",
  10292. "#if MAX_POINT_LIGHTS > 0",
  10293. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10294. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10295. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10296. "#endif",
  10297. "#if MAX_SPOT_LIGHTS > 0",
  10298. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10299. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10300. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10301. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10302. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10303. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10304. "#endif",
  10305. "#ifdef WRAP_AROUND",
  10306. "uniform vec3 wrapRGB;",
  10307. "#endif",
  10308. "varying vec3 vWorldPosition;",
  10309. "varying vec3 vViewPosition;",
  10310. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10311. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10312. "void main() {",
  10313. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10314. "vec3 specularTex = vec3( 1.0 );",
  10315. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10316. "normalTex.xy *= uNormalScale;",
  10317. "normalTex = normalize( normalTex );",
  10318. "if( enableDiffuse ) {",
  10319. "#ifdef GAMMA_INPUT",
  10320. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10321. "texelColor.xyz *= texelColor.xyz;",
  10322. "gl_FragColor = gl_FragColor * texelColor;",
  10323. "#else",
  10324. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10325. "#endif",
  10326. "}",
  10327. "if( enableAO ) {",
  10328. "#ifdef GAMMA_INPUT",
  10329. "vec4 aoColor = texture2D( tAO, vUv );",
  10330. "aoColor.xyz *= aoColor.xyz;",
  10331. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10332. "#else",
  10333. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10334. "#endif",
  10335. "}",
  10336. "if( enableSpecular )",
  10337. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10338. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10339. "vec3 finalNormal = tsb * normalTex;",
  10340. "#ifdef FLIP_SIDED",
  10341. "finalNormal = -finalNormal;",
  10342. "#endif",
  10343. "vec3 normal = normalize( finalNormal );",
  10344. "vec3 viewPosition = normalize( vViewPosition );",
  10345. // point lights
  10346. "#if MAX_POINT_LIGHTS > 0",
  10347. "vec3 pointDiffuse = vec3( 0.0 );",
  10348. "vec3 pointSpecular = vec3( 0.0 );",
  10349. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10350. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10351. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10352. "float pointDistance = 1.0;",
  10353. "if ( pointLightDistance[ i ] > 0.0 )",
  10354. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10355. "pointVector = normalize( pointVector );",
  10356. // diffuse
  10357. "#ifdef WRAP_AROUND",
  10358. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10359. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10360. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10361. "#else",
  10362. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10363. "#endif",
  10364. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10365. // specular
  10366. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10367. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10368. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10369. "#ifdef PHYSICALLY_BASED_SHADING",
  10370. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10371. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10372. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10373. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10374. "#else",
  10375. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10376. "#endif",
  10377. "}",
  10378. "#endif",
  10379. // spot lights
  10380. "#if MAX_SPOT_LIGHTS > 0",
  10381. "vec3 spotDiffuse = vec3( 0.0 );",
  10382. "vec3 spotSpecular = vec3( 0.0 );",
  10383. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10384. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10385. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10386. "float spotDistance = 1.0;",
  10387. "if ( spotLightDistance[ i ] > 0.0 )",
  10388. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10389. "spotVector = normalize( spotVector );",
  10390. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10391. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10392. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10393. // diffuse
  10394. "#ifdef WRAP_AROUND",
  10395. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10396. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10397. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10398. "#else",
  10399. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10400. "#endif",
  10401. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10402. // specular
  10403. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10404. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10405. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10406. "#ifdef PHYSICALLY_BASED_SHADING",
  10407. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10408. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10409. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10410. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10411. "#else",
  10412. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10413. "#endif",
  10414. "}",
  10415. "}",
  10416. "#endif",
  10417. // directional lights
  10418. "#if MAX_DIR_LIGHTS > 0",
  10419. "vec3 dirDiffuse = vec3( 0.0 );",
  10420. "vec3 dirSpecular = vec3( 0.0 );",
  10421. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10422. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10423. "vec3 dirVector = normalize( lDirection.xyz );",
  10424. // diffuse
  10425. "#ifdef WRAP_AROUND",
  10426. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10427. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10428. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10429. "#else",
  10430. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10431. "#endif",
  10432. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10433. // specular
  10434. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10435. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10436. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10437. "#ifdef PHYSICALLY_BASED_SHADING",
  10438. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10439. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10440. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10441. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10442. "#else",
  10443. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10444. "#endif",
  10445. "}",
  10446. "#endif",
  10447. // hemisphere lights
  10448. "#if MAX_HEMI_LIGHTS > 0",
  10449. "vec3 hemiDiffuse = vec3( 0.0 );",
  10450. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10451. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10452. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10453. "vec3 lVector = normalize( lDirection.xyz );",
  10454. // diffuse
  10455. "float dotProduct = dot( normal, lVector );",
  10456. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10457. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10458. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10459. // specular (sky light)
  10460. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10461. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10462. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10463. // specular (ground light)
  10464. "vec3 lVectorGround = -lVector;",
  10465. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10466. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10467. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10468. "#ifdef PHYSICALLY_BASED_SHADING",
  10469. "float dotProductGround = dot( normal, lVectorGround );",
  10470. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10471. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10472. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10473. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10474. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10475. "#else",
  10476. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10477. "#endif",
  10478. "}",
  10479. "#endif",
  10480. // all lights contribution summation
  10481. "vec3 totalDiffuse = vec3( 0.0 );",
  10482. "vec3 totalSpecular = vec3( 0.0 );",
  10483. "#if MAX_DIR_LIGHTS > 0",
  10484. "totalDiffuse += dirDiffuse;",
  10485. "totalSpecular += dirSpecular;",
  10486. "#endif",
  10487. "#if MAX_HEMI_LIGHTS > 0",
  10488. "totalDiffuse += hemiDiffuse;",
  10489. "totalSpecular += hemiSpecular;",
  10490. "#endif",
  10491. "#if MAX_POINT_LIGHTS > 0",
  10492. "totalDiffuse += pointDiffuse;",
  10493. "totalSpecular += pointSpecular;",
  10494. "#endif",
  10495. "#if MAX_SPOT_LIGHTS > 0",
  10496. "totalDiffuse += spotDiffuse;",
  10497. "totalSpecular += spotSpecular;",
  10498. "#endif",
  10499. "#ifdef METAL",
  10500. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10501. "#else",
  10502. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10503. "#endif",
  10504. "if ( enableReflection ) {",
  10505. "vec3 vReflect;",
  10506. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10507. "if ( useRefract ) {",
  10508. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10509. "} else {",
  10510. "vReflect = reflect( cameraToVertex, normal );",
  10511. "}",
  10512. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10513. "#ifdef GAMMA_INPUT",
  10514. "cubeColor.xyz *= cubeColor.xyz;",
  10515. "#endif",
  10516. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10517. "}",
  10518. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10519. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10520. THREE.ShaderChunk[ "fog_fragment" ],
  10521. "}"
  10522. ].join("\n"),
  10523. vertexShader: [
  10524. "attribute vec4 tangent;",
  10525. "uniform vec2 uOffset;",
  10526. "uniform vec2 uRepeat;",
  10527. "uniform bool enableDisplacement;",
  10528. "#ifdef VERTEX_TEXTURES",
  10529. "uniform sampler2D tDisplacement;",
  10530. "uniform float uDisplacementScale;",
  10531. "uniform float uDisplacementBias;",
  10532. "#endif",
  10533. "varying vec3 vTangent;",
  10534. "varying vec3 vBinormal;",
  10535. "varying vec3 vNormal;",
  10536. "varying vec2 vUv;",
  10537. "varying vec3 vWorldPosition;",
  10538. "varying vec3 vViewPosition;",
  10539. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10540. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10541. "void main() {",
  10542. THREE.ShaderChunk[ "skinbase_vertex" ],
  10543. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10544. // normal, tangent and binormal vectors
  10545. "#ifdef USE_SKINNING",
  10546. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10547. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10548. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10549. "#else",
  10550. "vNormal = normalize( normalMatrix * normal );",
  10551. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10552. "#endif",
  10553. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10554. "vUv = uv * uRepeat + uOffset;",
  10555. // displacement mapping
  10556. "vec3 displacedPosition;",
  10557. "#ifdef VERTEX_TEXTURES",
  10558. "if ( enableDisplacement ) {",
  10559. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10560. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10561. "displacedPosition = position + normalize( normal ) * df;",
  10562. "} else {",
  10563. "#ifdef USE_SKINNING",
  10564. "vec4 skinVertex = vec4( position, 1.0 );",
  10565. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10566. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10567. "displacedPosition = skinned.xyz;",
  10568. "#else",
  10569. "displacedPosition = position;",
  10570. "#endif",
  10571. "}",
  10572. "#else",
  10573. "#ifdef USE_SKINNING",
  10574. "vec4 skinVertex = vec4( position, 1.0 );",
  10575. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10576. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10577. "displacedPosition = skinned.xyz;",
  10578. "#else",
  10579. "displacedPosition = position;",
  10580. "#endif",
  10581. "#endif",
  10582. //
  10583. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10584. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10585. "gl_Position = projectionMatrix * mvPosition;",
  10586. //
  10587. "vWorldPosition = worldPosition.xyz;",
  10588. "vViewPosition = -mvPosition.xyz;",
  10589. // shadows
  10590. "#ifdef USE_SHADOWMAP",
  10591. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10592. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10593. "}",
  10594. "#endif",
  10595. "}"
  10596. ].join("\n")
  10597. },
  10598. /* -------------------------------------------------------------------------
  10599. // Cube map shader
  10600. ------------------------------------------------------------------------- */
  10601. 'cube': {
  10602. uniforms: { "tCube": { type: "t", value: null },
  10603. "tFlip": { type: "f", value: -1 } },
  10604. vertexShader: [
  10605. "varying vec3 vWorldPosition;",
  10606. "void main() {",
  10607. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10608. "vWorldPosition = worldPosition.xyz;",
  10609. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10610. "}"
  10611. ].join("\n"),
  10612. fragmentShader: [
  10613. "uniform samplerCube tCube;",
  10614. "uniform float tFlip;",
  10615. "varying vec3 vWorldPosition;",
  10616. "void main() {",
  10617. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10618. "}"
  10619. ].join("\n")
  10620. },
  10621. // Depth encoding into RGBA texture
  10622. // based on SpiderGL shadow map example
  10623. // http://spidergl.org/example.php?id=6
  10624. // originally from
  10625. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10626. // see also here:
  10627. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10628. 'depthRGBA': {
  10629. uniforms: {},
  10630. vertexShader: [
  10631. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10632. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10633. "void main() {",
  10634. THREE.ShaderChunk[ "skinbase_vertex" ],
  10635. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10636. THREE.ShaderChunk[ "skinning_vertex" ],
  10637. THREE.ShaderChunk[ "default_vertex" ],
  10638. "}"
  10639. ].join("\n"),
  10640. fragmentShader: [
  10641. "vec4 pack_depth( const in float depth ) {",
  10642. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10643. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10644. "vec4 res = fract( depth * bit_shift );",
  10645. "res -= res.xxyz * bit_mask;",
  10646. "return res;",
  10647. "}",
  10648. "void main() {",
  10649. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10650. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10651. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10652. //"gl_FragData[ 0 ] = pack_depth( z );",
  10653. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10654. "}"
  10655. ].join("\n")
  10656. }
  10657. };
  10658. /**
  10659. * @author supereggbert / http://www.paulbrunt.co.uk/
  10660. * @author mrdoob / http://mrdoob.com/
  10661. * @author alteredq / http://alteredqualia.com/
  10662. * @author szimek / https://github.com/szimek/
  10663. */
  10664. THREE.WebGLRenderer = function ( parameters ) {
  10665. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10666. parameters = parameters || {};
  10667. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10668. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10669. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10670. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10671. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10672. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10673. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10674. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10675. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10676. // public properties
  10677. this.domElement = _canvas;
  10678. this.context = null;
  10679. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10680. ? parameters.devicePixelRatio
  10681. : window.devicePixelRatio !== undefined
  10682. ? window.devicePixelRatio
  10683. : 1;
  10684. // clearing
  10685. this.autoClear = true;
  10686. this.autoClearColor = true;
  10687. this.autoClearDepth = true;
  10688. this.autoClearStencil = true;
  10689. // scene graph
  10690. this.sortObjects = true;
  10691. this.autoUpdateObjects = true;
  10692. this.autoUpdateScene = true;
  10693. // physically based shading
  10694. this.gammaInput = false;
  10695. this.gammaOutput = false;
  10696. this.physicallyBasedShading = false;
  10697. // shadow map
  10698. this.shadowMapEnabled = false;
  10699. this.shadowMapAutoUpdate = true;
  10700. this.shadowMapType = THREE.PCFShadowMap;
  10701. this.shadowMapCullFace = THREE.CullFaceFront;
  10702. this.shadowMapDebug = false;
  10703. this.shadowMapCascade = false;
  10704. // morphs
  10705. this.maxMorphTargets = 8;
  10706. this.maxMorphNormals = 4;
  10707. // flags
  10708. this.autoScaleCubemaps = true;
  10709. // custom render plugins
  10710. this.renderPluginsPre = [];
  10711. this.renderPluginsPost = [];
  10712. // info
  10713. this.info = {
  10714. memory: {
  10715. programs: 0,
  10716. geometries: 0,
  10717. textures: 0
  10718. },
  10719. render: {
  10720. calls: 0,
  10721. vertices: 0,
  10722. faces: 0,
  10723. points: 0
  10724. }
  10725. };
  10726. // internal properties
  10727. var _this = this,
  10728. _programs = [],
  10729. _programs_counter = 0,
  10730. // internal state cache
  10731. _currentProgram = null,
  10732. _currentFramebuffer = null,
  10733. _currentMaterialId = -1,
  10734. _currentGeometryGroupHash = null,
  10735. _currentCamera = null,
  10736. _geometryGroupCounter = 0,
  10737. _usedTextureUnits = 0,
  10738. // GL state cache
  10739. _oldDoubleSided = -1,
  10740. _oldFlipSided = -1,
  10741. _oldBlending = -1,
  10742. _oldBlendEquation = -1,
  10743. _oldBlendSrc = -1,
  10744. _oldBlendDst = -1,
  10745. _oldDepthTest = -1,
  10746. _oldDepthWrite = -1,
  10747. _oldPolygonOffset = null,
  10748. _oldPolygonOffsetFactor = null,
  10749. _oldPolygonOffsetUnits = null,
  10750. _oldLineWidth = null,
  10751. _viewportX = 0,
  10752. _viewportY = 0,
  10753. _viewportWidth = 0,
  10754. _viewportHeight = 0,
  10755. _currentWidth = 0,
  10756. _currentHeight = 0,
  10757. _enabledAttributes = {},
  10758. // frustum
  10759. _frustum = new THREE.Frustum(),
  10760. // camera matrices cache
  10761. _projScreenMatrix = new THREE.Matrix4(),
  10762. _projScreenMatrixPS = new THREE.Matrix4(),
  10763. _vector3 = new THREE.Vector3(),
  10764. // light arrays cache
  10765. _direction = new THREE.Vector3(),
  10766. _lightsNeedUpdate = true,
  10767. _lights = {
  10768. ambient: [ 0, 0, 0 ],
  10769. directional: { length: 0, colors: new Array(), positions: new Array() },
  10770. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10771. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10772. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10773. };
  10774. // initialize
  10775. var _gl;
  10776. var _glExtensionTextureFloat;
  10777. var _glExtensionStandardDerivatives;
  10778. var _glExtensionTextureFilterAnisotropic;
  10779. var _glExtensionCompressedTextureS3TC;
  10780. initGL();
  10781. setDefaultGLState();
  10782. this.context = _gl;
  10783. // GPU capabilities
  10784. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10785. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10786. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10787. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10788. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10789. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10790. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10791. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10792. //
  10793. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10794. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10795. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10796. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10797. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10798. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10799. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10800. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10801. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10802. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10803. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10804. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10805. // clamp precision to maximum available
  10806. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10807. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10808. if ( _precision === "highp" && ! highpAvailable ) {
  10809. if ( mediumpAvailable ) {
  10810. _precision = "mediump";
  10811. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10812. } else {
  10813. _precision = "lowp";
  10814. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10815. }
  10816. }
  10817. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10818. _precision = "lowp";
  10819. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10820. }
  10821. // API
  10822. this.getContext = function () {
  10823. return _gl;
  10824. };
  10825. this.supportsVertexTextures = function () {
  10826. return _supportsVertexTextures;
  10827. };
  10828. this.supportsFloatTextures = function () {
  10829. return _glExtensionTextureFloat;
  10830. };
  10831. this.supportsStandardDerivatives = function () {
  10832. return _glExtensionStandardDerivatives;
  10833. };
  10834. this.supportsCompressedTextureS3TC = function () {
  10835. return _glExtensionCompressedTextureS3TC;
  10836. };
  10837. this.getMaxAnisotropy = function () {
  10838. return _maxAnisotropy;
  10839. };
  10840. this.getPrecision = function () {
  10841. return _precision;
  10842. };
  10843. this.setSize = function ( width, height ) {
  10844. _canvas.width = width * this.devicePixelRatio;
  10845. _canvas.height = height * this.devicePixelRatio;
  10846. _canvas.style.width = width + 'px';
  10847. _canvas.style.height = height + 'px';
  10848. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10849. };
  10850. this.setViewport = function ( x, y, width, height ) {
  10851. _viewportX = x !== undefined ? x : 0;
  10852. _viewportY = y !== undefined ? y : 0;
  10853. _viewportWidth = width !== undefined ? width : _canvas.width;
  10854. _viewportHeight = height !== undefined ? height : _canvas.height;
  10855. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10856. };
  10857. this.setScissor = function ( x, y, width, height ) {
  10858. _gl.scissor( x, y, width, height );
  10859. };
  10860. this.enableScissorTest = function ( enable ) {
  10861. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10862. };
  10863. // Clearing
  10864. this.setClearColorHex = function ( hex, alpha ) {
  10865. _clearColor.setHex( hex );
  10866. _clearAlpha = alpha;
  10867. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10868. };
  10869. this.setClearColor = function ( color, alpha ) {
  10870. _clearColor.copy( color );
  10871. _clearAlpha = alpha;
  10872. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10873. };
  10874. this.getClearColor = function () {
  10875. return _clearColor;
  10876. };
  10877. this.getClearAlpha = function () {
  10878. return _clearAlpha;
  10879. };
  10880. this.clear = function ( color, depth, stencil ) {
  10881. var bits = 0;
  10882. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10883. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10884. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10885. _gl.clear( bits );
  10886. };
  10887. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10888. this.setRenderTarget( renderTarget );
  10889. this.clear( color, depth, stencil );
  10890. };
  10891. // Plugins
  10892. this.addPostPlugin = function ( plugin ) {
  10893. plugin.init( this );
  10894. this.renderPluginsPost.push( plugin );
  10895. };
  10896. this.addPrePlugin = function ( plugin ) {
  10897. plugin.init( this );
  10898. this.renderPluginsPre.push( plugin );
  10899. };
  10900. // Rendering
  10901. this.updateShadowMap = function ( scene, camera ) {
  10902. _currentProgram = null;
  10903. _oldBlending = -1;
  10904. _oldDepthTest = -1;
  10905. _oldDepthWrite = -1;
  10906. _currentGeometryGroupHash = -1;
  10907. _currentMaterialId = -1;
  10908. _lightsNeedUpdate = true;
  10909. _oldDoubleSided = -1;
  10910. _oldFlipSided = -1;
  10911. this.shadowMapPlugin.update( scene, camera );
  10912. };
  10913. // Internal functions
  10914. // Buffer allocation
  10915. function createParticleBuffers ( geometry ) {
  10916. geometry.__webglVertexBuffer = _gl.createBuffer();
  10917. geometry.__webglColorBuffer = _gl.createBuffer();
  10918. _this.info.memory.geometries ++;
  10919. };
  10920. function createLineBuffers ( geometry ) {
  10921. geometry.__webglVertexBuffer = _gl.createBuffer();
  10922. geometry.__webglColorBuffer = _gl.createBuffer();
  10923. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10924. _this.info.memory.geometries ++;
  10925. };
  10926. function createRibbonBuffers ( geometry ) {
  10927. geometry.__webglVertexBuffer = _gl.createBuffer();
  10928. geometry.__webglColorBuffer = _gl.createBuffer();
  10929. geometry.__webglNormalBuffer = _gl.createBuffer();
  10930. _this.info.memory.geometries ++;
  10931. };
  10932. function createMeshBuffers ( geometryGroup ) {
  10933. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10934. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10935. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10936. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10937. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10938. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10939. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10940. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10941. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10942. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10943. var m, ml;
  10944. if ( geometryGroup.numMorphTargets ) {
  10945. geometryGroup.__webglMorphTargetsBuffers = [];
  10946. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10947. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10948. }
  10949. }
  10950. if ( geometryGroup.numMorphNormals ) {
  10951. geometryGroup.__webglMorphNormalsBuffers = [];
  10952. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10953. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10954. }
  10955. }
  10956. _this.info.memory.geometries ++;
  10957. };
  10958. // Events
  10959. var onGeometryDispose = function ( event ) {
  10960. var geometry = event.target;
  10961. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10962. deallocateGeometry( geometry );
  10963. _this.info.memory.geometries --;
  10964. };
  10965. var onTextureDispose = function ( event ) {
  10966. var texture = event.target;
  10967. texture.removeEventListener( 'dispose', onTextureDispose );
  10968. deallocateTexture( texture );
  10969. _this.info.memory.textures --;
  10970. };
  10971. var onRenderTargetDispose = function ( event ) {
  10972. var renderTarget = event.target;
  10973. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10974. deallocateRenderTarget( renderTarget );
  10975. _this.info.memory.textures --;
  10976. };
  10977. var onMaterialDispose = function ( event ) {
  10978. var material = event.target;
  10979. material.removeEventListener( 'dispose', onMaterialDispose );
  10980. deallocateMaterial( material );
  10981. };
  10982. // Buffer deallocation
  10983. var deallocateGeometry = function ( geometry ) {
  10984. geometry.__webglInit = undefined;
  10985. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10986. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10987. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10988. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10989. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10990. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10991. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10992. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10993. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10994. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10995. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10996. // geometry groups
  10997. if ( geometry.geometryGroups !== undefined ) {
  10998. for ( var g in geometry.geometryGroups ) {
  10999. var geometryGroup = geometry.geometryGroups[ g ];
  11000. if ( geometryGroup.numMorphTargets !== undefined ) {
  11001. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11002. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11003. }
  11004. }
  11005. if ( geometryGroup.numMorphNormals !== undefined ) {
  11006. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11007. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11008. }
  11009. }
  11010. deleteCustomAttributesBuffers( geometryGroup );
  11011. }
  11012. }
  11013. deleteCustomAttributesBuffers( geometry );
  11014. };
  11015. var deallocateTexture = function ( texture ) {
  11016. if ( texture.image && texture.image.__webglTextureCube ) {
  11017. // cube texture
  11018. _gl.deleteTexture( texture.image.__webglTextureCube );
  11019. } else {
  11020. // 2D texture
  11021. if ( ! texture.__webglInit ) return;
  11022. texture.__webglInit = false;
  11023. _gl.deleteTexture( texture.__webglTexture );
  11024. }
  11025. };
  11026. var deallocateRenderTarget = function ( renderTarget ) {
  11027. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11028. _gl.deleteTexture( renderTarget.__webglTexture );
  11029. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11030. for ( var i = 0; i < 6; i ++ ) {
  11031. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11032. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11033. }
  11034. } else {
  11035. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11036. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11037. }
  11038. };
  11039. var deallocateMaterial = function ( material ) {
  11040. var program = material.program;
  11041. if ( program === undefined ) return;
  11042. material.program = undefined;
  11043. // only deallocate GL program if this was the last use of shared program
  11044. // assumed there is only single copy of any program in the _programs list
  11045. // (that's how it's constructed)
  11046. var i, il, programInfo;
  11047. var deleteProgram = false;
  11048. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11049. programInfo = _programs[ i ];
  11050. if ( programInfo.program === program ) {
  11051. programInfo.usedTimes --;
  11052. if ( programInfo.usedTimes === 0 ) {
  11053. deleteProgram = true;
  11054. }
  11055. break;
  11056. }
  11057. }
  11058. if ( deleteProgram === true ) {
  11059. // avoid using array.splice, this is costlier than creating new array from scratch
  11060. var newPrograms = [];
  11061. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11062. programInfo = _programs[ i ];
  11063. if ( programInfo.program !== program ) {
  11064. newPrograms.push( programInfo );
  11065. }
  11066. }
  11067. _programs = newPrograms;
  11068. _gl.deleteProgram( program );
  11069. _this.info.memory.programs --;
  11070. }
  11071. };
  11072. //
  11073. /*
  11074. function deleteParticleBuffers ( geometry ) {
  11075. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11076. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11077. deleteCustomAttributesBuffers( geometry );
  11078. _this.info.memory.geometries --;
  11079. };
  11080. function deleteLineBuffers ( geometry ) {
  11081. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11082. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11083. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11084. deleteCustomAttributesBuffers( geometry );
  11085. _this.info.memory.geometries --;
  11086. };
  11087. function deleteRibbonBuffers ( geometry ) {
  11088. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11089. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11090. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11091. deleteCustomAttributesBuffers( geometry );
  11092. _this.info.memory.geometries --;
  11093. };
  11094. function deleteMeshBuffers ( geometryGroup ) {
  11095. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11096. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11097. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11098. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11099. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11100. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11101. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11102. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11103. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11104. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11105. var m, ml;
  11106. if ( geometryGroup.numMorphTargets ) {
  11107. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11108. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11109. }
  11110. }
  11111. if ( geometryGroup.numMorphNormals ) {
  11112. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11113. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11114. }
  11115. }
  11116. deleteCustomAttributesBuffers( geometryGroup );
  11117. _this.info.memory.geometries --;
  11118. };
  11119. */
  11120. function deleteCustomAttributesBuffers( geometry ) {
  11121. if ( geometry.__webglCustomAttributesList ) {
  11122. for ( var id in geometry.__webglCustomAttributesList ) {
  11123. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11124. }
  11125. }
  11126. };
  11127. // Buffer initialization
  11128. function initCustomAttributes ( geometry, object ) {
  11129. var nvertices = geometry.vertices.length;
  11130. var material = object.material;
  11131. if ( material.attributes ) {
  11132. if ( geometry.__webglCustomAttributesList === undefined ) {
  11133. geometry.__webglCustomAttributesList = [];
  11134. }
  11135. for ( var a in material.attributes ) {
  11136. var attribute = material.attributes[ a ];
  11137. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11138. attribute.__webglInitialized = true;
  11139. var size = 1; // "f" and "i"
  11140. if ( attribute.type === "v2" ) size = 2;
  11141. else if ( attribute.type === "v3" ) size = 3;
  11142. else if ( attribute.type === "v4" ) size = 4;
  11143. else if ( attribute.type === "c" ) size = 3;
  11144. attribute.size = size;
  11145. attribute.array = new Float32Array( nvertices * size );
  11146. attribute.buffer = _gl.createBuffer();
  11147. attribute.buffer.belongsToAttribute = a;
  11148. attribute.needsUpdate = true;
  11149. }
  11150. geometry.__webglCustomAttributesList.push( attribute );
  11151. }
  11152. }
  11153. };
  11154. function initParticleBuffers ( geometry, object ) {
  11155. var nvertices = geometry.vertices.length;
  11156. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11157. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11158. geometry.__sortArray = [];
  11159. geometry.__webglParticleCount = nvertices;
  11160. initCustomAttributes ( geometry, object );
  11161. };
  11162. function initLineBuffers ( geometry, object ) {
  11163. var nvertices = geometry.vertices.length;
  11164. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11165. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11166. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11167. geometry.__webglLineCount = nvertices;
  11168. initCustomAttributes ( geometry, object );
  11169. };
  11170. function initRibbonBuffers ( geometry, object ) {
  11171. var nvertices = geometry.vertices.length;
  11172. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11173. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11174. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11175. geometry.__webglVertexCount = nvertices;
  11176. initCustomAttributes ( geometry, object );
  11177. };
  11178. function initMeshBuffers ( geometryGroup, object ) {
  11179. var geometry = object.geometry,
  11180. faces3 = geometryGroup.faces3,
  11181. faces4 = geometryGroup.faces4,
  11182. nvertices = faces3.length * 3 + faces4.length * 4,
  11183. ntris = faces3.length * 1 + faces4.length * 2,
  11184. nlines = faces3.length * 3 + faces4.length * 4,
  11185. material = getBufferMaterial( object, geometryGroup ),
  11186. uvType = bufferGuessUVType( material ),
  11187. normalType = bufferGuessNormalType( material ),
  11188. vertexColorType = bufferGuessVertexColorType( material );
  11189. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11190. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11191. if ( normalType ) {
  11192. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11193. }
  11194. if ( geometry.hasTangents ) {
  11195. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11196. }
  11197. if ( vertexColorType ) {
  11198. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11199. }
  11200. if ( uvType ) {
  11201. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11202. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11203. }
  11204. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11205. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11206. }
  11207. }
  11208. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11209. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11210. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11211. }
  11212. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11213. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11214. var m, ml;
  11215. if ( geometryGroup.numMorphTargets ) {
  11216. geometryGroup.__morphTargetsArrays = [];
  11217. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11218. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11219. }
  11220. }
  11221. if ( geometryGroup.numMorphNormals ) {
  11222. geometryGroup.__morphNormalsArrays = [];
  11223. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11224. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11225. }
  11226. }
  11227. geometryGroup.__webglFaceCount = ntris * 3;
  11228. geometryGroup.__webglLineCount = nlines * 2;
  11229. // custom attributes
  11230. if ( material.attributes ) {
  11231. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11232. geometryGroup.__webglCustomAttributesList = [];
  11233. }
  11234. for ( var a in material.attributes ) {
  11235. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11236. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11237. var originalAttribute = material.attributes[ a ];
  11238. var attribute = {};
  11239. for ( var property in originalAttribute ) {
  11240. attribute[ property ] = originalAttribute[ property ];
  11241. }
  11242. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11243. attribute.__webglInitialized = true;
  11244. var size = 1; // "f" and "i"
  11245. if( attribute.type === "v2" ) size = 2;
  11246. else if( attribute.type === "v3" ) size = 3;
  11247. else if( attribute.type === "v4" ) size = 4;
  11248. else if( attribute.type === "c" ) size = 3;
  11249. attribute.size = size;
  11250. attribute.array = new Float32Array( nvertices * size );
  11251. attribute.buffer = _gl.createBuffer();
  11252. attribute.buffer.belongsToAttribute = a;
  11253. originalAttribute.needsUpdate = true;
  11254. attribute.__original = originalAttribute;
  11255. }
  11256. geometryGroup.__webglCustomAttributesList.push( attribute );
  11257. }
  11258. }
  11259. geometryGroup.__inittedArrays = true;
  11260. };
  11261. function getBufferMaterial( object, geometryGroup ) {
  11262. return object.material instanceof THREE.MeshFaceMaterial
  11263. ? object.material.materials[ geometryGroup.materialIndex ]
  11264. : object.material;
  11265. };
  11266. function materialNeedsSmoothNormals ( material ) {
  11267. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11268. };
  11269. function bufferGuessNormalType ( material ) {
  11270. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11271. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11272. return false;
  11273. }
  11274. if ( materialNeedsSmoothNormals( material ) ) {
  11275. return THREE.SmoothShading;
  11276. } else {
  11277. return THREE.FlatShading;
  11278. }
  11279. };
  11280. function bufferGuessVertexColorType ( material ) {
  11281. if ( material.vertexColors ) {
  11282. return material.vertexColors;
  11283. }
  11284. return false;
  11285. };
  11286. function bufferGuessUVType ( material ) {
  11287. // material must use some texture to require uvs
  11288. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  11289. return true;
  11290. }
  11291. return false;
  11292. };
  11293. //
  11294. function initDirectBuffers( geometry ) {
  11295. var a, attribute, type;
  11296. for ( a in geometry.attributes ) {
  11297. if ( a === "index" ) {
  11298. type = _gl.ELEMENT_ARRAY_BUFFER;
  11299. } else {
  11300. type = _gl.ARRAY_BUFFER;
  11301. }
  11302. attribute = geometry.attributes[ a ];
  11303. attribute.buffer = _gl.createBuffer();
  11304. _gl.bindBuffer( type, attribute.buffer );
  11305. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11306. }
  11307. };
  11308. // Buffer setting
  11309. function setParticleBuffers ( geometry, hint, object ) {
  11310. var v, c, vertex, offset, index, color,
  11311. vertices = geometry.vertices,
  11312. vl = vertices.length,
  11313. colors = geometry.colors,
  11314. cl = colors.length,
  11315. vertexArray = geometry.__vertexArray,
  11316. colorArray = geometry.__colorArray,
  11317. sortArray = geometry.__sortArray,
  11318. dirtyVertices = geometry.verticesNeedUpdate,
  11319. dirtyElements = geometry.elementsNeedUpdate,
  11320. dirtyColors = geometry.colorsNeedUpdate,
  11321. customAttributes = geometry.__webglCustomAttributesList,
  11322. i, il,
  11323. a, ca, cal, value,
  11324. customAttribute;
  11325. if ( object.sortParticles ) {
  11326. _projScreenMatrixPS.copy( _projScreenMatrix );
  11327. _projScreenMatrixPS.multiply( object.matrixWorld );
  11328. for ( v = 0; v < vl; v ++ ) {
  11329. vertex = vertices[ v ];
  11330. _vector3.copy( vertex );
  11331. _vector3.applyProjection( _projScreenMatrixPS );
  11332. sortArray[ v ] = [ _vector3.z, v ];
  11333. }
  11334. sortArray.sort( numericalSort );
  11335. for ( v = 0; v < vl; v ++ ) {
  11336. vertex = vertices[ sortArray[v][1] ];
  11337. offset = v * 3;
  11338. vertexArray[ offset ] = vertex.x;
  11339. vertexArray[ offset + 1 ] = vertex.y;
  11340. vertexArray[ offset + 2 ] = vertex.z;
  11341. }
  11342. for ( c = 0; c < cl; c ++ ) {
  11343. offset = c * 3;
  11344. color = colors[ sortArray[c][1] ];
  11345. colorArray[ offset ] = color.r;
  11346. colorArray[ offset + 1 ] = color.g;
  11347. colorArray[ offset + 2 ] = color.b;
  11348. }
  11349. if ( customAttributes ) {
  11350. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11351. customAttribute = customAttributes[ i ];
  11352. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11353. offset = 0;
  11354. cal = customAttribute.value.length;
  11355. if ( customAttribute.size === 1 ) {
  11356. for ( ca = 0; ca < cal; ca ++ ) {
  11357. index = sortArray[ ca ][ 1 ];
  11358. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11359. }
  11360. } else if ( customAttribute.size === 2 ) {
  11361. for ( ca = 0; ca < cal; ca ++ ) {
  11362. index = sortArray[ ca ][ 1 ];
  11363. value = customAttribute.value[ index ];
  11364. customAttribute.array[ offset ] = value.x;
  11365. customAttribute.array[ offset + 1 ] = value.y;
  11366. offset += 2;
  11367. }
  11368. } else if ( customAttribute.size === 3 ) {
  11369. if ( customAttribute.type === "c" ) {
  11370. for ( ca = 0; ca < cal; ca ++ ) {
  11371. index = sortArray[ ca ][ 1 ];
  11372. value = customAttribute.value[ index ];
  11373. customAttribute.array[ offset ] = value.r;
  11374. customAttribute.array[ offset + 1 ] = value.g;
  11375. customAttribute.array[ offset + 2 ] = value.b;
  11376. offset += 3;
  11377. }
  11378. } else {
  11379. for ( ca = 0; ca < cal; ca ++ ) {
  11380. index = sortArray[ ca ][ 1 ];
  11381. value = customAttribute.value[ index ];
  11382. customAttribute.array[ offset ] = value.x;
  11383. customAttribute.array[ offset + 1 ] = value.y;
  11384. customAttribute.array[ offset + 2 ] = value.z;
  11385. offset += 3;
  11386. }
  11387. }
  11388. } else if ( customAttribute.size === 4 ) {
  11389. for ( ca = 0; ca < cal; ca ++ ) {
  11390. index = sortArray[ ca ][ 1 ];
  11391. value = customAttribute.value[ index ];
  11392. customAttribute.array[ offset ] = value.x;
  11393. customAttribute.array[ offset + 1 ] = value.y;
  11394. customAttribute.array[ offset + 2 ] = value.z;
  11395. customAttribute.array[ offset + 3 ] = value.w;
  11396. offset += 4;
  11397. }
  11398. }
  11399. }
  11400. }
  11401. } else {
  11402. if ( dirtyVertices ) {
  11403. for ( v = 0; v < vl; v ++ ) {
  11404. vertex = vertices[ v ];
  11405. offset = v * 3;
  11406. vertexArray[ offset ] = vertex.x;
  11407. vertexArray[ offset + 1 ] = vertex.y;
  11408. vertexArray[ offset + 2 ] = vertex.z;
  11409. }
  11410. }
  11411. if ( dirtyColors ) {
  11412. for ( c = 0; c < cl; c ++ ) {
  11413. color = colors[ c ];
  11414. offset = c * 3;
  11415. colorArray[ offset ] = color.r;
  11416. colorArray[ offset + 1 ] = color.g;
  11417. colorArray[ offset + 2 ] = color.b;
  11418. }
  11419. }
  11420. if ( customAttributes ) {
  11421. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11422. customAttribute = customAttributes[ i ];
  11423. if ( customAttribute.needsUpdate &&
  11424. ( customAttribute.boundTo === undefined ||
  11425. customAttribute.boundTo === "vertices") ) {
  11426. cal = customAttribute.value.length;
  11427. offset = 0;
  11428. if ( customAttribute.size === 1 ) {
  11429. for ( ca = 0; ca < cal; ca ++ ) {
  11430. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11431. }
  11432. } else if ( customAttribute.size === 2 ) {
  11433. for ( ca = 0; ca < cal; ca ++ ) {
  11434. value = customAttribute.value[ ca ];
  11435. customAttribute.array[ offset ] = value.x;
  11436. customAttribute.array[ offset + 1 ] = value.y;
  11437. offset += 2;
  11438. }
  11439. } else if ( customAttribute.size === 3 ) {
  11440. if ( customAttribute.type === "c" ) {
  11441. for ( ca = 0; ca < cal; ca ++ ) {
  11442. value = customAttribute.value[ ca ];
  11443. customAttribute.array[ offset ] = value.r;
  11444. customAttribute.array[ offset + 1 ] = value.g;
  11445. customAttribute.array[ offset + 2 ] = value.b;
  11446. offset += 3;
  11447. }
  11448. } else {
  11449. for ( ca = 0; ca < cal; ca ++ ) {
  11450. value = customAttribute.value[ ca ];
  11451. customAttribute.array[ offset ] = value.x;
  11452. customAttribute.array[ offset + 1 ] = value.y;
  11453. customAttribute.array[ offset + 2 ] = value.z;
  11454. offset += 3;
  11455. }
  11456. }
  11457. } else if ( customAttribute.size === 4 ) {
  11458. for ( ca = 0; ca < cal; ca ++ ) {
  11459. value = customAttribute.value[ ca ];
  11460. customAttribute.array[ offset ] = value.x;
  11461. customAttribute.array[ offset + 1 ] = value.y;
  11462. customAttribute.array[ offset + 2 ] = value.z;
  11463. customAttribute.array[ offset + 3 ] = value.w;
  11464. offset += 4;
  11465. }
  11466. }
  11467. }
  11468. }
  11469. }
  11470. }
  11471. if ( dirtyVertices || object.sortParticles ) {
  11472. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11473. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11474. }
  11475. if ( dirtyColors || object.sortParticles ) {
  11476. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11477. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11478. }
  11479. if ( customAttributes ) {
  11480. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11481. customAttribute = customAttributes[ i ];
  11482. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11483. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11484. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11485. }
  11486. }
  11487. }
  11488. };
  11489. function setLineBuffers ( geometry, hint ) {
  11490. var v, c, d, vertex, offset, color,
  11491. vertices = geometry.vertices,
  11492. colors = geometry.colors,
  11493. lineDistances = geometry.lineDistances,
  11494. vl = vertices.length,
  11495. cl = colors.length,
  11496. dl = lineDistances.length,
  11497. vertexArray = geometry.__vertexArray,
  11498. colorArray = geometry.__colorArray,
  11499. lineDistanceArray = geometry.__lineDistanceArray,
  11500. dirtyVertices = geometry.verticesNeedUpdate,
  11501. dirtyColors = geometry.colorsNeedUpdate,
  11502. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11503. customAttributes = geometry.__webglCustomAttributesList,
  11504. i, il,
  11505. a, ca, cal, value,
  11506. customAttribute;
  11507. if ( dirtyVertices ) {
  11508. for ( v = 0; v < vl; v ++ ) {
  11509. vertex = vertices[ v ];
  11510. offset = v * 3;
  11511. vertexArray[ offset ] = vertex.x;
  11512. vertexArray[ offset + 1 ] = vertex.y;
  11513. vertexArray[ offset + 2 ] = vertex.z;
  11514. }
  11515. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11516. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11517. }
  11518. if ( dirtyColors ) {
  11519. for ( c = 0; c < cl; c ++ ) {
  11520. color = colors[ c ];
  11521. offset = c * 3;
  11522. colorArray[ offset ] = color.r;
  11523. colorArray[ offset + 1 ] = color.g;
  11524. colorArray[ offset + 2 ] = color.b;
  11525. }
  11526. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11527. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11528. }
  11529. if ( dirtyLineDistances ) {
  11530. for ( d = 0; d < dl; d ++ ) {
  11531. lineDistanceArray[ d ] = lineDistances[ d ];
  11532. }
  11533. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11534. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11535. }
  11536. if ( customAttributes ) {
  11537. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11538. customAttribute = customAttributes[ i ];
  11539. if ( customAttribute.needsUpdate &&
  11540. ( customAttribute.boundTo === undefined ||
  11541. customAttribute.boundTo === "vertices" ) ) {
  11542. offset = 0;
  11543. cal = customAttribute.value.length;
  11544. if ( customAttribute.size === 1 ) {
  11545. for ( ca = 0; ca < cal; ca ++ ) {
  11546. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11547. }
  11548. } else if ( customAttribute.size === 2 ) {
  11549. for ( ca = 0; ca < cal; ca ++ ) {
  11550. value = customAttribute.value[ ca ];
  11551. customAttribute.array[ offset ] = value.x;
  11552. customAttribute.array[ offset + 1 ] = value.y;
  11553. offset += 2;
  11554. }
  11555. } else if ( customAttribute.size === 3 ) {
  11556. if ( customAttribute.type === "c" ) {
  11557. for ( ca = 0; ca < cal; ca ++ ) {
  11558. value = customAttribute.value[ ca ];
  11559. customAttribute.array[ offset ] = value.r;
  11560. customAttribute.array[ offset + 1 ] = value.g;
  11561. customAttribute.array[ offset + 2 ] = value.b;
  11562. offset += 3;
  11563. }
  11564. } else {
  11565. for ( ca = 0; ca < cal; ca ++ ) {
  11566. value = customAttribute.value[ ca ];
  11567. customAttribute.array[ offset ] = value.x;
  11568. customAttribute.array[ offset + 1 ] = value.y;
  11569. customAttribute.array[ offset + 2 ] = value.z;
  11570. offset += 3;
  11571. }
  11572. }
  11573. } else if ( customAttribute.size === 4 ) {
  11574. for ( ca = 0; ca < cal; ca ++ ) {
  11575. value = customAttribute.value[ ca ];
  11576. customAttribute.array[ offset ] = value.x;
  11577. customAttribute.array[ offset + 1 ] = value.y;
  11578. customAttribute.array[ offset + 2 ] = value.z;
  11579. customAttribute.array[ offset + 3 ] = value.w;
  11580. offset += 4;
  11581. }
  11582. }
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11584. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11585. }
  11586. }
  11587. }
  11588. };
  11589. function setRibbonBuffers ( geometry, hint ) {
  11590. var v, c, n, vertex, offset, color, normal,
  11591. i, il, ca, cal, customAttribute, value,
  11592. vertices = geometry.vertices,
  11593. colors = geometry.colors,
  11594. normals = geometry.normals,
  11595. vl = vertices.length,
  11596. cl = colors.length,
  11597. nl = normals.length,
  11598. vertexArray = geometry.__vertexArray,
  11599. colorArray = geometry.__colorArray,
  11600. normalArray = geometry.__normalArray,
  11601. dirtyVertices = geometry.verticesNeedUpdate,
  11602. dirtyColors = geometry.colorsNeedUpdate,
  11603. dirtyNormals = geometry.normalsNeedUpdate,
  11604. customAttributes = geometry.__webglCustomAttributesList;
  11605. if ( dirtyVertices ) {
  11606. for ( v = 0; v < vl; v ++ ) {
  11607. vertex = vertices[ v ];
  11608. offset = v * 3;
  11609. vertexArray[ offset ] = vertex.x;
  11610. vertexArray[ offset + 1 ] = vertex.y;
  11611. vertexArray[ offset + 2 ] = vertex.z;
  11612. }
  11613. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11614. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11615. }
  11616. if ( dirtyColors ) {
  11617. for ( c = 0; c < cl; c ++ ) {
  11618. color = colors[ c ];
  11619. offset = c * 3;
  11620. colorArray[ offset ] = color.r;
  11621. colorArray[ offset + 1 ] = color.g;
  11622. colorArray[ offset + 2 ] = color.b;
  11623. }
  11624. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11625. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11626. }
  11627. if ( dirtyNormals ) {
  11628. for ( n = 0; n < nl; n ++ ) {
  11629. normal = normals[ n ];
  11630. offset = n * 3;
  11631. normalArray[ offset ] = normal.x;
  11632. normalArray[ offset + 1 ] = normal.y;
  11633. normalArray[ offset + 2 ] = normal.z;
  11634. }
  11635. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11636. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11637. }
  11638. if ( customAttributes ) {
  11639. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11640. customAttribute = customAttributes[ i ];
  11641. if ( customAttribute.needsUpdate &&
  11642. ( customAttribute.boundTo === undefined ||
  11643. customAttribute.boundTo === "vertices" ) ) {
  11644. offset = 0;
  11645. cal = customAttribute.value.length;
  11646. if ( customAttribute.size === 1 ) {
  11647. for ( ca = 0; ca < cal; ca ++ ) {
  11648. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11649. }
  11650. } else if ( customAttribute.size === 2 ) {
  11651. for ( ca = 0; ca < cal; ca ++ ) {
  11652. value = customAttribute.value[ ca ];
  11653. customAttribute.array[ offset ] = value.x;
  11654. customAttribute.array[ offset + 1 ] = value.y;
  11655. offset += 2;
  11656. }
  11657. } else if ( customAttribute.size === 3 ) {
  11658. if ( customAttribute.type === "c" ) {
  11659. for ( ca = 0; ca < cal; ca ++ ) {
  11660. value = customAttribute.value[ ca ];
  11661. customAttribute.array[ offset ] = value.r;
  11662. customAttribute.array[ offset + 1 ] = value.g;
  11663. customAttribute.array[ offset + 2 ] = value.b;
  11664. offset += 3;
  11665. }
  11666. } else {
  11667. for ( ca = 0; ca < cal; ca ++ ) {
  11668. value = customAttribute.value[ ca ];
  11669. customAttribute.array[ offset ] = value.x;
  11670. customAttribute.array[ offset + 1 ] = value.y;
  11671. customAttribute.array[ offset + 2 ] = value.z;
  11672. offset += 3;
  11673. }
  11674. }
  11675. } else if ( customAttribute.size === 4 ) {
  11676. for ( ca = 0; ca < cal; ca ++ ) {
  11677. value = customAttribute.value[ ca ];
  11678. customAttribute.array[ offset ] = value.x;
  11679. customAttribute.array[ offset + 1 ] = value.y;
  11680. customAttribute.array[ offset + 2 ] = value.z;
  11681. customAttribute.array[ offset + 3 ] = value.w;
  11682. offset += 4;
  11683. }
  11684. }
  11685. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11686. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11687. }
  11688. }
  11689. }
  11690. };
  11691. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11692. if ( ! geometryGroup.__inittedArrays ) {
  11693. return;
  11694. }
  11695. var normalType = bufferGuessNormalType( material ),
  11696. vertexColorType = bufferGuessVertexColorType( material ),
  11697. uvType = bufferGuessUVType( material ),
  11698. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11699. var f, fl, fi, face,
  11700. vertexNormals, faceNormal, normal,
  11701. vertexColors, faceColor,
  11702. vertexTangents,
  11703. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11704. c1, c2, c3, c4,
  11705. sw1, sw2, sw3, sw4,
  11706. si1, si2, si3, si4,
  11707. sa1, sa2, sa3, sa4,
  11708. sb1, sb2, sb3, sb4,
  11709. m, ml, i, il,
  11710. vn, uvi, uv2i,
  11711. vk, vkl, vka,
  11712. nka, chf, faceVertexNormals,
  11713. a,
  11714. vertexIndex = 0,
  11715. offset = 0,
  11716. offset_uv = 0,
  11717. offset_uv2 = 0,
  11718. offset_face = 0,
  11719. offset_normal = 0,
  11720. offset_tangent = 0,
  11721. offset_line = 0,
  11722. offset_color = 0,
  11723. offset_skin = 0,
  11724. offset_morphTarget = 0,
  11725. offset_custom = 0,
  11726. offset_customSrc = 0,
  11727. value,
  11728. vertexArray = geometryGroup.__vertexArray,
  11729. uvArray = geometryGroup.__uvArray,
  11730. uv2Array = geometryGroup.__uv2Array,
  11731. normalArray = geometryGroup.__normalArray,
  11732. tangentArray = geometryGroup.__tangentArray,
  11733. colorArray = geometryGroup.__colorArray,
  11734. skinIndexArray = geometryGroup.__skinIndexArray,
  11735. skinWeightArray = geometryGroup.__skinWeightArray,
  11736. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11737. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11738. customAttributes = geometryGroup.__webglCustomAttributesList,
  11739. customAttribute,
  11740. faceArray = geometryGroup.__faceArray,
  11741. lineArray = geometryGroup.__lineArray,
  11742. geometry = object.geometry, // this is shared for all chunks
  11743. dirtyVertices = geometry.verticesNeedUpdate,
  11744. dirtyElements = geometry.elementsNeedUpdate,
  11745. dirtyUvs = geometry.uvsNeedUpdate,
  11746. dirtyNormals = geometry.normalsNeedUpdate,
  11747. dirtyTangents = geometry.tangentsNeedUpdate,
  11748. dirtyColors = geometry.colorsNeedUpdate,
  11749. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11750. vertices = geometry.vertices,
  11751. chunk_faces3 = geometryGroup.faces3,
  11752. chunk_faces4 = geometryGroup.faces4,
  11753. obj_faces = geometry.faces,
  11754. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11755. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11756. obj_colors = geometry.colors,
  11757. obj_skinIndices = geometry.skinIndices,
  11758. obj_skinWeights = geometry.skinWeights,
  11759. morphTargets = geometry.morphTargets,
  11760. morphNormals = geometry.morphNormals;
  11761. if ( dirtyVertices ) {
  11762. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11763. face = obj_faces[ chunk_faces3[ f ] ];
  11764. v1 = vertices[ face.a ];
  11765. v2 = vertices[ face.b ];
  11766. v3 = vertices[ face.c ];
  11767. vertexArray[ offset ] = v1.x;
  11768. vertexArray[ offset + 1 ] = v1.y;
  11769. vertexArray[ offset + 2 ] = v1.z;
  11770. vertexArray[ offset + 3 ] = v2.x;
  11771. vertexArray[ offset + 4 ] = v2.y;
  11772. vertexArray[ offset + 5 ] = v2.z;
  11773. vertexArray[ offset + 6 ] = v3.x;
  11774. vertexArray[ offset + 7 ] = v3.y;
  11775. vertexArray[ offset + 8 ] = v3.z;
  11776. offset += 9;
  11777. }
  11778. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11779. face = obj_faces[ chunk_faces4[ f ] ];
  11780. v1 = vertices[ face.a ];
  11781. v2 = vertices[ face.b ];
  11782. v3 = vertices[ face.c ];
  11783. v4 = vertices[ face.d ];
  11784. vertexArray[ offset ] = v1.x;
  11785. vertexArray[ offset + 1 ] = v1.y;
  11786. vertexArray[ offset + 2 ] = v1.z;
  11787. vertexArray[ offset + 3 ] = v2.x;
  11788. vertexArray[ offset + 4 ] = v2.y;
  11789. vertexArray[ offset + 5 ] = v2.z;
  11790. vertexArray[ offset + 6 ] = v3.x;
  11791. vertexArray[ offset + 7 ] = v3.y;
  11792. vertexArray[ offset + 8 ] = v3.z;
  11793. vertexArray[ offset + 9 ] = v4.x;
  11794. vertexArray[ offset + 10 ] = v4.y;
  11795. vertexArray[ offset + 11 ] = v4.z;
  11796. offset += 12;
  11797. }
  11798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11799. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11800. }
  11801. if ( dirtyMorphTargets ) {
  11802. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11803. offset_morphTarget = 0;
  11804. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11805. chf = chunk_faces3[ f ];
  11806. face = obj_faces[ chf ];
  11807. // morph positions
  11808. v1 = morphTargets[ vk ].vertices[ face.a ];
  11809. v2 = morphTargets[ vk ].vertices[ face.b ];
  11810. v3 = morphTargets[ vk ].vertices[ face.c ];
  11811. vka = morphTargetsArrays[ vk ];
  11812. vka[ offset_morphTarget ] = v1.x;
  11813. vka[ offset_morphTarget + 1 ] = v1.y;
  11814. vka[ offset_morphTarget + 2 ] = v1.z;
  11815. vka[ offset_morphTarget + 3 ] = v2.x;
  11816. vka[ offset_morphTarget + 4 ] = v2.y;
  11817. vka[ offset_morphTarget + 5 ] = v2.z;
  11818. vka[ offset_morphTarget + 6 ] = v3.x;
  11819. vka[ offset_morphTarget + 7 ] = v3.y;
  11820. vka[ offset_morphTarget + 8 ] = v3.z;
  11821. // morph normals
  11822. if ( material.morphNormals ) {
  11823. if ( needsSmoothNormals ) {
  11824. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11825. n1 = faceVertexNormals.a;
  11826. n2 = faceVertexNormals.b;
  11827. n3 = faceVertexNormals.c;
  11828. } else {
  11829. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11830. n2 = n1;
  11831. n3 = n1;
  11832. }
  11833. nka = morphNormalsArrays[ vk ];
  11834. nka[ offset_morphTarget ] = n1.x;
  11835. nka[ offset_morphTarget + 1 ] = n1.y;
  11836. nka[ offset_morphTarget + 2 ] = n1.z;
  11837. nka[ offset_morphTarget + 3 ] = n2.x;
  11838. nka[ offset_morphTarget + 4 ] = n2.y;
  11839. nka[ offset_morphTarget + 5 ] = n2.z;
  11840. nka[ offset_morphTarget + 6 ] = n3.x;
  11841. nka[ offset_morphTarget + 7 ] = n3.y;
  11842. nka[ offset_morphTarget + 8 ] = n3.z;
  11843. }
  11844. //
  11845. offset_morphTarget += 9;
  11846. }
  11847. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11848. chf = chunk_faces4[ f ];
  11849. face = obj_faces[ chf ];
  11850. // morph positions
  11851. v1 = morphTargets[ vk ].vertices[ face.a ];
  11852. v2 = morphTargets[ vk ].vertices[ face.b ];
  11853. v3 = morphTargets[ vk ].vertices[ face.c ];
  11854. v4 = morphTargets[ vk ].vertices[ face.d ];
  11855. vka = morphTargetsArrays[ vk ];
  11856. vka[ offset_morphTarget ] = v1.x;
  11857. vka[ offset_morphTarget + 1 ] = v1.y;
  11858. vka[ offset_morphTarget + 2 ] = v1.z;
  11859. vka[ offset_morphTarget + 3 ] = v2.x;
  11860. vka[ offset_morphTarget + 4 ] = v2.y;
  11861. vka[ offset_morphTarget + 5 ] = v2.z;
  11862. vka[ offset_morphTarget + 6 ] = v3.x;
  11863. vka[ offset_morphTarget + 7 ] = v3.y;
  11864. vka[ offset_morphTarget + 8 ] = v3.z;
  11865. vka[ offset_morphTarget + 9 ] = v4.x;
  11866. vka[ offset_morphTarget + 10 ] = v4.y;
  11867. vka[ offset_morphTarget + 11 ] = v4.z;
  11868. // morph normals
  11869. if ( material.morphNormals ) {
  11870. if ( needsSmoothNormals ) {
  11871. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11872. n1 = faceVertexNormals.a;
  11873. n2 = faceVertexNormals.b;
  11874. n3 = faceVertexNormals.c;
  11875. n4 = faceVertexNormals.d;
  11876. } else {
  11877. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11878. n2 = n1;
  11879. n3 = n1;
  11880. n4 = n1;
  11881. }
  11882. nka = morphNormalsArrays[ vk ];
  11883. nka[ offset_morphTarget ] = n1.x;
  11884. nka[ offset_morphTarget + 1 ] = n1.y;
  11885. nka[ offset_morphTarget + 2 ] = n1.z;
  11886. nka[ offset_morphTarget + 3 ] = n2.x;
  11887. nka[ offset_morphTarget + 4 ] = n2.y;
  11888. nka[ offset_morphTarget + 5 ] = n2.z;
  11889. nka[ offset_morphTarget + 6 ] = n3.x;
  11890. nka[ offset_morphTarget + 7 ] = n3.y;
  11891. nka[ offset_morphTarget + 8 ] = n3.z;
  11892. nka[ offset_morphTarget + 9 ] = n4.x;
  11893. nka[ offset_morphTarget + 10 ] = n4.y;
  11894. nka[ offset_morphTarget + 11 ] = n4.z;
  11895. }
  11896. //
  11897. offset_morphTarget += 12;
  11898. }
  11899. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11900. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11901. if ( material.morphNormals ) {
  11902. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11903. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11904. }
  11905. }
  11906. }
  11907. if ( obj_skinWeights.length ) {
  11908. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11909. face = obj_faces[ chunk_faces3[ f ] ];
  11910. // weights
  11911. sw1 = obj_skinWeights[ face.a ];
  11912. sw2 = obj_skinWeights[ face.b ];
  11913. sw3 = obj_skinWeights[ face.c ];
  11914. skinWeightArray[ offset_skin ] = sw1.x;
  11915. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11916. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11917. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11918. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11919. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11920. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11921. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11922. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11923. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11924. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11925. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11926. // indices
  11927. si1 = obj_skinIndices[ face.a ];
  11928. si2 = obj_skinIndices[ face.b ];
  11929. si3 = obj_skinIndices[ face.c ];
  11930. skinIndexArray[ offset_skin ] = si1.x;
  11931. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11932. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11933. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11934. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11935. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11936. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11937. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11938. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11939. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11940. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11941. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11942. offset_skin += 12;
  11943. }
  11944. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11945. face = obj_faces[ chunk_faces4[ f ] ];
  11946. // weights
  11947. sw1 = obj_skinWeights[ face.a ];
  11948. sw2 = obj_skinWeights[ face.b ];
  11949. sw3 = obj_skinWeights[ face.c ];
  11950. sw4 = obj_skinWeights[ face.d ];
  11951. skinWeightArray[ offset_skin ] = sw1.x;
  11952. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11953. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11954. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11955. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11956. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11957. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11958. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11959. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11960. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11961. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11962. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11963. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11964. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11965. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11966. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11967. // indices
  11968. si1 = obj_skinIndices[ face.a ];
  11969. si2 = obj_skinIndices[ face.b ];
  11970. si3 = obj_skinIndices[ face.c ];
  11971. si4 = obj_skinIndices[ face.d ];
  11972. skinIndexArray[ offset_skin ] = si1.x;
  11973. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11974. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11975. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11976. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11977. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11978. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11979. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11980. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11981. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11982. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11983. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11984. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11985. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11986. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11987. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11988. offset_skin += 16;
  11989. }
  11990. if ( offset_skin > 0 ) {
  11991. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11992. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11993. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11994. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11995. }
  11996. }
  11997. if ( dirtyColors && vertexColorType ) {
  11998. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11999. face = obj_faces[ chunk_faces3[ f ] ];
  12000. vertexColors = face.vertexColors;
  12001. faceColor = face.color;
  12002. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12003. c1 = vertexColors[ 0 ];
  12004. c2 = vertexColors[ 1 ];
  12005. c3 = vertexColors[ 2 ];
  12006. } else {
  12007. c1 = faceColor;
  12008. c2 = faceColor;
  12009. c3 = faceColor;
  12010. }
  12011. colorArray[ offset_color ] = c1.r;
  12012. colorArray[ offset_color + 1 ] = c1.g;
  12013. colorArray[ offset_color + 2 ] = c1.b;
  12014. colorArray[ offset_color + 3 ] = c2.r;
  12015. colorArray[ offset_color + 4 ] = c2.g;
  12016. colorArray[ offset_color + 5 ] = c2.b;
  12017. colorArray[ offset_color + 6 ] = c3.r;
  12018. colorArray[ offset_color + 7 ] = c3.g;
  12019. colorArray[ offset_color + 8 ] = c3.b;
  12020. offset_color += 9;
  12021. }
  12022. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12023. face = obj_faces[ chunk_faces4[ f ] ];
  12024. vertexColors = face.vertexColors;
  12025. faceColor = face.color;
  12026. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12027. c1 = vertexColors[ 0 ];
  12028. c2 = vertexColors[ 1 ];
  12029. c3 = vertexColors[ 2 ];
  12030. c4 = vertexColors[ 3 ];
  12031. } else {
  12032. c1 = faceColor;
  12033. c2 = faceColor;
  12034. c3 = faceColor;
  12035. c4 = faceColor;
  12036. }
  12037. colorArray[ offset_color ] = c1.r;
  12038. colorArray[ offset_color + 1 ] = c1.g;
  12039. colorArray[ offset_color + 2 ] = c1.b;
  12040. colorArray[ offset_color + 3 ] = c2.r;
  12041. colorArray[ offset_color + 4 ] = c2.g;
  12042. colorArray[ offset_color + 5 ] = c2.b;
  12043. colorArray[ offset_color + 6 ] = c3.r;
  12044. colorArray[ offset_color + 7 ] = c3.g;
  12045. colorArray[ offset_color + 8 ] = c3.b;
  12046. colorArray[ offset_color + 9 ] = c4.r;
  12047. colorArray[ offset_color + 10 ] = c4.g;
  12048. colorArray[ offset_color + 11 ] = c4.b;
  12049. offset_color += 12;
  12050. }
  12051. if ( offset_color > 0 ) {
  12052. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12053. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12054. }
  12055. }
  12056. if ( dirtyTangents && geometry.hasTangents ) {
  12057. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12058. face = obj_faces[ chunk_faces3[ f ] ];
  12059. vertexTangents = face.vertexTangents;
  12060. t1 = vertexTangents[ 0 ];
  12061. t2 = vertexTangents[ 1 ];
  12062. t3 = vertexTangents[ 2 ];
  12063. tangentArray[ offset_tangent ] = t1.x;
  12064. tangentArray[ offset_tangent + 1 ] = t1.y;
  12065. tangentArray[ offset_tangent + 2 ] = t1.z;
  12066. tangentArray[ offset_tangent + 3 ] = t1.w;
  12067. tangentArray[ offset_tangent + 4 ] = t2.x;
  12068. tangentArray[ offset_tangent + 5 ] = t2.y;
  12069. tangentArray[ offset_tangent + 6 ] = t2.z;
  12070. tangentArray[ offset_tangent + 7 ] = t2.w;
  12071. tangentArray[ offset_tangent + 8 ] = t3.x;
  12072. tangentArray[ offset_tangent + 9 ] = t3.y;
  12073. tangentArray[ offset_tangent + 10 ] = t3.z;
  12074. tangentArray[ offset_tangent + 11 ] = t3.w;
  12075. offset_tangent += 12;
  12076. }
  12077. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12078. face = obj_faces[ chunk_faces4[ f ] ];
  12079. vertexTangents = face.vertexTangents;
  12080. t1 = vertexTangents[ 0 ];
  12081. t2 = vertexTangents[ 1 ];
  12082. t3 = vertexTangents[ 2 ];
  12083. t4 = vertexTangents[ 3 ];
  12084. tangentArray[ offset_tangent ] = t1.x;
  12085. tangentArray[ offset_tangent + 1 ] = t1.y;
  12086. tangentArray[ offset_tangent + 2 ] = t1.z;
  12087. tangentArray[ offset_tangent + 3 ] = t1.w;
  12088. tangentArray[ offset_tangent + 4 ] = t2.x;
  12089. tangentArray[ offset_tangent + 5 ] = t2.y;
  12090. tangentArray[ offset_tangent + 6 ] = t2.z;
  12091. tangentArray[ offset_tangent + 7 ] = t2.w;
  12092. tangentArray[ offset_tangent + 8 ] = t3.x;
  12093. tangentArray[ offset_tangent + 9 ] = t3.y;
  12094. tangentArray[ offset_tangent + 10 ] = t3.z;
  12095. tangentArray[ offset_tangent + 11 ] = t3.w;
  12096. tangentArray[ offset_tangent + 12 ] = t4.x;
  12097. tangentArray[ offset_tangent + 13 ] = t4.y;
  12098. tangentArray[ offset_tangent + 14 ] = t4.z;
  12099. tangentArray[ offset_tangent + 15 ] = t4.w;
  12100. offset_tangent += 16;
  12101. }
  12102. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12103. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12104. }
  12105. if ( dirtyNormals && normalType ) {
  12106. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12107. face = obj_faces[ chunk_faces3[ f ] ];
  12108. vertexNormals = face.vertexNormals;
  12109. faceNormal = face.normal;
  12110. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12111. for ( i = 0; i < 3; i ++ ) {
  12112. vn = vertexNormals[ i ];
  12113. normalArray[ offset_normal ] = vn.x;
  12114. normalArray[ offset_normal + 1 ] = vn.y;
  12115. normalArray[ offset_normal + 2 ] = vn.z;
  12116. offset_normal += 3;
  12117. }
  12118. } else {
  12119. for ( i = 0; i < 3; i ++ ) {
  12120. normalArray[ offset_normal ] = faceNormal.x;
  12121. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12122. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12123. offset_normal += 3;
  12124. }
  12125. }
  12126. }
  12127. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12128. face = obj_faces[ chunk_faces4[ f ] ];
  12129. vertexNormals = face.vertexNormals;
  12130. faceNormal = face.normal;
  12131. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12132. for ( i = 0; i < 4; i ++ ) {
  12133. vn = vertexNormals[ i ];
  12134. normalArray[ offset_normal ] = vn.x;
  12135. normalArray[ offset_normal + 1 ] = vn.y;
  12136. normalArray[ offset_normal + 2 ] = vn.z;
  12137. offset_normal += 3;
  12138. }
  12139. } else {
  12140. for ( i = 0; i < 4; i ++ ) {
  12141. normalArray[ offset_normal ] = faceNormal.x;
  12142. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12143. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12144. offset_normal += 3;
  12145. }
  12146. }
  12147. }
  12148. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12149. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12150. }
  12151. if ( dirtyUvs && obj_uvs && uvType ) {
  12152. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12153. fi = chunk_faces3[ f ];
  12154. uv = obj_uvs[ fi ];
  12155. if ( uv === undefined ) continue;
  12156. for ( i = 0; i < 3; i ++ ) {
  12157. uvi = uv[ i ];
  12158. uvArray[ offset_uv ] = uvi.x;
  12159. uvArray[ offset_uv + 1 ] = uvi.y;
  12160. offset_uv += 2;
  12161. }
  12162. }
  12163. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12164. fi = chunk_faces4[ f ];
  12165. uv = obj_uvs[ fi ];
  12166. if ( uv === undefined ) continue;
  12167. for ( i = 0; i < 4; i ++ ) {
  12168. uvi = uv[ i ];
  12169. uvArray[ offset_uv ] = uvi.x;
  12170. uvArray[ offset_uv + 1 ] = uvi.y;
  12171. offset_uv += 2;
  12172. }
  12173. }
  12174. if ( offset_uv > 0 ) {
  12175. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12176. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12177. }
  12178. }
  12179. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12180. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12181. fi = chunk_faces3[ f ];
  12182. uv2 = obj_uvs2[ fi ];
  12183. if ( uv2 === undefined ) continue;
  12184. for ( i = 0; i < 3; i ++ ) {
  12185. uv2i = uv2[ i ];
  12186. uv2Array[ offset_uv2 ] = uv2i.x;
  12187. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12188. offset_uv2 += 2;
  12189. }
  12190. }
  12191. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12192. fi = chunk_faces4[ f ];
  12193. uv2 = obj_uvs2[ fi ];
  12194. if ( uv2 === undefined ) continue;
  12195. for ( i = 0; i < 4; i ++ ) {
  12196. uv2i = uv2[ i ];
  12197. uv2Array[ offset_uv2 ] = uv2i.x;
  12198. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12199. offset_uv2 += 2;
  12200. }
  12201. }
  12202. if ( offset_uv2 > 0 ) {
  12203. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12204. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12205. }
  12206. }
  12207. if ( dirtyElements ) {
  12208. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12209. faceArray[ offset_face ] = vertexIndex;
  12210. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12211. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12212. offset_face += 3;
  12213. lineArray[ offset_line ] = vertexIndex;
  12214. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12215. lineArray[ offset_line + 2 ] = vertexIndex;
  12216. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12217. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12218. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12219. offset_line += 6;
  12220. vertexIndex += 3;
  12221. }
  12222. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12223. faceArray[ offset_face ] = vertexIndex;
  12224. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12225. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12226. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12227. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12228. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12229. offset_face += 6;
  12230. lineArray[ offset_line ] = vertexIndex;
  12231. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12232. lineArray[ offset_line + 2 ] = vertexIndex;
  12233. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12234. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12235. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12236. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12237. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12238. offset_line += 8;
  12239. vertexIndex += 4;
  12240. }
  12241. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12242. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12243. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12244. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12245. }
  12246. if ( customAttributes ) {
  12247. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12248. customAttribute = customAttributes[ i ];
  12249. if ( ! customAttribute.__original.needsUpdate ) continue;
  12250. offset_custom = 0;
  12251. offset_customSrc = 0;
  12252. if ( customAttribute.size === 1 ) {
  12253. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12254. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12255. face = obj_faces[ chunk_faces3[ f ] ];
  12256. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12257. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12258. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12259. offset_custom += 3;
  12260. }
  12261. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12262. face = obj_faces[ chunk_faces4[ f ] ];
  12263. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12264. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12265. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12266. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12267. offset_custom += 4;
  12268. }
  12269. } else if ( customAttribute.boundTo === "faces" ) {
  12270. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12271. value = customAttribute.value[ chunk_faces3[ f ] ];
  12272. customAttribute.array[ offset_custom ] = value;
  12273. customAttribute.array[ offset_custom + 1 ] = value;
  12274. customAttribute.array[ offset_custom + 2 ] = value;
  12275. offset_custom += 3;
  12276. }
  12277. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12278. value = customAttribute.value[ chunk_faces4[ f ] ];
  12279. customAttribute.array[ offset_custom ] = value;
  12280. customAttribute.array[ offset_custom + 1 ] = value;
  12281. customAttribute.array[ offset_custom + 2 ] = value;
  12282. customAttribute.array[ offset_custom + 3 ] = value;
  12283. offset_custom += 4;
  12284. }
  12285. }
  12286. } else if ( customAttribute.size === 2 ) {
  12287. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12288. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12289. face = obj_faces[ chunk_faces3[ f ] ];
  12290. v1 = customAttribute.value[ face.a ];
  12291. v2 = customAttribute.value[ face.b ];
  12292. v3 = customAttribute.value[ face.c ];
  12293. customAttribute.array[ offset_custom ] = v1.x;
  12294. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12295. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12296. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12297. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12298. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12299. offset_custom += 6;
  12300. }
  12301. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12302. face = obj_faces[ chunk_faces4[ f ] ];
  12303. v1 = customAttribute.value[ face.a ];
  12304. v2 = customAttribute.value[ face.b ];
  12305. v3 = customAttribute.value[ face.c ];
  12306. v4 = customAttribute.value[ face.d ];
  12307. customAttribute.array[ offset_custom ] = v1.x;
  12308. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12309. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12310. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12311. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12312. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12313. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12314. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12315. offset_custom += 8;
  12316. }
  12317. } else if ( customAttribute.boundTo === "faces" ) {
  12318. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12319. value = customAttribute.value[ chunk_faces3[ f ] ];
  12320. v1 = value;
  12321. v2 = value;
  12322. v3 = value;
  12323. customAttribute.array[ offset_custom ] = v1.x;
  12324. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12325. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12326. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12327. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12328. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12329. offset_custom += 6;
  12330. }
  12331. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12332. value = customAttribute.value[ chunk_faces4[ f ] ];
  12333. v1 = value;
  12334. v2 = value;
  12335. v3 = value;
  12336. v4 = value;
  12337. customAttribute.array[ offset_custom ] = v1.x;
  12338. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12339. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12340. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12341. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12342. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12343. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12344. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12345. offset_custom += 8;
  12346. }
  12347. }
  12348. } else if ( customAttribute.size === 3 ) {
  12349. var pp;
  12350. if ( customAttribute.type === "c" ) {
  12351. pp = [ "r", "g", "b" ];
  12352. } else {
  12353. pp = [ "x", "y", "z" ];
  12354. }
  12355. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12356. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12357. face = obj_faces[ chunk_faces3[ f ] ];
  12358. v1 = customAttribute.value[ face.a ];
  12359. v2 = customAttribute.value[ face.b ];
  12360. v3 = customAttribute.value[ face.c ];
  12361. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12362. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12363. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12364. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12365. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12366. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12367. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12368. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12369. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12370. offset_custom += 9;
  12371. }
  12372. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12373. face = obj_faces[ chunk_faces4[ f ] ];
  12374. v1 = customAttribute.value[ face.a ];
  12375. v2 = customAttribute.value[ face.b ];
  12376. v3 = customAttribute.value[ face.c ];
  12377. v4 = customAttribute.value[ face.d ];
  12378. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12379. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12380. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12381. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12382. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12383. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12384. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12385. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12386. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12387. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12388. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12389. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12390. offset_custom += 12;
  12391. }
  12392. } else if ( customAttribute.boundTo === "faces" ) {
  12393. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12394. value = customAttribute.value[ chunk_faces3[ f ] ];
  12395. v1 = value;
  12396. v2 = value;
  12397. v3 = value;
  12398. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12399. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12400. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12401. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12402. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12403. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12404. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12405. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12406. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12407. offset_custom += 9;
  12408. }
  12409. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12410. value = customAttribute.value[ chunk_faces4[ f ] ];
  12411. v1 = value;
  12412. v2 = value;
  12413. v3 = value;
  12414. v4 = value;
  12415. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12416. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12417. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12418. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12419. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12420. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12421. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12422. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12423. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12424. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12425. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12426. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12427. offset_custom += 12;
  12428. }
  12429. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12430. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12431. value = customAttribute.value[ chunk_faces3[ f ] ];
  12432. v1 = value[ 0 ];
  12433. v2 = value[ 1 ];
  12434. v3 = value[ 2 ];
  12435. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12436. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12437. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12438. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12439. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12440. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12441. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12442. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12443. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12444. offset_custom += 9;
  12445. }
  12446. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12447. value = customAttribute.value[ chunk_faces4[ f ] ];
  12448. v1 = value[ 0 ];
  12449. v2 = value[ 1 ];
  12450. v3 = value[ 2 ];
  12451. v4 = value[ 3 ];
  12452. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12453. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12454. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12455. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12456. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12457. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12458. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12459. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12460. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12461. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12462. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12463. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12464. offset_custom += 12;
  12465. }
  12466. }
  12467. } else if ( customAttribute.size === 4 ) {
  12468. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12469. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12470. face = obj_faces[ chunk_faces3[ f ] ];
  12471. v1 = customAttribute.value[ face.a ];
  12472. v2 = customAttribute.value[ face.b ];
  12473. v3 = customAttribute.value[ face.c ];
  12474. customAttribute.array[ offset_custom ] = v1.x;
  12475. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12476. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12477. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12478. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12479. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12480. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12481. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12482. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12483. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12484. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12485. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12486. offset_custom += 12;
  12487. }
  12488. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12489. face = obj_faces[ chunk_faces4[ f ] ];
  12490. v1 = customAttribute.value[ face.a ];
  12491. v2 = customAttribute.value[ face.b ];
  12492. v3 = customAttribute.value[ face.c ];
  12493. v4 = customAttribute.value[ face.d ];
  12494. customAttribute.array[ offset_custom ] = v1.x;
  12495. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12496. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12497. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12498. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12499. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12500. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12501. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12502. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12503. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12504. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12505. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12506. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12507. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12508. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12509. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12510. offset_custom += 16;
  12511. }
  12512. } else if ( customAttribute.boundTo === "faces" ) {
  12513. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12514. value = customAttribute.value[ chunk_faces3[ f ] ];
  12515. v1 = value;
  12516. v2 = value;
  12517. v3 = value;
  12518. customAttribute.array[ offset_custom ] = v1.x;
  12519. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12520. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12521. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12522. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12523. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12524. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12525. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12526. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12527. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12528. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12529. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12530. offset_custom += 12;
  12531. }
  12532. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12533. value = customAttribute.value[ chunk_faces4[ f ] ];
  12534. v1 = value;
  12535. v2 = value;
  12536. v3 = value;
  12537. v4 = value;
  12538. customAttribute.array[ offset_custom ] = v1.x;
  12539. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12540. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12541. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12542. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12543. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12544. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12545. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12546. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12547. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12548. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12549. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12550. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12551. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12552. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12553. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12554. offset_custom += 16;
  12555. }
  12556. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12557. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12558. value = customAttribute.value[ chunk_faces3[ f ] ];
  12559. v1 = value[ 0 ];
  12560. v2 = value[ 1 ];
  12561. v3 = value[ 2 ];
  12562. customAttribute.array[ offset_custom ] = v1.x;
  12563. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12564. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12565. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12566. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12567. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12568. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12569. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12570. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12571. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12572. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12573. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12574. offset_custom += 12;
  12575. }
  12576. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12577. value = customAttribute.value[ chunk_faces4[ f ] ];
  12578. v1 = value[ 0 ];
  12579. v2 = value[ 1 ];
  12580. v3 = value[ 2 ];
  12581. v4 = value[ 3 ];
  12582. customAttribute.array[ offset_custom ] = v1.x;
  12583. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12584. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12585. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12586. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12587. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12588. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12589. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12590. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12591. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12592. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12593. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12594. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12595. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12596. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12597. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12598. offset_custom += 16;
  12599. }
  12600. }
  12601. }
  12602. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12603. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12604. }
  12605. }
  12606. if ( dispose ) {
  12607. delete geometryGroup.__inittedArrays;
  12608. delete geometryGroup.__colorArray;
  12609. delete geometryGroup.__normalArray;
  12610. delete geometryGroup.__tangentArray;
  12611. delete geometryGroup.__uvArray;
  12612. delete geometryGroup.__uv2Array;
  12613. delete geometryGroup.__faceArray;
  12614. delete geometryGroup.__vertexArray;
  12615. delete geometryGroup.__lineArray;
  12616. delete geometryGroup.__skinIndexArray;
  12617. delete geometryGroup.__skinWeightArray;
  12618. }
  12619. };
  12620. function setDirectBuffers ( geometry, hint, dispose ) {
  12621. var attributes = geometry.attributes;
  12622. var index = attributes[ "index" ];
  12623. var position = attributes[ "position" ];
  12624. var normal = attributes[ "normal" ];
  12625. var uv = attributes[ "uv" ];
  12626. var color = attributes[ "color" ];
  12627. var tangent = attributes[ "tangent" ];
  12628. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12629. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12630. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12631. }
  12632. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12633. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12634. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12635. }
  12636. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12637. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12638. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12639. }
  12640. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12641. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12642. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12643. }
  12644. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12645. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12646. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12647. }
  12648. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12649. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12650. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12651. }
  12652. if ( dispose ) {
  12653. for ( var i in geometry.attributes ) {
  12654. delete geometry.attributes[ i ].array;
  12655. }
  12656. }
  12657. };
  12658. // Buffer rendering
  12659. this.renderBufferImmediate = function ( object, program, material ) {
  12660. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12661. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12662. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12663. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12664. if ( object.hasPositions ) {
  12665. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12666. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12667. _gl.enableVertexAttribArray( program.attributes.position );
  12668. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12669. }
  12670. if ( object.hasNormals ) {
  12671. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12672. if ( material.shading === THREE.FlatShading ) {
  12673. var nx, ny, nz,
  12674. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12675. normalArray,
  12676. i, il = object.count * 3;
  12677. for( i = 0; i < il; i += 9 ) {
  12678. normalArray = object.normalArray;
  12679. nax = normalArray[ i ];
  12680. nay = normalArray[ i + 1 ];
  12681. naz = normalArray[ i + 2 ];
  12682. nbx = normalArray[ i + 3 ];
  12683. nby = normalArray[ i + 4 ];
  12684. nbz = normalArray[ i + 5 ];
  12685. ncx = normalArray[ i + 6 ];
  12686. ncy = normalArray[ i + 7 ];
  12687. ncz = normalArray[ i + 8 ];
  12688. nx = ( nax + nbx + ncx ) / 3;
  12689. ny = ( nay + nby + ncy ) / 3;
  12690. nz = ( naz + nbz + ncz ) / 3;
  12691. normalArray[ i ] = nx;
  12692. normalArray[ i + 1 ] = ny;
  12693. normalArray[ i + 2 ] = nz;
  12694. normalArray[ i + 3 ] = nx;
  12695. normalArray[ i + 4 ] = ny;
  12696. normalArray[ i + 5 ] = nz;
  12697. normalArray[ i + 6 ] = nx;
  12698. normalArray[ i + 7 ] = ny;
  12699. normalArray[ i + 8 ] = nz;
  12700. }
  12701. }
  12702. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12703. _gl.enableVertexAttribArray( program.attributes.normal );
  12704. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12705. }
  12706. if ( object.hasUvs && material.map ) {
  12707. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12708. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12709. _gl.enableVertexAttribArray( program.attributes.uv );
  12710. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12711. }
  12712. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12713. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12714. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12715. _gl.enableVertexAttribArray( program.attributes.color );
  12716. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12717. }
  12718. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12719. object.count = 0;
  12720. };
  12721. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12722. if ( material.visible === false ) return;
  12723. var program, attributes, linewidth, primitives, a, attribute;
  12724. program = setProgram( camera, lights, fog, material, object );
  12725. attributes = program.attributes;
  12726. var updateBuffers = false,
  12727. wireframeBit = material.wireframe ? 1 : 0,
  12728. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12729. if ( geometryHash !== _currentGeometryGroupHash ) {
  12730. _currentGeometryGroupHash = geometryHash;
  12731. updateBuffers = true;
  12732. }
  12733. if ( updateBuffers ) {
  12734. disableAttributes();
  12735. }
  12736. // render mesh
  12737. if ( object instanceof THREE.Mesh ) {
  12738. var index = geometry.attributes[ "index" ];
  12739. // indexed triangles
  12740. if ( index ) {
  12741. var offsets = geometry.offsets;
  12742. // if there is more than 1 chunk
  12743. // must set attribute pointers to use new offsets for each chunk
  12744. // even if geometry and materials didn't change
  12745. if ( offsets.length > 1 ) updateBuffers = true;
  12746. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12747. var startIndex = offsets[ i ].index;
  12748. if ( updateBuffers ) {
  12749. // vertices
  12750. var position = geometry.attributes[ "position" ];
  12751. var positionSize = position.itemSize;
  12752. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12753. enableAttribute( attributes.position );
  12754. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12755. // normals
  12756. var normal = geometry.attributes[ "normal" ];
  12757. if ( attributes.normal >= 0 && normal ) {
  12758. var normalSize = normal.itemSize;
  12759. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12760. enableAttribute( attributes.normal );
  12761. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12762. }
  12763. // uvs
  12764. var uv = geometry.attributes[ "uv" ];
  12765. if ( attributes.uv >= 0 && uv ) {
  12766. var uvSize = uv.itemSize;
  12767. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12768. enableAttribute( attributes.uv );
  12769. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12770. }
  12771. // colors
  12772. var color = geometry.attributes[ "color" ];
  12773. if ( attributes.color >= 0 && color ) {
  12774. var colorSize = color.itemSize;
  12775. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12776. enableAttribute( attributes.color );
  12777. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12778. }
  12779. // tangents
  12780. var tangent = geometry.attributes[ "tangent" ];
  12781. if ( attributes.tangent >= 0 && tangent ) {
  12782. var tangentSize = tangent.itemSize;
  12783. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12784. enableAttribute( attributes.tangent );
  12785. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12786. }
  12787. // indices
  12788. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12789. }
  12790. // render indexed triangles
  12791. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12792. _this.info.render.calls ++;
  12793. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12794. _this.info.render.faces += offsets[ i ].count / 3;
  12795. }
  12796. // non-indexed triangles
  12797. } else {
  12798. if ( updateBuffers ) {
  12799. // vertices
  12800. var position = geometry.attributes[ "position" ];
  12801. var positionSize = position.itemSize;
  12802. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12803. enableAttribute( attributes.position );
  12804. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12805. // normals
  12806. var normal = geometry.attributes[ "normal" ];
  12807. if ( attributes.normal >= 0 && normal ) {
  12808. var normalSize = normal.itemSize;
  12809. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12810. enableAttribute( attributes.normal );
  12811. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12812. }
  12813. // uvs
  12814. var uv = geometry.attributes[ "uv" ];
  12815. if ( attributes.uv >= 0 && uv ) {
  12816. var uvSize = uv.itemSize;
  12817. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12818. enableAttribute( attributes.uv );
  12819. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12820. }
  12821. // colors
  12822. var color = geometry.attributes[ "color" ];
  12823. if ( attributes.color >= 0 && color ) {
  12824. var colorSize = color.itemSize;
  12825. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12826. enableAttribute( attributes.color );
  12827. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12828. }
  12829. // tangents
  12830. var tangent = geometry.attributes[ "tangent" ];
  12831. if ( attributes.tangent >= 0 && tangent ) {
  12832. var tangentSize = tangent.itemSize;
  12833. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12834. enableAttribute( attributes.tangent );
  12835. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12836. }
  12837. }
  12838. // render non-indexed triangles
  12839. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12840. _this.info.render.calls ++;
  12841. _this.info.render.vertices += position.numItems / 3;
  12842. _this.info.render.faces += position.numItems / 3 / 3;
  12843. }
  12844. // render particles
  12845. } else if ( object instanceof THREE.ParticleSystem ) {
  12846. if ( updateBuffers ) {
  12847. // vertices
  12848. var position = geometry.attributes[ "position" ];
  12849. var positionSize = position.itemSize;
  12850. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12851. enableAttribute( attributes.position );
  12852. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12853. // colors
  12854. var color = geometry.attributes[ "color" ];
  12855. if ( attributes.color >= 0 && color ) {
  12856. var colorSize = color.itemSize;
  12857. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12858. enableAttribute( attributes.color );
  12859. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12860. }
  12861. // render particles
  12862. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12863. _this.info.render.calls ++;
  12864. _this.info.render.points += position.numItems / 3;
  12865. }
  12866. } else if ( object instanceof THREE.Line ) {
  12867. if ( updateBuffers ) {
  12868. // vertices
  12869. var position = geometry.attributes[ "position" ];
  12870. var positionSize = position.itemSize;
  12871. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12872. enableAttribute( attributes.position );
  12873. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12874. // colors
  12875. var color = geometry.attributes[ "color" ];
  12876. if ( attributes.color >= 0 && color ) {
  12877. var colorSize = color.itemSize;
  12878. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12879. enableAttribute( attributes.color );
  12880. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12881. }
  12882. // render lines
  12883. setLineWidth( material.linewidth );
  12884. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12885. _this.info.render.calls ++;
  12886. _this.info.render.points += position.numItems;
  12887. }
  12888. }
  12889. };
  12890. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12891. if ( material.visible === false ) return;
  12892. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12893. program = setProgram( camera, lights, fog, material, object );
  12894. attributes = program.attributes;
  12895. var updateBuffers = false,
  12896. wireframeBit = material.wireframe ? 1 : 0,
  12897. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12898. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12899. _currentGeometryGroupHash = geometryGroupHash;
  12900. updateBuffers = true;
  12901. }
  12902. if ( updateBuffers ) {
  12903. disableAttributes();
  12904. }
  12905. // vertices
  12906. if ( !material.morphTargets && attributes.position >= 0 ) {
  12907. if ( updateBuffers ) {
  12908. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12909. enableAttribute( attributes.position );
  12910. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12911. }
  12912. } else {
  12913. if ( object.morphTargetBase ) {
  12914. setupMorphTargets( material, geometryGroup, object );
  12915. }
  12916. }
  12917. if ( updateBuffers ) {
  12918. // custom attributes
  12919. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12920. if ( geometryGroup.__webglCustomAttributesList ) {
  12921. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12922. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12923. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12924. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12925. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12926. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12927. }
  12928. }
  12929. }
  12930. // colors
  12931. if ( attributes.color >= 0 ) {
  12932. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12933. enableAttribute( attributes.color );
  12934. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12935. }
  12936. // normals
  12937. if ( attributes.normal >= 0 ) {
  12938. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12939. enableAttribute( attributes.normal );
  12940. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12941. }
  12942. // tangents
  12943. if ( attributes.tangent >= 0 ) {
  12944. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12945. enableAttribute( attributes.tangent );
  12946. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12947. }
  12948. // uvs
  12949. if ( attributes.uv >= 0 ) {
  12950. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12951. enableAttribute( attributes.uv );
  12952. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12953. }
  12954. if ( attributes.uv2 >= 0 ) {
  12955. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12956. enableAttribute( attributes.uv2 );
  12957. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12958. }
  12959. if ( material.skinning &&
  12960. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12961. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12962. enableAttribute( attributes.skinIndex );
  12963. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12964. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12965. enableAttribute( attributes.skinWeight );
  12966. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12967. }
  12968. // line distances
  12969. if ( attributes.lineDistance >= 0 ) {
  12970. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12971. enableAttribute( attributes.lineDistance );
  12972. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12973. }
  12974. }
  12975. // render mesh
  12976. if ( object instanceof THREE.Mesh ) {
  12977. // wireframe
  12978. if ( material.wireframe ) {
  12979. setLineWidth( material.wireframeLinewidth );
  12980. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12981. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12982. // triangles
  12983. } else {
  12984. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12985. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12986. }
  12987. _this.info.render.calls ++;
  12988. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12989. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12990. // render lines
  12991. } else if ( object instanceof THREE.Line ) {
  12992. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12993. setLineWidth( material.linewidth );
  12994. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12995. _this.info.render.calls ++;
  12996. // render particles
  12997. } else if ( object instanceof THREE.ParticleSystem ) {
  12998. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12999. _this.info.render.calls ++;
  13000. _this.info.render.points += geometryGroup.__webglParticleCount;
  13001. // render ribbon
  13002. } else if ( object instanceof THREE.Ribbon ) {
  13003. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13004. _this.info.render.calls ++;
  13005. }
  13006. };
  13007. function enableAttribute( attribute ) {
  13008. if ( ! _enabledAttributes[ attribute ] ) {
  13009. _gl.enableVertexAttribArray( attribute );
  13010. _enabledAttributes[ attribute ] = true;
  13011. }
  13012. };
  13013. function disableAttributes() {
  13014. for ( var attribute in _enabledAttributes ) {
  13015. if ( _enabledAttributes[ attribute ] ) {
  13016. _gl.disableVertexAttribArray( attribute );
  13017. _enabledAttributes[ attribute ] = false;
  13018. }
  13019. }
  13020. };
  13021. function setupMorphTargets ( material, geometryGroup, object ) {
  13022. // set base
  13023. var attributes = material.program.attributes;
  13024. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13025. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13026. enableAttribute( attributes.position );
  13027. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13028. } else if ( attributes.position >= 0 ) {
  13029. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13030. enableAttribute( attributes.position );
  13031. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13032. }
  13033. if ( object.morphTargetForcedOrder.length ) {
  13034. // set forced order
  13035. var m = 0;
  13036. var order = object.morphTargetForcedOrder;
  13037. var influences = object.morphTargetInfluences;
  13038. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13039. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13040. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13041. enableAttribute( attributes[ "morphTarget" + m ] );
  13042. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13043. }
  13044. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13045. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13046. enableAttribute( attributes[ "morphNormal" + m ] );
  13047. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13048. }
  13049. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13050. m ++;
  13051. }
  13052. } else {
  13053. // find the most influencing
  13054. var influence, activeInfluenceIndices = [];
  13055. var influences = object.morphTargetInfluences;
  13056. var i, il = influences.length;
  13057. for ( i = 0; i < il; i ++ ) {
  13058. influence = influences[ i ];
  13059. if ( influence > 0 ) {
  13060. activeInfluenceIndices.push( [ influence, i ] );
  13061. }
  13062. }
  13063. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13064. activeInfluenceIndices.sort( numericalSort );
  13065. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13066. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13067. activeInfluenceIndices.sort( numericalSort );
  13068. } else if ( activeInfluenceIndices.length === 0 ) {
  13069. activeInfluenceIndices.push( [ 0, 0 ] );
  13070. };
  13071. var influenceIndex, m = 0;
  13072. while ( m < material.numSupportedMorphTargets ) {
  13073. if ( activeInfluenceIndices[ m ] ) {
  13074. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13075. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13076. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13077. enableAttribute( attributes[ "morphTarget" + m ] );
  13078. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13079. }
  13080. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13082. enableAttribute( attributes[ "morphNormal" + m ] );
  13083. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13084. }
  13085. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13086. } else {
  13087. /*
  13088. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13089. if ( material.morphNormals ) {
  13090. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13091. }
  13092. */
  13093. object.__webglMorphTargetInfluences[ m ] = 0;
  13094. }
  13095. m ++;
  13096. }
  13097. }
  13098. // load updated influences uniform
  13099. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13100. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13101. }
  13102. };
  13103. // Sorting
  13104. function painterSortStable ( a, b ) {
  13105. if ( a.z !== b.z ) {
  13106. return b.z - a.z;
  13107. } else {
  13108. return b.id - a.id;
  13109. }
  13110. };
  13111. function numericalSort ( a, b ) {
  13112. return b[ 0 ] - a[ 0 ];
  13113. };
  13114. // Rendering
  13115. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13116. if ( camera instanceof THREE.Camera === false ) {
  13117. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13118. return;
  13119. }
  13120. var i, il,
  13121. webglObject, object,
  13122. renderList,
  13123. lights = scene.__lights,
  13124. fog = scene.fog;
  13125. // reset caching for this frame
  13126. _currentMaterialId = -1;
  13127. _lightsNeedUpdate = true;
  13128. // update scene graph
  13129. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  13130. // update camera matrices and frustum
  13131. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13132. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13133. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13134. _frustum.setFromMatrix( _projScreenMatrix );
  13135. // update WebGL objects
  13136. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13137. // custom render plugins (pre pass)
  13138. renderPlugins( this.renderPluginsPre, scene, camera );
  13139. //
  13140. _this.info.render.calls = 0;
  13141. _this.info.render.vertices = 0;
  13142. _this.info.render.faces = 0;
  13143. _this.info.render.points = 0;
  13144. this.setRenderTarget( renderTarget );
  13145. if ( this.autoClear || forceClear ) {
  13146. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13147. }
  13148. // set matrices for regular objects (frustum culled)
  13149. renderList = scene.__webglObjects;
  13150. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13151. webglObject = renderList[ i ];
  13152. object = webglObject.object;
  13153. webglObject.render = false;
  13154. if ( object.visible ) {
  13155. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13156. setupMatrices( object, camera );
  13157. unrollBufferMaterial( webglObject );
  13158. webglObject.render = true;
  13159. if ( this.sortObjects === true ) {
  13160. if ( object.renderDepth !== null ) {
  13161. webglObject.z = object.renderDepth;
  13162. } else {
  13163. _vector3.getPositionFromMatrix( object.matrixWorld );
  13164. _vector3.applyProjection( _projScreenMatrix );
  13165. webglObject.z = _vector3.z;
  13166. }
  13167. webglObject.id = object.id;
  13168. }
  13169. }
  13170. }
  13171. }
  13172. if ( this.sortObjects ) {
  13173. renderList.sort( painterSortStable );
  13174. }
  13175. // set matrices for immediate objects
  13176. renderList = scene.__webglObjectsImmediate;
  13177. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13178. webglObject = renderList[ i ];
  13179. object = webglObject.object;
  13180. if ( object.visible ) {
  13181. setupMatrices( object, camera );
  13182. unrollImmediateBufferMaterial( webglObject );
  13183. }
  13184. }
  13185. if ( scene.overrideMaterial ) {
  13186. var material = scene.overrideMaterial;
  13187. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13188. this.setDepthTest( material.depthTest );
  13189. this.setDepthWrite( material.depthWrite );
  13190. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13191. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13192. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13193. } else {
  13194. var material = null;
  13195. // opaque pass (front-to-back order)
  13196. this.setBlending( THREE.NoBlending );
  13197. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13198. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13199. // transparent pass (back-to-front order)
  13200. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13201. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13202. }
  13203. // custom render plugins (post pass)
  13204. renderPlugins( this.renderPluginsPost, scene, camera );
  13205. // Generate mipmap if we're using any kind of mipmap filtering
  13206. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13207. updateRenderTargetMipmap( renderTarget );
  13208. }
  13209. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13210. this.setDepthTest( true );
  13211. this.setDepthWrite( true );
  13212. // _gl.finish();
  13213. };
  13214. function renderPlugins( plugins, scene, camera ) {
  13215. if ( ! plugins.length ) return;
  13216. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13217. // reset state for plugin (to start from clean slate)
  13218. _currentProgram = null;
  13219. _currentCamera = null;
  13220. _oldBlending = -1;
  13221. _oldDepthTest = -1;
  13222. _oldDepthWrite = -1;
  13223. _oldDoubleSided = -1;
  13224. _oldFlipSided = -1;
  13225. _currentGeometryGroupHash = -1;
  13226. _currentMaterialId = -1;
  13227. _lightsNeedUpdate = true;
  13228. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13229. // reset state after plugin (anything could have changed)
  13230. _currentProgram = null;
  13231. _currentCamera = null;
  13232. _oldBlending = -1;
  13233. _oldDepthTest = -1;
  13234. _oldDepthWrite = -1;
  13235. _oldDoubleSided = -1;
  13236. _oldFlipSided = -1;
  13237. _currentGeometryGroupHash = -1;
  13238. _currentMaterialId = -1;
  13239. _lightsNeedUpdate = true;
  13240. }
  13241. };
  13242. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13243. var webglObject, object, buffer, material, start, end, delta;
  13244. if ( reverse ) {
  13245. start = renderList.length - 1;
  13246. end = -1;
  13247. delta = -1;
  13248. } else {
  13249. start = 0;
  13250. end = renderList.length;
  13251. delta = 1;
  13252. }
  13253. for ( var i = start; i !== end; i += delta ) {
  13254. webglObject = renderList[ i ];
  13255. if ( webglObject.render ) {
  13256. object = webglObject.object;
  13257. buffer = webglObject.buffer;
  13258. if ( overrideMaterial ) {
  13259. material = overrideMaterial;
  13260. } else {
  13261. material = webglObject[ materialType ];
  13262. if ( ! material ) continue;
  13263. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13264. _this.setDepthTest( material.depthTest );
  13265. _this.setDepthWrite( material.depthWrite );
  13266. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13267. }
  13268. _this.setMaterialFaces( material );
  13269. if ( buffer instanceof THREE.BufferGeometry ) {
  13270. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13271. } else {
  13272. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13273. }
  13274. }
  13275. }
  13276. };
  13277. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13278. var webglObject, object, material, program;
  13279. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13280. webglObject = renderList[ i ];
  13281. object = webglObject.object;
  13282. if ( object.visible ) {
  13283. if ( overrideMaterial ) {
  13284. material = overrideMaterial;
  13285. } else {
  13286. material = webglObject[ materialType ];
  13287. if ( ! material ) continue;
  13288. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13289. _this.setDepthTest( material.depthTest );
  13290. _this.setDepthWrite( material.depthWrite );
  13291. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13292. }
  13293. _this.renderImmediateObject( camera, lights, fog, material, object );
  13294. }
  13295. }
  13296. };
  13297. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13298. var program = setProgram( camera, lights, fog, material, object );
  13299. _currentGeometryGroupHash = -1;
  13300. _this.setMaterialFaces( material );
  13301. if ( object.immediateRenderCallback ) {
  13302. object.immediateRenderCallback( program, _gl, _frustum );
  13303. } else {
  13304. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13305. }
  13306. };
  13307. function unrollImmediateBufferMaterial ( globject ) {
  13308. var object = globject.object,
  13309. material = object.material;
  13310. if ( material.transparent ) {
  13311. globject.transparent = material;
  13312. globject.opaque = null;
  13313. } else {
  13314. globject.opaque = material;
  13315. globject.transparent = null;
  13316. }
  13317. };
  13318. function unrollBufferMaterial ( globject ) {
  13319. var object = globject.object,
  13320. buffer = globject.buffer,
  13321. material, materialIndex, meshMaterial;
  13322. meshMaterial = object.material;
  13323. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13324. materialIndex = buffer.materialIndex;
  13325. material = meshMaterial.materials[ materialIndex ];
  13326. if ( material.transparent ) {
  13327. globject.transparent = material;
  13328. globject.opaque = null;
  13329. } else {
  13330. globject.opaque = material;
  13331. globject.transparent = null;
  13332. }
  13333. } else {
  13334. material = meshMaterial;
  13335. if ( material ) {
  13336. if ( material.transparent ) {
  13337. globject.transparent = material;
  13338. globject.opaque = null;
  13339. } else {
  13340. globject.opaque = material;
  13341. globject.transparent = null;
  13342. }
  13343. }
  13344. }
  13345. };
  13346. // Geometry splitting
  13347. function sortFacesByMaterial ( geometry, material ) {
  13348. var f, fl, face, materialIndex, vertices,
  13349. groupHash, hash_map = {};
  13350. var numMorphTargets = geometry.morphTargets.length;
  13351. var numMorphNormals = geometry.morphNormals.length;
  13352. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13353. geometry.geometryGroups = {};
  13354. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13355. face = geometry.faces[ f ];
  13356. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13357. if ( hash_map[ materialIndex ] === undefined ) {
  13358. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13359. }
  13360. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13361. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13362. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13363. }
  13364. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13365. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13366. hash_map[ materialIndex ].counter += 1;
  13367. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13368. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13369. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13370. }
  13371. }
  13372. if ( face instanceof THREE.Face3 ) {
  13373. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13374. } else {
  13375. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13376. }
  13377. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13378. }
  13379. geometry.geometryGroupsList = [];
  13380. for ( var g in geometry.geometryGroups ) {
  13381. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13382. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13383. }
  13384. };
  13385. // Objects refresh
  13386. this.initWebGLObjects = function ( scene ) {
  13387. if ( !scene.__webglObjects ) {
  13388. scene.__webglObjects = [];
  13389. scene.__webglObjectsImmediate = [];
  13390. scene.__webglSprites = [];
  13391. scene.__webglFlares = [];
  13392. }
  13393. while ( scene.__objectsAdded.length ) {
  13394. addObject( scene.__objectsAdded[ 0 ], scene );
  13395. scene.__objectsAdded.splice( 0, 1 );
  13396. }
  13397. while ( scene.__objectsRemoved.length ) {
  13398. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13399. scene.__objectsRemoved.splice( 0, 1 );
  13400. }
  13401. // update must be called after objects adding / removal
  13402. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13403. updateObject( scene.__webglObjects[ o ].object );
  13404. }
  13405. };
  13406. // Objects adding
  13407. function addObject ( object, scene ) {
  13408. var g, geometry, material, geometryGroup;
  13409. if ( ! object.__webglInit ) {
  13410. object.__webglInit = true;
  13411. object._modelViewMatrix = new THREE.Matrix4();
  13412. object._normalMatrix = new THREE.Matrix3();
  13413. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13414. object.geometry.__webglInit = true;
  13415. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13416. }
  13417. if ( object instanceof THREE.Mesh ) {
  13418. geometry = object.geometry;
  13419. material = object.material;
  13420. if ( geometry instanceof THREE.Geometry ) {
  13421. if ( geometry.geometryGroups === undefined ) {
  13422. sortFacesByMaterial( geometry, material );
  13423. }
  13424. // create separate VBOs per geometry chunk
  13425. for ( g in geometry.geometryGroups ) {
  13426. geometryGroup = geometry.geometryGroups[ g ];
  13427. // initialise VBO on the first access
  13428. if ( ! geometryGroup.__webglVertexBuffer ) {
  13429. createMeshBuffers( geometryGroup );
  13430. initMeshBuffers( geometryGroup, object );
  13431. geometry.verticesNeedUpdate = true;
  13432. geometry.morphTargetsNeedUpdate = true;
  13433. geometry.elementsNeedUpdate = true;
  13434. geometry.uvsNeedUpdate = true;
  13435. geometry.normalsNeedUpdate = true;
  13436. geometry.tangentsNeedUpdate = true;
  13437. geometry.colorsNeedUpdate = true;
  13438. }
  13439. }
  13440. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13441. initDirectBuffers( geometry );
  13442. }
  13443. } else if ( object instanceof THREE.Ribbon ) {
  13444. geometry = object.geometry;
  13445. if ( ! geometry.__webglVertexBuffer ) {
  13446. createRibbonBuffers( geometry );
  13447. initRibbonBuffers( geometry, object );
  13448. geometry.verticesNeedUpdate = true;
  13449. geometry.colorsNeedUpdate = true;
  13450. geometry.normalsNeedUpdate = true;
  13451. }
  13452. } else if ( object instanceof THREE.Line ) {
  13453. geometry = object.geometry;
  13454. if ( ! geometry.__webglVertexBuffer ) {
  13455. if ( geometry instanceof THREE.Geometry ) {
  13456. createLineBuffers( geometry );
  13457. initLineBuffers( geometry, object );
  13458. geometry.verticesNeedUpdate = true;
  13459. geometry.colorsNeedUpdate = true;
  13460. geometry.lineDistancesNeedUpdate = true;
  13461. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13462. initDirectBuffers( geometry );
  13463. }
  13464. }
  13465. } else if ( object instanceof THREE.ParticleSystem ) {
  13466. geometry = object.geometry;
  13467. if ( ! geometry.__webglVertexBuffer ) {
  13468. if ( geometry instanceof THREE.Geometry ) {
  13469. createParticleBuffers( geometry );
  13470. initParticleBuffers( geometry, object );
  13471. geometry.verticesNeedUpdate = true;
  13472. geometry.colorsNeedUpdate = true;
  13473. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13474. initDirectBuffers( geometry );
  13475. }
  13476. }
  13477. }
  13478. }
  13479. if ( ! object.__webglActive ) {
  13480. if ( object instanceof THREE.Mesh ) {
  13481. geometry = object.geometry;
  13482. if ( geometry instanceof THREE.BufferGeometry ) {
  13483. addBuffer( scene.__webglObjects, geometry, object );
  13484. } else if ( geometry instanceof THREE.Geometry ) {
  13485. for ( g in geometry.geometryGroups ) {
  13486. geometryGroup = geometry.geometryGroups[ g ];
  13487. addBuffer( scene.__webglObjects, geometryGroup, object );
  13488. }
  13489. }
  13490. } else if ( object instanceof THREE.Ribbon ||
  13491. object instanceof THREE.Line ||
  13492. object instanceof THREE.ParticleSystem ) {
  13493. geometry = object.geometry;
  13494. addBuffer( scene.__webglObjects, geometry, object );
  13495. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13496. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13497. } else if ( object instanceof THREE.Sprite ) {
  13498. scene.__webglSprites.push( object );
  13499. } else if ( object instanceof THREE.LensFlare ) {
  13500. scene.__webglFlares.push( object );
  13501. }
  13502. object.__webglActive = true;
  13503. }
  13504. };
  13505. function addBuffer ( objlist, buffer, object ) {
  13506. objlist.push(
  13507. {
  13508. buffer: buffer,
  13509. object: object,
  13510. opaque: null,
  13511. transparent: null
  13512. }
  13513. );
  13514. };
  13515. function addBufferImmediate ( objlist, object ) {
  13516. objlist.push(
  13517. {
  13518. object: object,
  13519. opaque: null,
  13520. transparent: null
  13521. }
  13522. );
  13523. };
  13524. // Objects updates
  13525. function updateObject ( object ) {
  13526. var geometry = object.geometry,
  13527. geometryGroup, customAttributesDirty, material;
  13528. if ( object instanceof THREE.Mesh ) {
  13529. if ( geometry instanceof THREE.BufferGeometry ) {
  13530. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13531. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13532. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13533. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13534. }
  13535. geometry.verticesNeedUpdate = false;
  13536. geometry.elementsNeedUpdate = false;
  13537. geometry.uvsNeedUpdate = false;
  13538. geometry.normalsNeedUpdate = false;
  13539. geometry.colorsNeedUpdate = false;
  13540. geometry.tangentsNeedUpdate = false;
  13541. } else {
  13542. // check all geometry groups
  13543. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13544. geometryGroup = geometry.geometryGroupsList[ i ];
  13545. material = getBufferMaterial( object, geometryGroup );
  13546. if ( geometry.buffersNeedUpdate ) {
  13547. initMeshBuffers( geometryGroup, object );
  13548. }
  13549. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13550. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13551. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13552. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13553. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13554. }
  13555. }
  13556. geometry.verticesNeedUpdate = false;
  13557. geometry.morphTargetsNeedUpdate = false;
  13558. geometry.elementsNeedUpdate = false;
  13559. geometry.uvsNeedUpdate = false;
  13560. geometry.normalsNeedUpdate = false;
  13561. geometry.colorsNeedUpdate = false;
  13562. geometry.tangentsNeedUpdate = false;
  13563. geometry.buffersNeedUpdate = false;
  13564. material.attributes && clearCustomAttributes( material );
  13565. }
  13566. } else if ( object instanceof THREE.Ribbon ) {
  13567. material = getBufferMaterial( object, geometry );
  13568. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13569. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13570. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13571. }
  13572. geometry.verticesNeedUpdate = false;
  13573. geometry.colorsNeedUpdate = false;
  13574. geometry.normalsNeedUpdate = false;
  13575. material.attributes && clearCustomAttributes( material );
  13576. } else if ( object instanceof THREE.Line ) {
  13577. if ( geometry instanceof THREE.BufferGeometry ) {
  13578. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13579. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13580. }
  13581. geometry.verticesNeedUpdate = false;
  13582. geometry.colorsNeedUpdate = false;
  13583. } else {
  13584. material = getBufferMaterial( object, geometry );
  13585. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13586. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13587. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13588. }
  13589. geometry.verticesNeedUpdate = false;
  13590. geometry.colorsNeedUpdate = false;
  13591. geometry.lineDistancesNeedUpdate = false;
  13592. material.attributes && clearCustomAttributes( material );
  13593. }
  13594. } else if ( object instanceof THREE.ParticleSystem ) {
  13595. if ( geometry instanceof THREE.BufferGeometry ) {
  13596. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13597. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13598. }
  13599. geometry.verticesNeedUpdate = false;
  13600. geometry.colorsNeedUpdate = false;
  13601. } else {
  13602. material = getBufferMaterial( object, geometry );
  13603. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13604. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13605. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13606. }
  13607. geometry.verticesNeedUpdate = false;
  13608. geometry.colorsNeedUpdate = false;
  13609. material.attributes && clearCustomAttributes( material );
  13610. }
  13611. }
  13612. };
  13613. // Objects updates - custom attributes check
  13614. function areCustomAttributesDirty ( material ) {
  13615. for ( var a in material.attributes ) {
  13616. if ( material.attributes[ a ].needsUpdate ) return true;
  13617. }
  13618. return false;
  13619. };
  13620. function clearCustomAttributes ( material ) {
  13621. for ( var a in material.attributes ) {
  13622. material.attributes[ a ].needsUpdate = false;
  13623. }
  13624. };
  13625. // Objects removal
  13626. function removeObject ( object, scene ) {
  13627. if ( object instanceof THREE.Mesh ||
  13628. object instanceof THREE.ParticleSystem ||
  13629. object instanceof THREE.Ribbon ||
  13630. object instanceof THREE.Line ) {
  13631. removeInstances( scene.__webglObjects, object );
  13632. } else if ( object instanceof THREE.Sprite ) {
  13633. removeInstancesDirect( scene.__webglSprites, object );
  13634. } else if ( object instanceof THREE.LensFlare ) {
  13635. removeInstancesDirect( scene.__webglFlares, object );
  13636. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13637. removeInstances( scene.__webglObjectsImmediate, object );
  13638. }
  13639. object.__webglActive = false;
  13640. };
  13641. function removeInstances ( objlist, object ) {
  13642. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13643. if ( objlist[ o ].object === object ) {
  13644. objlist.splice( o, 1 );
  13645. }
  13646. }
  13647. };
  13648. function removeInstancesDirect ( objlist, object ) {
  13649. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13650. if ( objlist[ o ] === object ) {
  13651. objlist.splice( o, 1 );
  13652. }
  13653. }
  13654. };
  13655. // Materials
  13656. this.initMaterial = function ( material, lights, fog, object ) {
  13657. material.addEventListener( 'dispose', onMaterialDispose );
  13658. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13659. if ( material instanceof THREE.MeshDepthMaterial ) {
  13660. shaderID = 'depth';
  13661. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13662. shaderID = 'normal';
  13663. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13664. shaderID = 'basic';
  13665. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13666. shaderID = 'lambert';
  13667. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13668. shaderID = 'phong';
  13669. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13670. shaderID = 'basic';
  13671. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13672. shaderID = 'dashed';
  13673. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13674. shaderID = 'particle_basic';
  13675. }
  13676. if ( shaderID ) {
  13677. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13678. }
  13679. // heuristics to create shader parameters according to lights in the scene
  13680. // (not to blow over maxLights budget)
  13681. maxLightCount = allocateLights( lights );
  13682. maxShadows = allocateShadows( lights );
  13683. maxBones = allocateBones( object );
  13684. parameters = {
  13685. map: !!material.map,
  13686. envMap: !!material.envMap,
  13687. lightMap: !!material.lightMap,
  13688. bumpMap: !!material.bumpMap,
  13689. normalMap: !!material.normalMap,
  13690. specularMap: !!material.specularMap,
  13691. vertexColors: material.vertexColors,
  13692. fog: fog,
  13693. useFog: material.fog,
  13694. fogExp: fog instanceof THREE.FogExp2,
  13695. sizeAttenuation: material.sizeAttenuation,
  13696. skinning: material.skinning,
  13697. maxBones: maxBones,
  13698. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13699. boneTextureWidth: object && object.boneTextureWidth,
  13700. boneTextureHeight: object && object.boneTextureHeight,
  13701. morphTargets: material.morphTargets,
  13702. morphNormals: material.morphNormals,
  13703. maxMorphTargets: this.maxMorphTargets,
  13704. maxMorphNormals: this.maxMorphNormals,
  13705. maxDirLights: maxLightCount.directional,
  13706. maxPointLights: maxLightCount.point,
  13707. maxSpotLights: maxLightCount.spot,
  13708. maxHemiLights: maxLightCount.hemi,
  13709. maxShadows: maxShadows,
  13710. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13711. shadowMapType: this.shadowMapType,
  13712. shadowMapDebug: this.shadowMapDebug,
  13713. shadowMapCascade: this.shadowMapCascade,
  13714. alphaTest: material.alphaTest,
  13715. metal: material.metal,
  13716. perPixel: material.perPixel,
  13717. wrapAround: material.wrapAround,
  13718. doubleSided: material.side === THREE.DoubleSide,
  13719. flipSided: material.side === THREE.BackSide
  13720. };
  13721. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13722. var attributes = material.program.attributes;
  13723. if ( material.morphTargets ) {
  13724. material.numSupportedMorphTargets = 0;
  13725. var id, base = "morphTarget";
  13726. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13727. id = base + i;
  13728. if ( attributes[ id ] >= 0 ) {
  13729. material.numSupportedMorphTargets ++;
  13730. }
  13731. }
  13732. }
  13733. if ( material.morphNormals ) {
  13734. material.numSupportedMorphNormals = 0;
  13735. var id, base = "morphNormal";
  13736. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13737. id = base + i;
  13738. if ( attributes[ id ] >= 0 ) {
  13739. material.numSupportedMorphNormals ++;
  13740. }
  13741. }
  13742. }
  13743. material.uniformsList = [];
  13744. for ( u in material.uniforms ) {
  13745. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13746. }
  13747. };
  13748. function setMaterialShaders( material, shaders ) {
  13749. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13750. material.vertexShader = shaders.vertexShader;
  13751. material.fragmentShader = shaders.fragmentShader;
  13752. };
  13753. function setProgram( camera, lights, fog, material, object ) {
  13754. _usedTextureUnits = 0;
  13755. if ( material.needsUpdate ) {
  13756. if ( material.program ) deallocateMaterial( material );
  13757. _this.initMaterial( material, lights, fog, object );
  13758. material.needsUpdate = false;
  13759. }
  13760. if ( material.morphTargets ) {
  13761. if ( ! object.__webglMorphTargetInfluences ) {
  13762. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13763. }
  13764. }
  13765. var refreshMaterial = false;
  13766. var program = material.program,
  13767. p_uniforms = program.uniforms,
  13768. m_uniforms = material.uniforms;
  13769. if ( program !== _currentProgram ) {
  13770. _gl.useProgram( program );
  13771. _currentProgram = program;
  13772. refreshMaterial = true;
  13773. }
  13774. if ( material.id !== _currentMaterialId ) {
  13775. _currentMaterialId = material.id;
  13776. refreshMaterial = true;
  13777. }
  13778. if ( refreshMaterial || camera !== _currentCamera ) {
  13779. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13780. if ( camera !== _currentCamera ) _currentCamera = camera;
  13781. }
  13782. // skinning uniforms must be set even if material didn't change
  13783. // auto-setting of texture unit for bone texture must go before other textures
  13784. // not sure why, but otherwise weird things happen
  13785. if ( material.skinning ) {
  13786. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13787. if ( p_uniforms.boneTexture !== null ) {
  13788. var textureUnit = getTextureUnit();
  13789. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13790. _this.setTexture( object.boneTexture, textureUnit );
  13791. }
  13792. } else {
  13793. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13794. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13795. }
  13796. }
  13797. }
  13798. if ( refreshMaterial ) {
  13799. // refresh uniforms common to several materials
  13800. if ( fog && material.fog ) {
  13801. refreshUniformsFog( m_uniforms, fog );
  13802. }
  13803. if ( material instanceof THREE.MeshPhongMaterial ||
  13804. material instanceof THREE.MeshLambertMaterial ||
  13805. material.lights ) {
  13806. if ( _lightsNeedUpdate ) {
  13807. setupLights( program, lights );
  13808. _lightsNeedUpdate = false;
  13809. }
  13810. refreshUniformsLights( m_uniforms, _lights );
  13811. }
  13812. if ( material instanceof THREE.MeshBasicMaterial ||
  13813. material instanceof THREE.MeshLambertMaterial ||
  13814. material instanceof THREE.MeshPhongMaterial ) {
  13815. refreshUniformsCommon( m_uniforms, material );
  13816. }
  13817. // refresh single material specific uniforms
  13818. if ( material instanceof THREE.LineBasicMaterial ) {
  13819. refreshUniformsLine( m_uniforms, material );
  13820. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13821. refreshUniformsLine( m_uniforms, material );
  13822. refreshUniformsDash( m_uniforms, material );
  13823. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13824. refreshUniformsParticle( m_uniforms, material );
  13825. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13826. refreshUniformsPhong( m_uniforms, material );
  13827. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13828. refreshUniformsLambert( m_uniforms, material );
  13829. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13830. m_uniforms.mNear.value = camera.near;
  13831. m_uniforms.mFar.value = camera.far;
  13832. m_uniforms.opacity.value = material.opacity;
  13833. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13834. m_uniforms.opacity.value = material.opacity;
  13835. }
  13836. if ( object.receiveShadow && ! material._shadowPass ) {
  13837. refreshUniformsShadow( m_uniforms, lights );
  13838. }
  13839. // load common uniforms
  13840. loadUniformsGeneric( program, material.uniformsList );
  13841. // load material specific uniforms
  13842. // (shader material also gets them for the sake of genericity)
  13843. if ( material instanceof THREE.ShaderMaterial ||
  13844. material instanceof THREE.MeshPhongMaterial ||
  13845. material.envMap ) {
  13846. if ( p_uniforms.cameraPosition !== null ) {
  13847. _vector3.getPositionFromMatrix( camera.matrixWorld );
  13848. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13849. }
  13850. }
  13851. if ( material instanceof THREE.MeshPhongMaterial ||
  13852. material instanceof THREE.MeshLambertMaterial ||
  13853. material instanceof THREE.ShaderMaterial ||
  13854. material.skinning ) {
  13855. if ( p_uniforms.viewMatrix !== null ) {
  13856. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13857. }
  13858. }
  13859. }
  13860. loadUniformsMatrices( p_uniforms, object );
  13861. if ( p_uniforms.modelMatrix !== null ) {
  13862. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13863. }
  13864. return program;
  13865. };
  13866. // Uniforms (refresh uniforms objects)
  13867. function refreshUniformsCommon ( uniforms, material ) {
  13868. uniforms.opacity.value = material.opacity;
  13869. if ( _this.gammaInput ) {
  13870. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13871. } else {
  13872. uniforms.diffuse.value = material.color;
  13873. }
  13874. uniforms.map.value = material.map;
  13875. uniforms.lightMap.value = material.lightMap;
  13876. uniforms.specularMap.value = material.specularMap;
  13877. if ( material.bumpMap ) {
  13878. uniforms.bumpMap.value = material.bumpMap;
  13879. uniforms.bumpScale.value = material.bumpScale;
  13880. }
  13881. if ( material.normalMap ) {
  13882. uniforms.normalMap.value = material.normalMap;
  13883. uniforms.normalScale.value.copy( material.normalScale );
  13884. }
  13885. // uv repeat and offset setting priorities
  13886. // 1. color map
  13887. // 2. specular map
  13888. // 3. normal map
  13889. // 4. bump map
  13890. var uvScaleMap;
  13891. if ( material.map ) {
  13892. uvScaleMap = material.map;
  13893. } else if ( material.specularMap ) {
  13894. uvScaleMap = material.specularMap;
  13895. } else if ( material.normalMap ) {
  13896. uvScaleMap = material.normalMap;
  13897. } else if ( material.bumpMap ) {
  13898. uvScaleMap = material.bumpMap;
  13899. }
  13900. if ( uvScaleMap !== undefined ) {
  13901. var offset = uvScaleMap.offset;
  13902. var repeat = uvScaleMap.repeat;
  13903. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13904. }
  13905. uniforms.envMap.value = material.envMap;
  13906. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13907. if ( _this.gammaInput ) {
  13908. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13909. uniforms.reflectivity.value = material.reflectivity;
  13910. } else {
  13911. uniforms.reflectivity.value = material.reflectivity;
  13912. }
  13913. uniforms.refractionRatio.value = material.refractionRatio;
  13914. uniforms.combine.value = material.combine;
  13915. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13916. };
  13917. function refreshUniformsLine ( uniforms, material ) {
  13918. uniforms.diffuse.value = material.color;
  13919. uniforms.opacity.value = material.opacity;
  13920. };
  13921. function refreshUniformsDash ( uniforms, material ) {
  13922. uniforms.dashSize.value = material.dashSize;
  13923. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13924. uniforms.scale.value = material.scale;
  13925. };
  13926. function refreshUniformsParticle ( uniforms, material ) {
  13927. uniforms.psColor.value = material.color;
  13928. uniforms.opacity.value = material.opacity;
  13929. uniforms.size.value = material.size;
  13930. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13931. uniforms.map.value = material.map;
  13932. };
  13933. function refreshUniformsFog ( uniforms, fog ) {
  13934. uniforms.fogColor.value = fog.color;
  13935. if ( fog instanceof THREE.Fog ) {
  13936. uniforms.fogNear.value = fog.near;
  13937. uniforms.fogFar.value = fog.far;
  13938. } else if ( fog instanceof THREE.FogExp2 ) {
  13939. uniforms.fogDensity.value = fog.density;
  13940. }
  13941. };
  13942. function refreshUniformsPhong ( uniforms, material ) {
  13943. uniforms.shininess.value = material.shininess;
  13944. if ( _this.gammaInput ) {
  13945. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13946. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13947. uniforms.specular.value.copyGammaToLinear( material.specular );
  13948. } else {
  13949. uniforms.ambient.value = material.ambient;
  13950. uniforms.emissive.value = material.emissive;
  13951. uniforms.specular.value = material.specular;
  13952. }
  13953. if ( material.wrapAround ) {
  13954. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13955. }
  13956. };
  13957. function refreshUniformsLambert ( uniforms, material ) {
  13958. if ( _this.gammaInput ) {
  13959. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13960. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13961. } else {
  13962. uniforms.ambient.value = material.ambient;
  13963. uniforms.emissive.value = material.emissive;
  13964. }
  13965. if ( material.wrapAround ) {
  13966. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13967. }
  13968. };
  13969. function refreshUniformsLights ( uniforms, lights ) {
  13970. uniforms.ambientLightColor.value = lights.ambient;
  13971. uniforms.directionalLightColor.value = lights.directional.colors;
  13972. uniforms.directionalLightDirection.value = lights.directional.positions;
  13973. uniforms.pointLightColor.value = lights.point.colors;
  13974. uniforms.pointLightPosition.value = lights.point.positions;
  13975. uniforms.pointLightDistance.value = lights.point.distances;
  13976. uniforms.spotLightColor.value = lights.spot.colors;
  13977. uniforms.spotLightPosition.value = lights.spot.positions;
  13978. uniforms.spotLightDistance.value = lights.spot.distances;
  13979. uniforms.spotLightDirection.value = lights.spot.directions;
  13980. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13981. uniforms.spotLightExponent.value = lights.spot.exponents;
  13982. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13983. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13984. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13985. };
  13986. function refreshUniformsShadow ( uniforms, lights ) {
  13987. if ( uniforms.shadowMatrix ) {
  13988. var j = 0;
  13989. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13990. var light = lights[ i ];
  13991. if ( ! light.castShadow ) continue;
  13992. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13993. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13994. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13995. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13996. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13997. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13998. j ++;
  13999. }
  14000. }
  14001. }
  14002. };
  14003. // Uniforms (load to GPU)
  14004. function loadUniformsMatrices ( uniforms, object ) {
  14005. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14006. if ( uniforms.normalMatrix ) {
  14007. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14008. }
  14009. };
  14010. function getTextureUnit() {
  14011. var textureUnit = _usedTextureUnits;
  14012. if ( textureUnit >= _maxTextures ) {
  14013. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14014. }
  14015. _usedTextureUnits += 1;
  14016. return textureUnit;
  14017. };
  14018. function loadUniformsGeneric ( program, uniforms ) {
  14019. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14020. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14021. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14022. if ( !location ) continue;
  14023. uniform = uniforms[ j ][ 0 ];
  14024. type = uniform.type;
  14025. value = uniform.value;
  14026. if ( type === "i" ) { // single integer
  14027. _gl.uniform1i( location, value );
  14028. } else if ( type === "f" ) { // single float
  14029. _gl.uniform1f( location, value );
  14030. } else if ( type === "v2" ) { // single THREE.Vector2
  14031. _gl.uniform2f( location, value.x, value.y );
  14032. } else if ( type === "v3" ) { // single THREE.Vector3
  14033. _gl.uniform3f( location, value.x, value.y, value.z );
  14034. } else if ( type === "v4" ) { // single THREE.Vector4
  14035. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14036. } else if ( type === "c" ) { // single THREE.Color
  14037. _gl.uniform3f( location, value.r, value.g, value.b );
  14038. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14039. _gl.uniform1iv( location, value );
  14040. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14041. _gl.uniform3iv( location, value );
  14042. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14043. _gl.uniform1fv( location, value );
  14044. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14045. _gl.uniform3fv( location, value );
  14046. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14047. if ( uniform._array === undefined ) {
  14048. uniform._array = new Float32Array( 2 * value.length );
  14049. }
  14050. for ( i = 0, il = value.length; i < il; i ++ ) {
  14051. offset = i * 2;
  14052. uniform._array[ offset ] = value[ i ].x;
  14053. uniform._array[ offset + 1 ] = value[ i ].y;
  14054. }
  14055. _gl.uniform2fv( location, uniform._array );
  14056. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14057. if ( uniform._array === undefined ) {
  14058. uniform._array = new Float32Array( 3 * value.length );
  14059. }
  14060. for ( i = 0, il = value.length; i < il; i ++ ) {
  14061. offset = i * 3;
  14062. uniform._array[ offset ] = value[ i ].x;
  14063. uniform._array[ offset + 1 ] = value[ i ].y;
  14064. uniform._array[ offset + 2 ] = value[ i ].z;
  14065. }
  14066. _gl.uniform3fv( location, uniform._array );
  14067. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14068. if ( uniform._array === undefined ) {
  14069. uniform._array = new Float32Array( 4 * value.length );
  14070. }
  14071. for ( i = 0, il = value.length; i < il; i ++ ) {
  14072. offset = i * 4;
  14073. uniform._array[ offset ] = value[ i ].x;
  14074. uniform._array[ offset + 1 ] = value[ i ].y;
  14075. uniform._array[ offset + 2 ] = value[ i ].z;
  14076. uniform._array[ offset + 3 ] = value[ i ].w;
  14077. }
  14078. _gl.uniform4fv( location, uniform._array );
  14079. } else if ( type === "m4") { // single THREE.Matrix4
  14080. if ( uniform._array === undefined ) {
  14081. uniform._array = new Float32Array( 16 );
  14082. }
  14083. value.flattenToArray( uniform._array );
  14084. _gl.uniformMatrix4fv( location, false, uniform._array );
  14085. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14086. if ( uniform._array === undefined ) {
  14087. uniform._array = new Float32Array( 16 * value.length );
  14088. }
  14089. for ( i = 0, il = value.length; i < il; i ++ ) {
  14090. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14091. }
  14092. _gl.uniformMatrix4fv( location, false, uniform._array );
  14093. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14094. texture = value;
  14095. textureUnit = getTextureUnit();
  14096. _gl.uniform1i( location, textureUnit );
  14097. if ( !texture ) continue;
  14098. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14099. setCubeTexture( texture, textureUnit );
  14100. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14101. setCubeTextureDynamic( texture, textureUnit );
  14102. } else {
  14103. _this.setTexture( texture, textureUnit );
  14104. }
  14105. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14106. if ( uniform._array === undefined ) {
  14107. uniform._array = [];
  14108. }
  14109. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14110. uniform._array[ i ] = getTextureUnit();
  14111. }
  14112. _gl.uniform1iv( location, uniform._array );
  14113. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14114. texture = uniform.value[ i ];
  14115. textureUnit = uniform._array[ i ];
  14116. if ( !texture ) continue;
  14117. _this.setTexture( texture, textureUnit );
  14118. }
  14119. }
  14120. }
  14121. };
  14122. function setupMatrices ( object, camera ) {
  14123. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14124. object._normalMatrix.getInverse( object._modelViewMatrix );
  14125. object._normalMatrix.transpose();
  14126. };
  14127. //
  14128. function setColorGamma( array, offset, color, intensitySq ) {
  14129. array[ offset ] = color.r * color.r * intensitySq;
  14130. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14131. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14132. };
  14133. function setColorLinear( array, offset, color, intensity ) {
  14134. array[ offset ] = color.r * intensity;
  14135. array[ offset + 1 ] = color.g * intensity;
  14136. array[ offset + 2 ] = color.b * intensity;
  14137. };
  14138. function setupLights ( program, lights ) {
  14139. var l, ll, light, n,
  14140. r = 0, g = 0, b = 0,
  14141. color, skyColor, groundColor,
  14142. intensity, intensitySq,
  14143. position,
  14144. distance,
  14145. zlights = _lights,
  14146. dirColors = zlights.directional.colors,
  14147. dirPositions = zlights.directional.positions,
  14148. pointColors = zlights.point.colors,
  14149. pointPositions = zlights.point.positions,
  14150. pointDistances = zlights.point.distances,
  14151. spotColors = zlights.spot.colors,
  14152. spotPositions = zlights.spot.positions,
  14153. spotDistances = zlights.spot.distances,
  14154. spotDirections = zlights.spot.directions,
  14155. spotAnglesCos = zlights.spot.anglesCos,
  14156. spotExponents = zlights.spot.exponents,
  14157. hemiSkyColors = zlights.hemi.skyColors,
  14158. hemiGroundColors = zlights.hemi.groundColors,
  14159. hemiPositions = zlights.hemi.positions,
  14160. dirLength = 0,
  14161. pointLength = 0,
  14162. spotLength = 0,
  14163. hemiLength = 0,
  14164. dirCount = 0,
  14165. pointCount = 0,
  14166. spotCount = 0,
  14167. hemiCount = 0,
  14168. dirOffset = 0,
  14169. pointOffset = 0,
  14170. spotOffset = 0,
  14171. hemiOffset = 0;
  14172. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14173. light = lights[ l ];
  14174. if ( light.onlyShadow ) continue;
  14175. color = light.color;
  14176. intensity = light.intensity;
  14177. distance = light.distance;
  14178. if ( light instanceof THREE.AmbientLight ) {
  14179. if ( ! light.visible ) continue;
  14180. if ( _this.gammaInput ) {
  14181. r += color.r * color.r;
  14182. g += color.g * color.g;
  14183. b += color.b * color.b;
  14184. } else {
  14185. r += color.r;
  14186. g += color.g;
  14187. b += color.b;
  14188. }
  14189. } else if ( light instanceof THREE.DirectionalLight ) {
  14190. dirCount += 1;
  14191. if ( ! light.visible ) continue;
  14192. _direction.getPositionFromMatrix( light.matrixWorld );
  14193. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14194. _direction.sub( _vector3 );
  14195. _direction.normalize();
  14196. // skip lights with undefined direction
  14197. // these create troubles in OpenGL (making pixel black)
  14198. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14199. dirOffset = dirLength * 3;
  14200. dirPositions[ dirOffset ] = _direction.x;
  14201. dirPositions[ dirOffset + 1 ] = _direction.y;
  14202. dirPositions[ dirOffset + 2 ] = _direction.z;
  14203. if ( _this.gammaInput ) {
  14204. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14205. } else {
  14206. setColorLinear( dirColors, dirOffset, color, intensity );
  14207. }
  14208. dirLength += 1;
  14209. } else if ( light instanceof THREE.PointLight ) {
  14210. pointCount += 1;
  14211. if ( ! light.visible ) continue;
  14212. pointOffset = pointLength * 3;
  14213. if ( _this.gammaInput ) {
  14214. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14215. } else {
  14216. setColorLinear( pointColors, pointOffset, color, intensity );
  14217. }
  14218. _vector3.getPositionFromMatrix( light.matrixWorld );
  14219. pointPositions[ pointOffset ] = _vector3.x;
  14220. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14221. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14222. pointDistances[ pointLength ] = distance;
  14223. pointLength += 1;
  14224. } else if ( light instanceof THREE.SpotLight ) {
  14225. spotCount += 1;
  14226. if ( ! light.visible ) continue;
  14227. spotOffset = spotLength * 3;
  14228. if ( _this.gammaInput ) {
  14229. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14230. } else {
  14231. setColorLinear( spotColors, spotOffset, color, intensity );
  14232. }
  14233. _vector3.getPositionFromMatrix( light.matrixWorld );
  14234. spotPositions[ spotOffset ] = _vector3.x;
  14235. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14236. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14237. spotDistances[ spotLength ] = distance;
  14238. _direction.copy( _vector3 );
  14239. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14240. _direction.sub( _vector3 );
  14241. _direction.normalize();
  14242. spotDirections[ spotOffset ] = _direction.x;
  14243. spotDirections[ spotOffset + 1 ] = _direction.y;
  14244. spotDirections[ spotOffset + 2 ] = _direction.z;
  14245. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14246. spotExponents[ spotLength ] = light.exponent;
  14247. spotLength += 1;
  14248. } else if ( light instanceof THREE.HemisphereLight ) {
  14249. hemiCount += 1;
  14250. if ( ! light.visible ) continue;
  14251. _direction.getPositionFromMatrix( light.matrixWorld );
  14252. _direction.normalize();
  14253. // skip lights with undefined direction
  14254. // these create troubles in OpenGL (making pixel black)
  14255. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14256. hemiOffset = hemiLength * 3;
  14257. hemiPositions[ hemiOffset ] = _direction.x;
  14258. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14259. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14260. skyColor = light.color;
  14261. groundColor = light.groundColor;
  14262. if ( _this.gammaInput ) {
  14263. intensitySq = intensity * intensity;
  14264. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14265. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14266. } else {
  14267. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14268. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14269. }
  14270. hemiLength += 1;
  14271. }
  14272. }
  14273. // null eventual remains from removed lights
  14274. // (this is to avoid if in shader)
  14275. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14276. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14277. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14278. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14279. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14280. zlights.directional.length = dirLength;
  14281. zlights.point.length = pointLength;
  14282. zlights.spot.length = spotLength;
  14283. zlights.hemi.length = hemiLength;
  14284. zlights.ambient[ 0 ] = r;
  14285. zlights.ambient[ 1 ] = g;
  14286. zlights.ambient[ 2 ] = b;
  14287. };
  14288. // GL state setting
  14289. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14290. if ( cullFace === THREE.CullFaceNone ) {
  14291. _gl.disable( _gl.CULL_FACE );
  14292. } else {
  14293. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14294. _gl.frontFace( _gl.CW );
  14295. } else {
  14296. _gl.frontFace( _gl.CCW );
  14297. }
  14298. if ( cullFace === THREE.CullFaceBack ) {
  14299. _gl.cullFace( _gl.BACK );
  14300. } else if ( cullFace === THREE.CullFaceFront ) {
  14301. _gl.cullFace( _gl.FRONT );
  14302. } else {
  14303. _gl.cullFace( _gl.FRONT_AND_BACK );
  14304. }
  14305. _gl.enable( _gl.CULL_FACE );
  14306. }
  14307. };
  14308. this.setMaterialFaces = function ( material ) {
  14309. var doubleSided = material.side === THREE.DoubleSide;
  14310. var flipSided = material.side === THREE.BackSide;
  14311. if ( _oldDoubleSided !== doubleSided ) {
  14312. if ( doubleSided ) {
  14313. _gl.disable( _gl.CULL_FACE );
  14314. } else {
  14315. _gl.enable( _gl.CULL_FACE );
  14316. }
  14317. _oldDoubleSided = doubleSided;
  14318. }
  14319. if ( _oldFlipSided !== flipSided ) {
  14320. if ( flipSided ) {
  14321. _gl.frontFace( _gl.CW );
  14322. } else {
  14323. _gl.frontFace( _gl.CCW );
  14324. }
  14325. _oldFlipSided = flipSided;
  14326. }
  14327. };
  14328. this.setDepthTest = function ( depthTest ) {
  14329. if ( _oldDepthTest !== depthTest ) {
  14330. if ( depthTest ) {
  14331. _gl.enable( _gl.DEPTH_TEST );
  14332. } else {
  14333. _gl.disable( _gl.DEPTH_TEST );
  14334. }
  14335. _oldDepthTest = depthTest;
  14336. }
  14337. };
  14338. this.setDepthWrite = function ( depthWrite ) {
  14339. if ( _oldDepthWrite !== depthWrite ) {
  14340. _gl.depthMask( depthWrite );
  14341. _oldDepthWrite = depthWrite;
  14342. }
  14343. };
  14344. function setLineWidth ( width ) {
  14345. if ( width !== _oldLineWidth ) {
  14346. _gl.lineWidth( width );
  14347. _oldLineWidth = width;
  14348. }
  14349. };
  14350. function setPolygonOffset ( polygonoffset, factor, units ) {
  14351. if ( _oldPolygonOffset !== polygonoffset ) {
  14352. if ( polygonoffset ) {
  14353. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14354. } else {
  14355. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14356. }
  14357. _oldPolygonOffset = polygonoffset;
  14358. }
  14359. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14360. _gl.polygonOffset( factor, units );
  14361. _oldPolygonOffsetFactor = factor;
  14362. _oldPolygonOffsetUnits = units;
  14363. }
  14364. };
  14365. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14366. if ( blending !== _oldBlending ) {
  14367. if ( blending === THREE.NoBlending ) {
  14368. _gl.disable( _gl.BLEND );
  14369. } else if ( blending === THREE.AdditiveBlending ) {
  14370. _gl.enable( _gl.BLEND );
  14371. _gl.blendEquation( _gl.FUNC_ADD );
  14372. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14373. } else if ( blending === THREE.SubtractiveBlending ) {
  14374. // TODO: Find blendFuncSeparate() combination
  14375. _gl.enable( _gl.BLEND );
  14376. _gl.blendEquation( _gl.FUNC_ADD );
  14377. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14378. } else if ( blending === THREE.MultiplyBlending ) {
  14379. // TODO: Find blendFuncSeparate() combination
  14380. _gl.enable( _gl.BLEND );
  14381. _gl.blendEquation( _gl.FUNC_ADD );
  14382. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14383. } else if ( blending === THREE.CustomBlending ) {
  14384. _gl.enable( _gl.BLEND );
  14385. } else {
  14386. _gl.enable( _gl.BLEND );
  14387. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14388. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14389. }
  14390. _oldBlending = blending;
  14391. }
  14392. if ( blending === THREE.CustomBlending ) {
  14393. if ( blendEquation !== _oldBlendEquation ) {
  14394. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14395. _oldBlendEquation = blendEquation;
  14396. }
  14397. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14398. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14399. _oldBlendSrc = blendSrc;
  14400. _oldBlendDst = blendDst;
  14401. }
  14402. } else {
  14403. _oldBlendEquation = null;
  14404. _oldBlendSrc = null;
  14405. _oldBlendDst = null;
  14406. }
  14407. };
  14408. // Defines
  14409. function generateDefines ( defines ) {
  14410. var value, chunk, chunks = [];
  14411. for ( var d in defines ) {
  14412. value = defines[ d ];
  14413. if ( value === false ) continue;
  14414. chunk = "#define " + d + " " + value;
  14415. chunks.push( chunk );
  14416. }
  14417. return chunks.join( "\n" );
  14418. };
  14419. // Shaders
  14420. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14421. var p, pl, d, program, code;
  14422. var chunks = [];
  14423. // Generate code
  14424. if ( shaderID ) {
  14425. chunks.push( shaderID );
  14426. } else {
  14427. chunks.push( fragmentShader );
  14428. chunks.push( vertexShader );
  14429. }
  14430. for ( d in defines ) {
  14431. chunks.push( d );
  14432. chunks.push( defines[ d ] );
  14433. }
  14434. for ( p in parameters ) {
  14435. chunks.push( p );
  14436. chunks.push( parameters[ p ] );
  14437. }
  14438. code = chunks.join();
  14439. // Check if code has been already compiled
  14440. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14441. var programInfo = _programs[ p ];
  14442. if ( programInfo.code === code ) {
  14443. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  14444. programInfo.usedTimes ++;
  14445. return programInfo.program;
  14446. }
  14447. }
  14448. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14449. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14450. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14451. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14452. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14453. }
  14454. //console.log( "building new program " );
  14455. //
  14456. var customDefines = generateDefines( defines );
  14457. //
  14458. program = _gl.createProgram();
  14459. var prefix_vertex = [
  14460. "precision " + _precision + " float;",
  14461. customDefines,
  14462. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14463. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14464. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14465. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14466. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14467. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14468. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14469. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14470. "#define MAX_SHADOWS " + parameters.maxShadows,
  14471. "#define MAX_BONES " + parameters.maxBones,
  14472. parameters.map ? "#define USE_MAP" : "",
  14473. parameters.envMap ? "#define USE_ENVMAP" : "",
  14474. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14475. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14476. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14477. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14478. parameters.vertexColors ? "#define USE_COLOR" : "",
  14479. parameters.skinning ? "#define USE_SKINNING" : "",
  14480. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14481. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14482. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14483. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14484. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14485. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14486. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14487. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14488. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14489. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14490. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14491. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14492. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14493. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14494. "uniform mat4 modelMatrix;",
  14495. "uniform mat4 modelViewMatrix;",
  14496. "uniform mat4 projectionMatrix;",
  14497. "uniform mat4 viewMatrix;",
  14498. "uniform mat3 normalMatrix;",
  14499. "uniform vec3 cameraPosition;",
  14500. "attribute vec3 position;",
  14501. "attribute vec3 normal;",
  14502. "attribute vec2 uv;",
  14503. "attribute vec2 uv2;",
  14504. "#ifdef USE_COLOR",
  14505. "attribute vec3 color;",
  14506. "#endif",
  14507. "#ifdef USE_MORPHTARGETS",
  14508. "attribute vec3 morphTarget0;",
  14509. "attribute vec3 morphTarget1;",
  14510. "attribute vec3 morphTarget2;",
  14511. "attribute vec3 morphTarget3;",
  14512. "#ifdef USE_MORPHNORMALS",
  14513. "attribute vec3 morphNormal0;",
  14514. "attribute vec3 morphNormal1;",
  14515. "attribute vec3 morphNormal2;",
  14516. "attribute vec3 morphNormal3;",
  14517. "#else",
  14518. "attribute vec3 morphTarget4;",
  14519. "attribute vec3 morphTarget5;",
  14520. "attribute vec3 morphTarget6;",
  14521. "attribute vec3 morphTarget7;",
  14522. "#endif",
  14523. "#endif",
  14524. "#ifdef USE_SKINNING",
  14525. "attribute vec4 skinIndex;",
  14526. "attribute vec4 skinWeight;",
  14527. "#endif",
  14528. ""
  14529. ].join("\n");
  14530. var prefix_fragment = [
  14531. "precision " + _precision + " float;",
  14532. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14533. customDefines,
  14534. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14535. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14536. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14537. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14538. "#define MAX_SHADOWS " + parameters.maxShadows,
  14539. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14540. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14541. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14542. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14543. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14544. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14545. parameters.map ? "#define USE_MAP" : "",
  14546. parameters.envMap ? "#define USE_ENVMAP" : "",
  14547. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14548. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14549. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14550. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14551. parameters.vertexColors ? "#define USE_COLOR" : "",
  14552. parameters.metal ? "#define METAL" : "",
  14553. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14554. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14555. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14556. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14557. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14558. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14559. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14560. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14561. "uniform mat4 viewMatrix;",
  14562. "uniform vec3 cameraPosition;",
  14563. ""
  14564. ].join("\n");
  14565. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14566. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14567. _gl.attachShader( program, glVertexShader );
  14568. _gl.attachShader( program, glFragmentShader );
  14569. _gl.linkProgram( program );
  14570. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14571. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14572. }
  14573. // clean up
  14574. _gl.deleteShader( glFragmentShader );
  14575. _gl.deleteShader( glVertexShader );
  14576. //console.log( prefix_fragment + fragmentShader );
  14577. //console.log( prefix_vertex + vertexShader );
  14578. program.uniforms = {};
  14579. program.attributes = {};
  14580. var identifiers, u, a, i;
  14581. // cache uniform locations
  14582. identifiers = [
  14583. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14584. 'morphTargetInfluences'
  14585. ];
  14586. if ( parameters.useVertexTexture ) {
  14587. identifiers.push( 'boneTexture' );
  14588. } else {
  14589. identifiers.push( 'boneGlobalMatrices' );
  14590. }
  14591. for ( u in uniforms ) {
  14592. identifiers.push( u );
  14593. }
  14594. cacheUniformLocations( program, identifiers );
  14595. // cache attributes locations
  14596. identifiers = [
  14597. "position", "normal", "uv", "uv2", "tangent", "color",
  14598. "skinIndex", "skinWeight", "lineDistance"
  14599. ];
  14600. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14601. identifiers.push( "morphTarget" + i );
  14602. }
  14603. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14604. identifiers.push( "morphNormal" + i );
  14605. }
  14606. for ( a in attributes ) {
  14607. identifiers.push( a );
  14608. }
  14609. cacheAttributeLocations( program, identifiers );
  14610. program.id = _programs_counter ++;
  14611. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14612. _this.info.memory.programs = _programs.length;
  14613. return program;
  14614. };
  14615. // Shader parameters cache
  14616. function cacheUniformLocations ( program, identifiers ) {
  14617. var i, l, id;
  14618. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14619. id = identifiers[ i ];
  14620. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14621. }
  14622. };
  14623. function cacheAttributeLocations ( program, identifiers ) {
  14624. var i, l, id;
  14625. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14626. id = identifiers[ i ];
  14627. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14628. }
  14629. };
  14630. function addLineNumbers ( string ) {
  14631. var chunks = string.split( "\n" );
  14632. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14633. // Chrome reports shader errors on lines
  14634. // starting counting from 1
  14635. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14636. }
  14637. return chunks.join( "\n" );
  14638. };
  14639. function getShader ( type, string ) {
  14640. var shader;
  14641. if ( type === "fragment" ) {
  14642. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14643. } else if ( type === "vertex" ) {
  14644. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14645. }
  14646. _gl.shaderSource( shader, string );
  14647. _gl.compileShader( shader );
  14648. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14649. console.error( _gl.getShaderInfoLog( shader ) );
  14650. console.error( addLineNumbers( string ) );
  14651. return null;
  14652. }
  14653. return shader;
  14654. };
  14655. // Textures
  14656. function isPowerOfTwo ( value ) {
  14657. return ( value & ( value - 1 ) ) === 0;
  14658. };
  14659. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14660. if ( isImagePowerOfTwo ) {
  14661. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14662. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14663. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14664. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14665. } else {
  14666. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14667. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14668. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14669. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14670. }
  14671. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14672. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14673. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14674. texture.__oldAnisotropy = texture.anisotropy;
  14675. }
  14676. }
  14677. };
  14678. this.setTexture = function ( texture, slot ) {
  14679. if ( texture.needsUpdate ) {
  14680. if ( ! texture.__webglInit ) {
  14681. texture.__webglInit = true;
  14682. texture.addEventListener( 'dispose', onTextureDispose );
  14683. texture.__webglTexture = _gl.createTexture();
  14684. _this.info.memory.textures ++;
  14685. }
  14686. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14687. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14688. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14689. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14690. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14691. var image = texture.image,
  14692. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14693. glFormat = paramThreeToGL( texture.format ),
  14694. glType = paramThreeToGL( texture.type );
  14695. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14696. var mipmap, mipmaps = texture.mipmaps;
  14697. if ( texture instanceof THREE.DataTexture ) {
  14698. // use manually created mipmaps if available
  14699. // if there are no manual mipmaps
  14700. // set 0 level mipmap and then use GL to generate other mipmap levels
  14701. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14702. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14703. mipmap = mipmaps[ i ];
  14704. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14705. }
  14706. texture.generateMipmaps = false;
  14707. } else {
  14708. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14709. }
  14710. } else if ( texture instanceof THREE.CompressedTexture ) {
  14711. // compressed textures can only use manually created mipmaps
  14712. // WebGL can't generate mipmaps for DDS textures
  14713. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14714. mipmap = mipmaps[ i ];
  14715. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14716. }
  14717. } else { // regular Texture (image, video, canvas)
  14718. // use manually created mipmaps if available
  14719. // if there are no manual mipmaps
  14720. // set 0 level mipmap and then use GL to generate other mipmap levels
  14721. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14722. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14723. mipmap = mipmaps[ i ];
  14724. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14725. }
  14726. texture.generateMipmaps = false;
  14727. } else {
  14728. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14729. }
  14730. }
  14731. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14732. texture.needsUpdate = false;
  14733. if ( texture.onUpdate ) texture.onUpdate();
  14734. } else {
  14735. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14736. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14737. }
  14738. };
  14739. function clampToMaxSize ( image, maxSize ) {
  14740. if ( image.width <= maxSize && image.height <= maxSize ) {
  14741. return image;
  14742. }
  14743. // Warning: Scaling through the canvas will only work with images that use
  14744. // premultiplied alpha.
  14745. var maxDimension = Math.max( image.width, image.height );
  14746. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14747. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14748. var canvas = document.createElement( 'canvas' );
  14749. canvas.width = newWidth;
  14750. canvas.height = newHeight;
  14751. var ctx = canvas.getContext( "2d" );
  14752. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14753. return canvas;
  14754. }
  14755. function setCubeTexture ( texture, slot ) {
  14756. if ( texture.image.length === 6 ) {
  14757. if ( texture.needsUpdate ) {
  14758. if ( ! texture.image.__webglTextureCube ) {
  14759. texture.image.__webglTextureCube = _gl.createTexture();
  14760. _this.info.memory.textures ++;
  14761. }
  14762. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14763. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14764. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14765. var isCompressed = texture instanceof THREE.CompressedTexture;
  14766. var cubeImage = [];
  14767. for ( var i = 0; i < 6; i ++ ) {
  14768. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14769. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14770. } else {
  14771. cubeImage[ i ] = texture.image[ i ];
  14772. }
  14773. }
  14774. var image = cubeImage[ 0 ],
  14775. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14776. glFormat = paramThreeToGL( texture.format ),
  14777. glType = paramThreeToGL( texture.type );
  14778. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14779. for ( var i = 0; i < 6; i ++ ) {
  14780. if ( isCompressed ) {
  14781. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14782. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14783. mipmap = mipmaps[ j ];
  14784. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14785. }
  14786. } else {
  14787. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14788. }
  14789. }
  14790. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14791. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14792. }
  14793. texture.needsUpdate = false;
  14794. if ( texture.onUpdate ) texture.onUpdate();
  14795. } else {
  14796. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14797. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14798. }
  14799. }
  14800. };
  14801. function setCubeTextureDynamic ( texture, slot ) {
  14802. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14803. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14804. };
  14805. // Render targets
  14806. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14807. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14808. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14809. };
  14810. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14811. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14812. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14813. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14814. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14815. /* For some reason this is not working. Defaulting to RGBA4.
  14816. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14817. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14818. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14819. */
  14820. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14821. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14822. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14823. } else {
  14824. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14825. }
  14826. };
  14827. this.setRenderTarget = function ( renderTarget ) {
  14828. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14829. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14830. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14831. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14832. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14833. renderTarget.__webglTexture = _gl.createTexture();
  14834. _this.info.memory.textures ++;
  14835. // Setup texture, create render and frame buffers
  14836. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14837. glFormat = paramThreeToGL( renderTarget.format ),
  14838. glType = paramThreeToGL( renderTarget.type );
  14839. if ( isCube ) {
  14840. renderTarget.__webglFramebuffer = [];
  14841. renderTarget.__webglRenderbuffer = [];
  14842. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14843. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14844. for ( var i = 0; i < 6; i ++ ) {
  14845. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14846. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14847. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14848. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14849. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14850. }
  14851. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14852. } else {
  14853. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14854. if ( renderTarget.shareDepthFrom ) {
  14855. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14856. } else {
  14857. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14858. }
  14859. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14860. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14861. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14862. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14863. if ( renderTarget.shareDepthFrom ) {
  14864. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14865. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14866. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14867. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14868. }
  14869. } else {
  14870. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14871. }
  14872. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14873. }
  14874. // Release everything
  14875. if ( isCube ) {
  14876. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14877. } else {
  14878. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14879. }
  14880. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14881. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14882. }
  14883. var framebuffer, width, height, vx, vy;
  14884. if ( renderTarget ) {
  14885. if ( isCube ) {
  14886. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14887. } else {
  14888. framebuffer = renderTarget.__webglFramebuffer;
  14889. }
  14890. width = renderTarget.width;
  14891. height = renderTarget.height;
  14892. vx = 0;
  14893. vy = 0;
  14894. } else {
  14895. framebuffer = null;
  14896. width = _viewportWidth;
  14897. height = _viewportHeight;
  14898. vx = _viewportX;
  14899. vy = _viewportY;
  14900. }
  14901. if ( framebuffer !== _currentFramebuffer ) {
  14902. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14903. _gl.viewport( vx, vy, width, height );
  14904. _currentFramebuffer = framebuffer;
  14905. }
  14906. _currentWidth = width;
  14907. _currentHeight = height;
  14908. };
  14909. function updateRenderTargetMipmap ( renderTarget ) {
  14910. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14911. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14912. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14913. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14914. } else {
  14915. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14916. _gl.generateMipmap( _gl.TEXTURE_2D );
  14917. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14918. }
  14919. };
  14920. // Fallback filters for non-power-of-2 textures
  14921. function filterFallback ( f ) {
  14922. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14923. return _gl.NEAREST;
  14924. }
  14925. return _gl.LINEAR;
  14926. };
  14927. // Map three.js constants to WebGL constants
  14928. function paramThreeToGL ( p ) {
  14929. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14930. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14931. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14932. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14933. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14934. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14935. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14936. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14937. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14938. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14939. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14940. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14941. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14942. if ( p === THREE.ByteType ) return _gl.BYTE;
  14943. if ( p === THREE.ShortType ) return _gl.SHORT;
  14944. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14945. if ( p === THREE.IntType ) return _gl.INT;
  14946. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14947. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14948. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14949. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14950. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14951. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14952. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14953. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14954. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14955. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14956. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14957. if ( p === THREE.OneFactor ) return _gl.ONE;
  14958. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14959. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14960. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14961. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14962. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14963. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14964. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14965. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14966. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14967. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14968. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14969. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14970. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14971. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14972. }
  14973. return 0;
  14974. };
  14975. // Allocations
  14976. function allocateBones ( object ) {
  14977. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14978. return 1024;
  14979. } else {
  14980. // default for when object is not specified
  14981. // ( for example when prebuilding shader
  14982. // to be used with multiple objects )
  14983. //
  14984. // - leave some extra space for other uniforms
  14985. // - limit here is ANGLE's 254 max uniform vectors
  14986. // (up to 54 should be safe)
  14987. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14988. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14989. var maxBones = nVertexMatrices;
  14990. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14991. maxBones = Math.min( object.bones.length, maxBones );
  14992. if ( maxBones < object.bones.length ) {
  14993. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14994. }
  14995. }
  14996. return maxBones;
  14997. }
  14998. };
  14999. function allocateLights ( lights ) {
  15000. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  15001. dirLights = pointLights = spotLights = hemiLights = 0;
  15002. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15003. light = lights[ l ];
  15004. if ( light.onlyShadow ) continue;
  15005. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15006. if ( light instanceof THREE.PointLight ) pointLights ++;
  15007. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15008. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15009. }
  15010. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15011. };
  15012. function allocateShadows ( lights ) {
  15013. var l, ll, light, maxShadows = 0;
  15014. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  15015. light = lights[ l ];
  15016. if ( ! light.castShadow ) continue;
  15017. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15018. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15019. }
  15020. return maxShadows;
  15021. };
  15022. // Initialization
  15023. function initGL () {
  15024. try {
  15025. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15026. throw 'Error creating WebGL context.';
  15027. }
  15028. } catch ( error ) {
  15029. console.error( error );
  15030. }
  15031. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15032. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15033. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15034. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15035. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15036. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15037. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15038. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15039. if ( ! _glExtensionTextureFloat ) {
  15040. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15041. }
  15042. if ( ! _glExtensionStandardDerivatives ) {
  15043. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15044. }
  15045. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15046. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15047. }
  15048. if ( ! _glExtensionCompressedTextureS3TC ) {
  15049. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15050. }
  15051. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15052. _gl.getShaderPrecisionFormat = function() {
  15053. return {
  15054. "rangeMin" : 1,
  15055. "rangeMax" : 1,
  15056. "precision" : 1
  15057. };
  15058. }
  15059. }
  15060. };
  15061. function setDefaultGLState () {
  15062. _gl.clearColor( 0, 0, 0, 1 );
  15063. _gl.clearDepth( 1 );
  15064. _gl.clearStencil( 0 );
  15065. _gl.enable( _gl.DEPTH_TEST );
  15066. _gl.depthFunc( _gl.LEQUAL );
  15067. _gl.frontFace( _gl.CCW );
  15068. _gl.cullFace( _gl.BACK );
  15069. _gl.enable( _gl.CULL_FACE );
  15070. _gl.enable( _gl.BLEND );
  15071. _gl.blendEquation( _gl.FUNC_ADD );
  15072. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15073. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15074. };
  15075. // default plugins (order is important)
  15076. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15077. this.addPrePlugin( this.shadowMapPlugin );
  15078. this.addPostPlugin( new THREE.SpritePlugin() );
  15079. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15080. };
  15081. /**
  15082. * @author szimek / https://github.com/szimek/
  15083. * @author alteredq / http://alteredqualia.com/
  15084. */
  15085. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15086. THREE.EventDispatcher.call( this );
  15087. this.width = width;
  15088. this.height = height;
  15089. options = options || {};
  15090. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15091. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15092. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15093. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15094. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15095. this.offset = new THREE.Vector2( 0, 0 );
  15096. this.repeat = new THREE.Vector2( 1, 1 );
  15097. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15098. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15099. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15100. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15101. this.generateMipmaps = true;
  15102. this.shareDepthFrom = null;
  15103. };
  15104. THREE.WebGLRenderTarget.prototype.clone = function() {
  15105. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15106. tmp.wrapS = this.wrapS;
  15107. tmp.wrapT = this.wrapT;
  15108. tmp.magFilter = this.magFilter;
  15109. tmp.minFilter = this.minFilter;
  15110. tmp.anisotropy = this.anisotropy;
  15111. tmp.offset.copy( this.offset );
  15112. tmp.repeat.copy( this.repeat );
  15113. tmp.format = this.format;
  15114. tmp.type = this.type;
  15115. tmp.depthBuffer = this.depthBuffer;
  15116. tmp.stencilBuffer = this.stencilBuffer;
  15117. tmp.generateMipmaps = this.generateMipmaps;
  15118. tmp.shareDepthFrom = this.shareDepthFrom;
  15119. return tmp;
  15120. };
  15121. THREE.WebGLRenderTarget.prototype.dispose = function () {
  15122. this.dispatchEvent( { type: 'dispose' } );
  15123. };
  15124. /**
  15125. * @author alteredq / http://alteredqualia.com
  15126. */
  15127. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15128. THREE.WebGLRenderTarget.call( this, width, height, options );
  15129. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15130. };
  15131. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15132. /**
  15133. * @author mrdoob / http://mrdoob.com/
  15134. */
  15135. THREE.RenderableVertex = function () {
  15136. this.positionWorld = new THREE.Vector3();
  15137. this.positionScreen = new THREE.Vector4();
  15138. this.visible = true;
  15139. };
  15140. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15141. this.positionWorld.copy( vertex.positionWorld );
  15142. this.positionScreen.copy( vertex.positionScreen );
  15143. };
  15144. /**
  15145. * @author mrdoob / http://mrdoob.com/
  15146. */
  15147. THREE.RenderableFace3 = function () {
  15148. this.v1 = new THREE.RenderableVertex();
  15149. this.v2 = new THREE.RenderableVertex();
  15150. this.v3 = new THREE.RenderableVertex();
  15151. this.centroidModel = new THREE.Vector3();
  15152. this.normalModel = new THREE.Vector3();
  15153. this.normalModelView = new THREE.Vector3();
  15154. this.vertexNormalsLength = 0;
  15155. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15156. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15157. this.color = null;
  15158. this.material = null;
  15159. this.uvs = [[]];
  15160. this.z = null;
  15161. };
  15162. /**
  15163. * @author mrdoob / http://mrdoob.com/
  15164. */
  15165. THREE.RenderableFace4 = function () {
  15166. this.v1 = new THREE.RenderableVertex();
  15167. this.v2 = new THREE.RenderableVertex();
  15168. this.v3 = new THREE.RenderableVertex();
  15169. this.v4 = new THREE.RenderableVertex();
  15170. this.centroidModel = new THREE.Vector3();
  15171. this.normalModel = new THREE.Vector3();
  15172. this.normalModelView = new THREE.Vector3();
  15173. this.vertexNormalsLength = 0;
  15174. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15175. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15176. this.color = null;
  15177. this.material = null;
  15178. this.uvs = [[]];
  15179. this.z = null;
  15180. };
  15181. /**
  15182. * @author mrdoob / http://mrdoob.com/
  15183. */
  15184. THREE.RenderableObject = function () {
  15185. this.object = null;
  15186. this.z = null;
  15187. };
  15188. /**
  15189. * @author mrdoob / http://mrdoob.com/
  15190. */
  15191. THREE.RenderableParticle = function () {
  15192. this.object = null;
  15193. this.x = null;
  15194. this.y = null;
  15195. this.z = null;
  15196. this.rotation = null;
  15197. this.scale = new THREE.Vector2();
  15198. this.material = null;
  15199. };
  15200. /**
  15201. * @author mrdoob / http://mrdoob.com/
  15202. */
  15203. THREE.RenderableLine = function () {
  15204. this.z = null;
  15205. this.v1 = new THREE.RenderableVertex();
  15206. this.v2 = new THREE.RenderableVertex();
  15207. this.material = null;
  15208. };
  15209. /**
  15210. * @author mrdoob / http://mrdoob.com/
  15211. * @author alteredq / http://alteredqualia.com/
  15212. */
  15213. THREE.GeometryUtils = {
  15214. // Merge two geometries or geometry and geometry from object (using object's transform)
  15215. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  15216. var matrix, normalMatrix,
  15217. vertexOffset = geometry1.vertices.length,
  15218. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15219. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15220. vertices1 = geometry1.vertices,
  15221. vertices2 = geometry2.vertices,
  15222. faces1 = geometry1.faces,
  15223. faces2 = geometry2.faces,
  15224. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15225. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15226. if ( object2 instanceof THREE.Mesh ) {
  15227. object2.matrixAutoUpdate && object2.updateMatrix();
  15228. matrix = object2.matrix;
  15229. normalMatrix = new THREE.Matrix3();
  15230. normalMatrix.getInverse( matrix );
  15231. normalMatrix.transpose();
  15232. }
  15233. // vertices
  15234. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15235. var vertex = vertices2[ i ];
  15236. var vertexCopy = vertex.clone();
  15237. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15238. vertices1.push( vertexCopy );
  15239. }
  15240. // faces
  15241. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15242. var face = faces2[ i ], faceCopy, normal, color,
  15243. faceVertexNormals = face.vertexNormals,
  15244. faceVertexColors = face.vertexColors;
  15245. if ( face instanceof THREE.Face3 ) {
  15246. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15247. } else if ( face instanceof THREE.Face4 ) {
  15248. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15249. }
  15250. faceCopy.normal.copy( face.normal );
  15251. if ( normalMatrix ) {
  15252. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15253. }
  15254. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15255. normal = faceVertexNormals[ j ].clone();
  15256. if ( normalMatrix ) {
  15257. normal.applyMatrix3( normalMatrix ).normalize();
  15258. }
  15259. faceCopy.vertexNormals.push( normal );
  15260. }
  15261. faceCopy.color.copy( face.color );
  15262. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15263. color = faceVertexColors[ j ];
  15264. faceCopy.vertexColors.push( color.clone() );
  15265. }
  15266. faceCopy.materialIndex = face.materialIndex;
  15267. faceCopy.centroid.copy( face.centroid );
  15268. if ( matrix ) {
  15269. faceCopy.centroid.applyMatrix4( matrix );
  15270. }
  15271. faces1.push( faceCopy );
  15272. }
  15273. // uvs
  15274. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15275. var uv = uvs2[ i ], uvCopy = [];
  15276. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15277. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15278. }
  15279. uvs1.push( uvCopy );
  15280. }
  15281. },
  15282. removeMaterials: function ( geometry, materialIndexArray ) {
  15283. var materialIndexMap = {};
  15284. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15285. materialIndexMap[ materialIndexArray[i] ] = true;
  15286. }
  15287. var face, newFaces = [];
  15288. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15289. face = geometry.faces[ i ];
  15290. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15291. }
  15292. geometry.faces = newFaces;
  15293. },
  15294. // Get random point in triangle (via barycentric coordinates)
  15295. // (uniform distribution)
  15296. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15297. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15298. var a, b, c,
  15299. point = new THREE.Vector3(),
  15300. tmp = THREE.GeometryUtils.__v1;
  15301. a = THREE.GeometryUtils.random();
  15302. b = THREE.GeometryUtils.random();
  15303. if ( ( a + b ) > 1 ) {
  15304. a = 1 - a;
  15305. b = 1 - b;
  15306. }
  15307. c = 1 - a - b;
  15308. point.copy( vectorA );
  15309. point.multiplyScalar( a );
  15310. tmp.copy( vectorB );
  15311. tmp.multiplyScalar( b );
  15312. point.add( tmp );
  15313. tmp.copy( vectorC );
  15314. tmp.multiplyScalar( c );
  15315. point.add( tmp );
  15316. return point;
  15317. },
  15318. // Get random point in face (triangle / quad)
  15319. // (uniform distribution)
  15320. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15321. var vA, vB, vC, vD;
  15322. if ( face instanceof THREE.Face3 ) {
  15323. vA = geometry.vertices[ face.a ];
  15324. vB = geometry.vertices[ face.b ];
  15325. vC = geometry.vertices[ face.c ];
  15326. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15327. } else if ( face instanceof THREE.Face4 ) {
  15328. vA = geometry.vertices[ face.a ];
  15329. vB = geometry.vertices[ face.b ];
  15330. vC = geometry.vertices[ face.c ];
  15331. vD = geometry.vertices[ face.d ];
  15332. var area1, area2;
  15333. if ( useCachedAreas ) {
  15334. if ( face._area1 && face._area2 ) {
  15335. area1 = face._area1;
  15336. area2 = face._area2;
  15337. } else {
  15338. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15339. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15340. face._area1 = area1;
  15341. face._area2 = area2;
  15342. }
  15343. } else {
  15344. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15345. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15346. }
  15347. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15348. if ( r < area1 ) {
  15349. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15350. } else {
  15351. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15352. }
  15353. }
  15354. },
  15355. // Get uniformly distributed random points in mesh
  15356. // - create array with cumulative sums of face areas
  15357. // - pick random number from 0 to total area
  15358. // - find corresponding place in area array by binary search
  15359. // - get random point in face
  15360. randomPointsInGeometry: function ( geometry, n ) {
  15361. var face, i,
  15362. faces = geometry.faces,
  15363. vertices = geometry.vertices,
  15364. il = faces.length,
  15365. totalArea = 0,
  15366. cumulativeAreas = [],
  15367. vA, vB, vC, vD;
  15368. // precompute face areas
  15369. for ( i = 0; i < il; i ++ ) {
  15370. face = faces[ i ];
  15371. if ( face instanceof THREE.Face3 ) {
  15372. vA = vertices[ face.a ];
  15373. vB = vertices[ face.b ];
  15374. vC = vertices[ face.c ];
  15375. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15376. } else if ( face instanceof THREE.Face4 ) {
  15377. vA = vertices[ face.a ];
  15378. vB = vertices[ face.b ];
  15379. vC = vertices[ face.c ];
  15380. vD = vertices[ face.d ];
  15381. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15382. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15383. face._area = face._area1 + face._area2;
  15384. }
  15385. totalArea += face._area;
  15386. cumulativeAreas[ i ] = totalArea;
  15387. }
  15388. // binary search cumulative areas array
  15389. function binarySearchIndices( value ) {
  15390. function binarySearch( start, end ) {
  15391. // return closest larger index
  15392. // if exact number is not found
  15393. if ( end < start )
  15394. return start;
  15395. var mid = start + Math.floor( ( end - start ) / 2 );
  15396. if ( cumulativeAreas[ mid ] > value ) {
  15397. return binarySearch( start, mid - 1 );
  15398. } else if ( cumulativeAreas[ mid ] < value ) {
  15399. return binarySearch( mid + 1, end );
  15400. } else {
  15401. return mid;
  15402. }
  15403. }
  15404. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15405. return result;
  15406. }
  15407. // pick random face weighted by face area
  15408. var r, index,
  15409. result = [];
  15410. var stats = {};
  15411. for ( i = 0; i < n; i ++ ) {
  15412. r = THREE.GeometryUtils.random() * totalArea;
  15413. index = binarySearchIndices( r );
  15414. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15415. if ( ! stats[ index ] ) {
  15416. stats[ index ] = 1;
  15417. } else {
  15418. stats[ index ] += 1;
  15419. }
  15420. }
  15421. return result;
  15422. },
  15423. // Get triangle area (half of parallelogram)
  15424. // http://mathworld.wolfram.com/TriangleArea.html
  15425. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15426. var tmp1 = THREE.GeometryUtils.__v1,
  15427. tmp2 = THREE.GeometryUtils.__v2;
  15428. tmp1.subVectors( vectorB, vectorA );
  15429. tmp2.subVectors( vectorC, vectorA );
  15430. tmp1.cross( tmp2 );
  15431. return 0.5 * tmp1.length();
  15432. },
  15433. // Center geometry so that 0,0,0 is in center of bounding box
  15434. center: function ( geometry ) {
  15435. geometry.computeBoundingBox();
  15436. var bb = geometry.boundingBox;
  15437. var offset = new THREE.Vector3();
  15438. offset.addVectors( bb.min, bb.max );
  15439. offset.multiplyScalar( -0.5 );
  15440. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15441. geometry.computeBoundingBox();
  15442. return offset;
  15443. },
  15444. // Normalize UVs to be from <0,1>
  15445. // (for now just the first set of UVs)
  15446. normalizeUVs: function ( geometry ) {
  15447. var uvSet = geometry.faceVertexUvs[ 0 ];
  15448. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15449. var uvs = uvSet[ i ];
  15450. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15451. // texture repeat
  15452. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15453. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15454. }
  15455. }
  15456. },
  15457. triangulateQuads: function ( geometry ) {
  15458. var i, il, j, jl;
  15459. var faces = [];
  15460. var faceUvs = [];
  15461. var faceVertexUvs = [];
  15462. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15463. faceUvs[ i ] = [];
  15464. }
  15465. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15466. faceVertexUvs[ i ] = [];
  15467. }
  15468. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15469. var face = geometry.faces[ i ];
  15470. if ( face instanceof THREE.Face4 ) {
  15471. var a = face.a;
  15472. var b = face.b;
  15473. var c = face.c;
  15474. var d = face.d;
  15475. var triA = new THREE.Face3();
  15476. var triB = new THREE.Face3();
  15477. triA.color.copy( face.color );
  15478. triB.color.copy( face.color );
  15479. triA.materialIndex = face.materialIndex;
  15480. triB.materialIndex = face.materialIndex;
  15481. triA.a = a;
  15482. triA.b = b;
  15483. triA.c = d;
  15484. triB.a = b;
  15485. triB.b = c;
  15486. triB.c = d;
  15487. if ( face.vertexColors.length === 4 ) {
  15488. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15489. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15490. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15491. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15492. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15493. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15494. }
  15495. faces.push( triA, triB );
  15496. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15497. if ( geometry.faceVertexUvs[ j ].length ) {
  15498. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15499. var uvA = uvs[ 0 ];
  15500. var uvB = uvs[ 1 ];
  15501. var uvC = uvs[ 2 ];
  15502. var uvD = uvs[ 3 ];
  15503. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15504. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15505. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15506. }
  15507. }
  15508. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15509. if ( geometry.faceUvs[ j ].length ) {
  15510. var faceUv = geometry.faceUvs[ j ][ i ];
  15511. faceUvs[ j ].push( faceUv, faceUv );
  15512. }
  15513. }
  15514. } else {
  15515. faces.push( face );
  15516. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15517. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15518. }
  15519. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15520. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15521. }
  15522. }
  15523. }
  15524. geometry.faces = faces;
  15525. geometry.faceUvs = faceUvs;
  15526. geometry.faceVertexUvs = faceVertexUvs;
  15527. geometry.computeCentroids();
  15528. geometry.computeFaceNormals();
  15529. geometry.computeVertexNormals();
  15530. if ( geometry.hasTangents ) geometry.computeTangents();
  15531. },
  15532. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15533. var faces = geometry.faces;
  15534. var start = startFace || 0;
  15535. var end = endFace || faces.length - 1;
  15536. for ( var i = start; i <= end; i ++ ) {
  15537. faces[i].materialIndex = index;
  15538. }
  15539. }
  15540. };
  15541. THREE.GeometryUtils.random = THREE.Math.random16;
  15542. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15543. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15544. /**
  15545. * @author alteredq / http://alteredqualia.com/
  15546. * @author mrdoob / http://mrdoob.com/
  15547. */
  15548. THREE.ImageUtils = {
  15549. crossOrigin: 'anonymous',
  15550. loadTexture: function ( url, mapping, onLoad, onError ) {
  15551. var image = new Image();
  15552. var texture = new THREE.Texture( image, mapping );
  15553. var loader = new THREE.ImageLoader();
  15554. loader.addEventListener( 'load', function ( event ) {
  15555. texture.image = event.content;
  15556. texture.needsUpdate = true;
  15557. if ( onLoad ) onLoad( texture );
  15558. } );
  15559. loader.addEventListener( 'error', function ( event ) {
  15560. if ( onError ) onError( event.message );
  15561. } );
  15562. loader.crossOrigin = this.crossOrigin;
  15563. loader.load( url, image );
  15564. texture.sourceFile = url;
  15565. return texture;
  15566. },
  15567. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15568. var texture = new THREE.CompressedTexture();
  15569. texture.mapping = mapping;
  15570. var request = new XMLHttpRequest();
  15571. request.onload = function () {
  15572. var buffer = request.response;
  15573. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15574. texture.format = dds.format;
  15575. texture.mipmaps = dds.mipmaps;
  15576. texture.image.width = dds.width;
  15577. texture.image.height = dds.height;
  15578. // gl.generateMipmap fails for compressed textures
  15579. // mipmaps must be embedded in the DDS file
  15580. // or texture filters must not use mipmapping
  15581. texture.generateMipmaps = false;
  15582. texture.needsUpdate = true;
  15583. if ( onLoad ) onLoad( texture );
  15584. }
  15585. request.onerror = onError;
  15586. request.open( 'GET', url, true );
  15587. request.responseType = "arraybuffer";
  15588. request.send( null );
  15589. return texture;
  15590. },
  15591. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15592. var images = [];
  15593. images.loadCount = 0;
  15594. var texture = new THREE.Texture();
  15595. texture.image = images;
  15596. if ( mapping !== undefined ) texture.mapping = mapping;
  15597. // no flipping needed for cube textures
  15598. texture.flipY = false;
  15599. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15600. var cubeImage = new Image();
  15601. images[ i ] = cubeImage;
  15602. cubeImage.onload = function () {
  15603. images.loadCount += 1;
  15604. if ( images.loadCount === 6 ) {
  15605. texture.needsUpdate = true;
  15606. if ( onLoad ) onLoad( texture );
  15607. }
  15608. };
  15609. cubeImage.onerror = onError;
  15610. cubeImage.crossOrigin = this.crossOrigin;
  15611. cubeImage.src = array[ i ];
  15612. }
  15613. return texture;
  15614. },
  15615. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15616. var images = [];
  15617. images.loadCount = 0;
  15618. var texture = new THREE.CompressedTexture();
  15619. texture.image = images;
  15620. if ( mapping !== undefined ) texture.mapping = mapping;
  15621. // no flipping for cube textures
  15622. // (also flipping doesn't work for compressed textures )
  15623. texture.flipY = false;
  15624. // can't generate mipmaps for compressed textures
  15625. // mips must be embedded in DDS files
  15626. texture.generateMipmaps = false;
  15627. var generateCubeFaceCallback = function ( rq, img ) {
  15628. return function () {
  15629. var buffer = rq.response;
  15630. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15631. img.format = dds.format;
  15632. img.mipmaps = dds.mipmaps;
  15633. img.width = dds.width;
  15634. img.height = dds.height;
  15635. images.loadCount += 1;
  15636. if ( images.loadCount === 6 ) {
  15637. texture.format = dds.format;
  15638. texture.needsUpdate = true;
  15639. if ( onLoad ) onLoad( texture );
  15640. }
  15641. }
  15642. }
  15643. // compressed cubemap textures as 6 separate DDS files
  15644. if ( array instanceof Array ) {
  15645. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15646. var cubeImage = {};
  15647. images[ i ] = cubeImage;
  15648. var request = new XMLHttpRequest();
  15649. request.onload = generateCubeFaceCallback( request, cubeImage );
  15650. request.onerror = onError;
  15651. var url = array[ i ];
  15652. request.open( 'GET', url, true );
  15653. request.responseType = "arraybuffer";
  15654. request.send( null );
  15655. }
  15656. // compressed cubemap texture stored in a single DDS file
  15657. } else {
  15658. var url = array;
  15659. var request = new XMLHttpRequest();
  15660. request.onload = function( ) {
  15661. var buffer = request.response;
  15662. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15663. if ( dds.isCubemap ) {
  15664. var faces = dds.mipmaps.length / dds.mipmapCount;
  15665. for ( var f = 0; f < faces; f ++ ) {
  15666. images[ f ] = { mipmaps : [] };
  15667. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15668. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15669. images[ f ].format = dds.format;
  15670. images[ f ].width = dds.width;
  15671. images[ f ].height = dds.height;
  15672. }
  15673. }
  15674. texture.format = dds.format;
  15675. texture.needsUpdate = true;
  15676. if ( onLoad ) onLoad( texture );
  15677. }
  15678. }
  15679. request.onerror = onError;
  15680. request.open( 'GET', url, true );
  15681. request.responseType = "arraybuffer";
  15682. request.send( null );
  15683. }
  15684. return texture;
  15685. },
  15686. parseDDS: function ( buffer, loadMipmaps ) {
  15687. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15688. // Adapted from @toji's DDS utils
  15689. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15690. // All values and structures referenced from:
  15691. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15692. var DDS_MAGIC = 0x20534444;
  15693. var DDSD_CAPS = 0x1,
  15694. DDSD_HEIGHT = 0x2,
  15695. DDSD_WIDTH = 0x4,
  15696. DDSD_PITCH = 0x8,
  15697. DDSD_PIXELFORMAT = 0x1000,
  15698. DDSD_MIPMAPCOUNT = 0x20000,
  15699. DDSD_LINEARSIZE = 0x80000,
  15700. DDSD_DEPTH = 0x800000;
  15701. var DDSCAPS_COMPLEX = 0x8,
  15702. DDSCAPS_MIPMAP = 0x400000,
  15703. DDSCAPS_TEXTURE = 0x1000;
  15704. var DDSCAPS2_CUBEMAP = 0x200,
  15705. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15706. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15707. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15708. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15709. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15710. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15711. DDSCAPS2_VOLUME = 0x200000;
  15712. var DDPF_ALPHAPIXELS = 0x1,
  15713. DDPF_ALPHA = 0x2,
  15714. DDPF_FOURCC = 0x4,
  15715. DDPF_RGB = 0x40,
  15716. DDPF_YUV = 0x200,
  15717. DDPF_LUMINANCE = 0x20000;
  15718. function fourCCToInt32( value ) {
  15719. return value.charCodeAt(0) +
  15720. (value.charCodeAt(1) << 8) +
  15721. (value.charCodeAt(2) << 16) +
  15722. (value.charCodeAt(3) << 24);
  15723. }
  15724. function int32ToFourCC( value ) {
  15725. return String.fromCharCode(
  15726. value & 0xff,
  15727. (value >> 8) & 0xff,
  15728. (value >> 16) & 0xff,
  15729. (value >> 24) & 0xff
  15730. );
  15731. }
  15732. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15733. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15734. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15735. var headerLengthInt = 31; // The header length in 32 bit ints
  15736. // Offsets into the header array
  15737. var off_magic = 0;
  15738. var off_size = 1;
  15739. var off_flags = 2;
  15740. var off_height = 3;
  15741. var off_width = 4;
  15742. var off_mipmapCount = 7;
  15743. var off_pfFlags = 20;
  15744. var off_pfFourCC = 21;
  15745. var off_caps = 27;
  15746. var off_caps2 = 28;
  15747. var off_caps3 = 29;
  15748. var off_caps4 = 30;
  15749. // Parse header
  15750. var header = new Int32Array( buffer, 0, headerLengthInt );
  15751. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15752. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15753. return dds;
  15754. }
  15755. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15756. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15757. return dds;
  15758. }
  15759. var blockBytes;
  15760. var fourCC = header[ off_pfFourCC ];
  15761. switch ( fourCC ) {
  15762. case FOURCC_DXT1:
  15763. blockBytes = 8;
  15764. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15765. break;
  15766. case FOURCC_DXT3:
  15767. blockBytes = 16;
  15768. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15769. break;
  15770. case FOURCC_DXT5:
  15771. blockBytes = 16;
  15772. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15773. break;
  15774. default:
  15775. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15776. return dds;
  15777. }
  15778. dds.mipmapCount = 1;
  15779. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15780. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15781. }
  15782. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15783. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15784. dds.width = header[ off_width ];
  15785. dds.height = header[ off_height ];
  15786. var dataOffset = header[ off_size ] + 4;
  15787. // Extract mipmaps buffers
  15788. var width = dds.width;
  15789. var height = dds.height;
  15790. var faces = dds.isCubemap ? 6 : 1;
  15791. for ( var face = 0; face < faces; face ++ ) {
  15792. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15793. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15794. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15795. var mipmap = { "data": byteArray, "width": width, "height": height };
  15796. dds.mipmaps.push( mipmap );
  15797. dataOffset += dataLength;
  15798. width = Math.max( width * 0.5, 1 );
  15799. height = Math.max( height * 0.5, 1 );
  15800. }
  15801. width = dds.width;
  15802. height = dds.height;
  15803. }
  15804. return dds;
  15805. },
  15806. getNormalMap: function ( image, depth ) {
  15807. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15808. var cross = function ( a, b ) {
  15809. 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 ] ];
  15810. }
  15811. var subtract = function ( a, b ) {
  15812. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15813. }
  15814. var normalize = function ( a ) {
  15815. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15816. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15817. }
  15818. depth = depth | 1;
  15819. var width = image.width;
  15820. var height = image.height;
  15821. var canvas = document.createElement( 'canvas' );
  15822. canvas.width = width;
  15823. canvas.height = height;
  15824. var context = canvas.getContext( '2d' );
  15825. context.drawImage( image, 0, 0 );
  15826. var data = context.getImageData( 0, 0, width, height ).data;
  15827. var imageData = context.createImageData( width, height );
  15828. var output = imageData.data;
  15829. for ( var x = 0; x < width; x ++ ) {
  15830. for ( var y = 0; y < height; y ++ ) {
  15831. var ly = y - 1 < 0 ? 0 : y - 1;
  15832. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15833. var lx = x - 1 < 0 ? 0 : x - 1;
  15834. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15835. var points = [];
  15836. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15837. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15838. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15839. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15840. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15841. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15842. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15843. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15844. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15845. var normals = [];
  15846. var num_points = points.length;
  15847. for ( var i = 0; i < num_points; i ++ ) {
  15848. var v1 = points[ i ];
  15849. var v2 = points[ ( i + 1 ) % num_points ];
  15850. v1 = subtract( v1, origin );
  15851. v2 = subtract( v2, origin );
  15852. normals.push( normalize( cross( v1, v2 ) ) );
  15853. }
  15854. var normal = [ 0, 0, 0 ];
  15855. for ( var i = 0; i < normals.length; i ++ ) {
  15856. normal[ 0 ] += normals[ i ][ 0 ];
  15857. normal[ 1 ] += normals[ i ][ 1 ];
  15858. normal[ 2 ] += normals[ i ][ 2 ];
  15859. }
  15860. normal[ 0 ] /= normals.length;
  15861. normal[ 1 ] /= normals.length;
  15862. normal[ 2 ] /= normals.length;
  15863. var idx = ( y * width + x ) * 4;
  15864. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15865. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15866. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15867. output[ idx + 3 ] = 255;
  15868. }
  15869. }
  15870. context.putImageData( imageData, 0, 0 );
  15871. return canvas;
  15872. },
  15873. generateDataTexture: function ( width, height, color ) {
  15874. var size = width * height;
  15875. var data = new Uint8Array( 3 * size );
  15876. var r = Math.floor( color.r * 255 );
  15877. var g = Math.floor( color.g * 255 );
  15878. var b = Math.floor( color.b * 255 );
  15879. for ( var i = 0; i < size; i ++ ) {
  15880. data[ i * 3 ] = r;
  15881. data[ i * 3 + 1 ] = g;
  15882. data[ i * 3 + 2 ] = b;
  15883. }
  15884. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15885. texture.needsUpdate = true;
  15886. return texture;
  15887. }
  15888. };
  15889. /**
  15890. * @author alteredq / http://alteredqualia.com/
  15891. */
  15892. THREE.SceneUtils = {
  15893. createMultiMaterialObject: function ( geometry, materials ) {
  15894. var group = new THREE.Object3D();
  15895. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15896. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15897. }
  15898. return group;
  15899. },
  15900. detach : function ( child, parent, scene ) {
  15901. child.applyMatrix( parent.matrixWorld );
  15902. parent.remove( child );
  15903. scene.add( child );
  15904. },
  15905. attach: function ( child, scene, parent ) {
  15906. var matrixWorldInverse = new THREE.Matrix4();
  15907. matrixWorldInverse.getInverse( parent.matrixWorld );
  15908. child.applyMatrix( matrixWorldInverse );
  15909. scene.remove( child );
  15910. parent.add( child );
  15911. }
  15912. };
  15913. /**
  15914. * @author zz85 / http://www.lab4games.net/zz85/blog
  15915. * @author alteredq / http://alteredqualia.com/
  15916. *
  15917. * For Text operations in three.js (See TextGeometry)
  15918. *
  15919. * It uses techniques used in:
  15920. *
  15921. * typeface.js and canvastext
  15922. * For converting fonts and rendering with javascript
  15923. * http://typeface.neocracy.org
  15924. *
  15925. * Triangulation ported from AS3
  15926. * Simple Polygon Triangulation
  15927. * http://actionsnippet.com/?p=1462
  15928. *
  15929. * A Method to triangulate shapes with holes
  15930. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15931. *
  15932. */
  15933. THREE.FontUtils = {
  15934. faces : {},
  15935. // Just for now. face[weight][style]
  15936. face : "helvetiker",
  15937. weight: "normal",
  15938. style : "normal",
  15939. size : 150,
  15940. divisions : 10,
  15941. getFace : function() {
  15942. return this.faces[ this.face ][ this.weight ][ this.style ];
  15943. },
  15944. loadFace : function( data ) {
  15945. var family = data.familyName.toLowerCase();
  15946. var ThreeFont = this;
  15947. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15948. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15949. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15950. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15951. return data;
  15952. },
  15953. drawText : function( text ) {
  15954. var characterPts = [], allPts = [];
  15955. // RenderText
  15956. var i, p,
  15957. face = this.getFace(),
  15958. scale = this.size / face.resolution,
  15959. offset = 0,
  15960. chars = String( text ).split( '' ),
  15961. length = chars.length;
  15962. var fontPaths = [];
  15963. for ( i = 0; i < length; i ++ ) {
  15964. var path = new THREE.Path();
  15965. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15966. offset += ret.offset;
  15967. fontPaths.push( ret.path );
  15968. }
  15969. // get the width
  15970. var width = offset / 2;
  15971. //
  15972. // for ( p = 0; p < allPts.length; p++ ) {
  15973. //
  15974. // allPts[ p ].x -= width;
  15975. //
  15976. // }
  15977. //var extract = this.extractPoints( allPts, characterPts );
  15978. //extract.contour = allPts;
  15979. //extract.paths = fontPaths;
  15980. //extract.offset = width;
  15981. return { paths : fontPaths, offset : width };
  15982. },
  15983. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15984. var pts = [];
  15985. var i, i2, divisions,
  15986. outline, action, length,
  15987. scaleX, scaleY,
  15988. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15989. laste,
  15990. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15991. if ( !glyph ) return;
  15992. if ( glyph.o ) {
  15993. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15994. length = outline.length;
  15995. scaleX = scale;
  15996. scaleY = scale;
  15997. for ( i = 0; i < length; ) {
  15998. action = outline[ i ++ ];
  15999. //console.log( action );
  16000. switch( action ) {
  16001. case 'm':
  16002. // Move To
  16003. x = outline[ i++ ] * scaleX + offset;
  16004. y = outline[ i++ ] * scaleY;
  16005. path.moveTo( x, y );
  16006. break;
  16007. case 'l':
  16008. // Line To
  16009. x = outline[ i++ ] * scaleX + offset;
  16010. y = outline[ i++ ] * scaleY;
  16011. path.lineTo(x,y);
  16012. break;
  16013. case 'q':
  16014. // QuadraticCurveTo
  16015. cpx = outline[ i++ ] * scaleX + offset;
  16016. cpy = outline[ i++ ] * scaleY;
  16017. cpx1 = outline[ i++ ] * scaleX + offset;
  16018. cpy1 = outline[ i++ ] * scaleY;
  16019. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16020. laste = pts[ pts.length - 1 ];
  16021. if ( laste ) {
  16022. cpx0 = laste.x;
  16023. cpy0 = laste.y;
  16024. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16025. var t = i2 / divisions;
  16026. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16027. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16028. }
  16029. }
  16030. break;
  16031. case 'b':
  16032. // Cubic Bezier Curve
  16033. cpx = outline[ i++ ] * scaleX + offset;
  16034. cpy = outline[ i++ ] * scaleY;
  16035. cpx1 = outline[ i++ ] * scaleX + offset;
  16036. cpy1 = outline[ i++ ] * -scaleY;
  16037. cpx2 = outline[ i++ ] * scaleX + offset;
  16038. cpy2 = outline[ i++ ] * -scaleY;
  16039. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16040. laste = pts[ pts.length - 1 ];
  16041. if ( laste ) {
  16042. cpx0 = laste.x;
  16043. cpy0 = laste.y;
  16044. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16045. var t = i2 / divisions;
  16046. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16047. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16048. }
  16049. }
  16050. break;
  16051. }
  16052. }
  16053. }
  16054. return { offset: glyph.ha*scale, path:path};
  16055. }
  16056. };
  16057. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16058. // Parameters
  16059. parameters = parameters || {};
  16060. var size = parameters.size !== undefined ? parameters.size : 100;
  16061. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16062. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16063. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16064. var style = parameters.style !== undefined ? parameters.style : "normal";
  16065. THREE.FontUtils.size = size;
  16066. THREE.FontUtils.divisions = curveSegments;
  16067. THREE.FontUtils.face = font;
  16068. THREE.FontUtils.weight = weight;
  16069. THREE.FontUtils.style = style;
  16070. // Get a Font data json object
  16071. var data = THREE.FontUtils.drawText( text );
  16072. var paths = data.paths;
  16073. var shapes = [];
  16074. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16075. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16076. }
  16077. return shapes;
  16078. };
  16079. /**
  16080. * This code is a quick port of code written in C++ which was submitted to
  16081. * flipcode.com by John W. Ratcliff // July 22, 2000
  16082. * See original code and more information here:
  16083. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16084. *
  16085. * ported to actionscript by Zevan Rosser
  16086. * www.actionsnippet.com
  16087. *
  16088. * ported to javascript by Joshua Koo
  16089. * http://www.lab4games.net/zz85/blog
  16090. *
  16091. */
  16092. ( function( namespace ) {
  16093. var EPSILON = 0.0000000001;
  16094. // takes in an contour array and returns
  16095. var process = function( contour, indices ) {
  16096. var n = contour.length;
  16097. if ( n < 3 ) return null;
  16098. var result = [],
  16099. verts = [],
  16100. vertIndices = [];
  16101. /* we want a counter-clockwise polygon in verts */
  16102. var u, v, w;
  16103. if ( area( contour ) > 0.0 ) {
  16104. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16105. } else {
  16106. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16107. }
  16108. var nv = n;
  16109. /* remove nv - 2 vertices, creating 1 triangle every time */
  16110. var count = 2 * nv; /* error detection */
  16111. for( v = nv - 1; nv > 2; ) {
  16112. /* if we loop, it is probably a non-simple polygon */
  16113. if ( ( count-- ) <= 0 ) {
  16114. //** Triangulate: ERROR - probable bad polygon!
  16115. //throw ( "Warning, unable to triangulate polygon!" );
  16116. //return null;
  16117. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16118. console.log( "Warning, unable to triangulate polygon!" );
  16119. if ( indices ) return vertIndices;
  16120. return result;
  16121. }
  16122. /* three consecutive vertices in current polygon, <u,v,w> */
  16123. u = v; if ( nv <= u ) u = 0; /* previous */
  16124. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16125. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16126. if ( snip( contour, u, v, w, nv, verts ) ) {
  16127. var a, b, c, s, t;
  16128. /* true names of the vertices */
  16129. a = verts[ u ];
  16130. b = verts[ v ];
  16131. c = verts[ w ];
  16132. /* output Triangle */
  16133. result.push( [ contour[ a ],
  16134. contour[ b ],
  16135. contour[ c ] ] );
  16136. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16137. /* remove v from the remaining polygon */
  16138. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16139. verts[ s ] = verts[ t ];
  16140. }
  16141. nv--;
  16142. /* reset error detection counter */
  16143. count = 2 * nv;
  16144. }
  16145. }
  16146. if ( indices ) return vertIndices;
  16147. return result;
  16148. };
  16149. // calculate area of the contour polygon
  16150. var area = function ( contour ) {
  16151. var n = contour.length;
  16152. var a = 0.0;
  16153. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16154. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16155. }
  16156. return a * 0.5;
  16157. };
  16158. var snip = function ( contour, u, v, w, n, verts ) {
  16159. var p;
  16160. var ax, ay, bx, by;
  16161. var cx, cy, px, py;
  16162. ax = contour[ verts[ u ] ].x;
  16163. ay = contour[ verts[ u ] ].y;
  16164. bx = contour[ verts[ v ] ].x;
  16165. by = contour[ verts[ v ] ].y;
  16166. cx = contour[ verts[ w ] ].x;
  16167. cy = contour[ verts[ w ] ].y;
  16168. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16169. var aX, aY, bX, bY, cX, cY;
  16170. var apx, apy, bpx, bpy, cpx, cpy;
  16171. var cCROSSap, bCROSScp, aCROSSbp;
  16172. aX = cx - bx; aY = cy - by;
  16173. bX = ax - cx; bY = ay - cy;
  16174. cX = bx - ax; cY = by - ay;
  16175. for ( p = 0; p < n; p++ ) {
  16176. if( (p === u) || (p === v) || (p === w) ) continue;
  16177. px = contour[ verts[ p ] ].x
  16178. py = contour[ verts[ p ] ].y
  16179. apx = px - ax; apy = py - ay;
  16180. bpx = px - bx; bpy = py - by;
  16181. cpx = px - cx; cpy = py - cy;
  16182. // see if p is inside triangle abc
  16183. aCROSSbp = aX*bpy - aY*bpx;
  16184. cCROSSap = cX*apy - cY*apx;
  16185. bCROSScp = bX*cpy - bY*cpx;
  16186. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16187. }
  16188. return true;
  16189. };
  16190. namespace.Triangulate = process;
  16191. namespace.Triangulate.area = area;
  16192. return namespace;
  16193. })(THREE.FontUtils);
  16194. // To use the typeface.js face files, hook up the API
  16195. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16196. * @author zz85 / http://www.lab4games.net/zz85/blog
  16197. * Extensible curve object
  16198. *
  16199. * Some common of Curve methods
  16200. * .getPoint(t), getTangent(t)
  16201. * .getPointAt(u), getTagentAt(u)
  16202. * .getPoints(), .getSpacedPoints()
  16203. * .getLength()
  16204. * .updateArcLengths()
  16205. *
  16206. * This file contains following classes:
  16207. *
  16208. * -- 2d classes --
  16209. * THREE.Curve
  16210. * THREE.LineCurve
  16211. * THREE.QuadraticBezierCurve
  16212. * THREE.CubicBezierCurve
  16213. * THREE.SplineCurve
  16214. * THREE.ArcCurve
  16215. * THREE.EllipseCurve
  16216. *
  16217. * -- 3d classes --
  16218. * THREE.LineCurve3
  16219. * THREE.QuadraticBezierCurve3
  16220. * THREE.CubicBezierCurve3
  16221. * THREE.SplineCurve3
  16222. * THREE.ClosedSplineCurve3
  16223. *
  16224. * A series of curves can be represented as a THREE.CurvePath
  16225. *
  16226. **/
  16227. /**************************************************************
  16228. * Abstract Curve base class
  16229. **************************************************************/
  16230. THREE.Curve = function () {
  16231. };
  16232. // Virtual base class method to overwrite and implement in subclasses
  16233. // - t [0 .. 1]
  16234. THREE.Curve.prototype.getPoint = function ( t ) {
  16235. console.log( "Warning, getPoint() not implemented!" );
  16236. return null;
  16237. };
  16238. // Get point at relative position in curve according to arc length
  16239. // - u [0 .. 1]
  16240. THREE.Curve.prototype.getPointAt = function ( u ) {
  16241. var t = this.getUtoTmapping( u );
  16242. return this.getPoint( t );
  16243. };
  16244. // Get sequence of points using getPoint( t )
  16245. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16246. if ( !divisions ) divisions = 5;
  16247. var d, pts = [];
  16248. for ( d = 0; d <= divisions; d ++ ) {
  16249. pts.push( this.getPoint( d / divisions ) );
  16250. }
  16251. return pts;
  16252. };
  16253. // Get sequence of points using getPointAt( u )
  16254. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16255. if ( !divisions ) divisions = 5;
  16256. var d, pts = [];
  16257. for ( d = 0; d <= divisions; d ++ ) {
  16258. pts.push( this.getPointAt( d / divisions ) );
  16259. }
  16260. return pts;
  16261. };
  16262. // Get total curve arc length
  16263. THREE.Curve.prototype.getLength = function () {
  16264. var lengths = this.getLengths();
  16265. return lengths[ lengths.length - 1 ];
  16266. };
  16267. // Get list of cumulative segment lengths
  16268. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16269. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16270. if ( this.cacheArcLengths
  16271. && ( this.cacheArcLengths.length == divisions + 1 )
  16272. && !this.needsUpdate) {
  16273. //console.log( "cached", this.cacheArcLengths );
  16274. return this.cacheArcLengths;
  16275. }
  16276. this.needsUpdate = false;
  16277. var cache = [];
  16278. var current, last = this.getPoint( 0 );
  16279. var p, sum = 0;
  16280. cache.push( 0 );
  16281. for ( p = 1; p <= divisions; p ++ ) {
  16282. current = this.getPoint ( p / divisions );
  16283. sum += current.distanceTo( last );
  16284. cache.push( sum );
  16285. last = current;
  16286. }
  16287. this.cacheArcLengths = cache;
  16288. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16289. };
  16290. THREE.Curve.prototype.updateArcLengths = function() {
  16291. this.needsUpdate = true;
  16292. this.getLengths();
  16293. };
  16294. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16295. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16296. var arcLengths = this.getLengths();
  16297. var i = 0, il = arcLengths.length;
  16298. var targetArcLength; // The targeted u distance value to get
  16299. if ( distance ) {
  16300. targetArcLength = distance;
  16301. } else {
  16302. targetArcLength = u * arcLengths[ il - 1 ];
  16303. }
  16304. //var time = Date.now();
  16305. // binary search for the index with largest value smaller than target u distance
  16306. var low = 0, high = il - 1, comparison;
  16307. while ( low <= high ) {
  16308. 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
  16309. comparison = arcLengths[ i ] - targetArcLength;
  16310. if ( comparison < 0 ) {
  16311. low = i + 1;
  16312. continue;
  16313. } else if ( comparison > 0 ) {
  16314. high = i - 1;
  16315. continue;
  16316. } else {
  16317. high = i;
  16318. break;
  16319. // DONE
  16320. }
  16321. }
  16322. i = high;
  16323. //console.log('b' , i, low, high, Date.now()- time);
  16324. if ( arcLengths[ i ] == targetArcLength ) {
  16325. var t = i / ( il - 1 );
  16326. return t;
  16327. }
  16328. // we could get finer grain at lengths, or use simple interpolatation between two points
  16329. var lengthBefore = arcLengths[ i ];
  16330. var lengthAfter = arcLengths[ i + 1 ];
  16331. var segmentLength = lengthAfter - lengthBefore;
  16332. // determine where we are between the 'before' and 'after' points
  16333. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16334. // add that fractional amount to t
  16335. var t = ( i + segmentFraction ) / ( il -1 );
  16336. return t;
  16337. };
  16338. // Returns a unit vector tangent at t
  16339. // In case any sub curve does not implement its tangent derivation,
  16340. // 2 points a small delta apart will be used to find its gradient
  16341. // which seems to give a reasonable approximation
  16342. THREE.Curve.prototype.getTangent = function( t ) {
  16343. var delta = 0.0001;
  16344. var t1 = t - delta;
  16345. var t2 = t + delta;
  16346. // Capping in case of danger
  16347. if ( t1 < 0 ) t1 = 0;
  16348. if ( t2 > 1 ) t2 = 1;
  16349. var pt1 = this.getPoint( t1 );
  16350. var pt2 = this.getPoint( t2 );
  16351. var vec = pt2.clone().sub(pt1);
  16352. return vec.normalize();
  16353. };
  16354. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16355. var t = this.getUtoTmapping( u );
  16356. return this.getTangent( t );
  16357. };
  16358. /**************************************************************
  16359. * Line
  16360. **************************************************************/
  16361. THREE.LineCurve = function ( v1, v2 ) {
  16362. this.v1 = v1;
  16363. this.v2 = v2;
  16364. };
  16365. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16366. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16367. var point = this.v2.clone().sub(this.v1);
  16368. point.multiplyScalar( t ).add( this.v1 );
  16369. return point;
  16370. };
  16371. // Line curve is linear, so we can overwrite default getPointAt
  16372. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16373. return this.getPoint( u );
  16374. };
  16375. THREE.LineCurve.prototype.getTangent = function( t ) {
  16376. var tangent = this.v2.clone().sub(this.v1);
  16377. return tangent.normalize();
  16378. };
  16379. /**************************************************************
  16380. * Quadratic Bezier curve
  16381. **************************************************************/
  16382. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16383. this.v0 = v0;
  16384. this.v1 = v1;
  16385. this.v2 = v2;
  16386. };
  16387. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16388. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16389. var tx, ty;
  16390. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16391. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16392. return new THREE.Vector2( tx, ty );
  16393. };
  16394. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16395. var tx, ty;
  16396. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16397. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16398. // returns unit vector
  16399. var tangent = new THREE.Vector2( tx, ty );
  16400. tangent.normalize();
  16401. return tangent;
  16402. };
  16403. /**************************************************************
  16404. * Cubic Bezier curve
  16405. **************************************************************/
  16406. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16407. this.v0 = v0;
  16408. this.v1 = v1;
  16409. this.v2 = v2;
  16410. this.v3 = v3;
  16411. };
  16412. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16413. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16414. var tx, ty;
  16415. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16416. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16417. return new THREE.Vector2( tx, ty );
  16418. };
  16419. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16420. var tx, ty;
  16421. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16422. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16423. var tangent = new THREE.Vector2( tx, ty );
  16424. tangent.normalize();
  16425. return tangent;
  16426. };
  16427. /**************************************************************
  16428. * Spline curve
  16429. **************************************************************/
  16430. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16431. this.points = (points == undefined) ? [] : points;
  16432. };
  16433. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16434. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16435. var v = new THREE.Vector2();
  16436. var c = [];
  16437. var points = this.points, point, intPoint, weight;
  16438. point = ( points.length - 1 ) * t;
  16439. intPoint = Math.floor( point );
  16440. weight = point - intPoint;
  16441. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16442. c[ 1 ] = intPoint;
  16443. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16444. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16445. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16446. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16447. return v;
  16448. };
  16449. /**************************************************************
  16450. * Ellipse curve
  16451. **************************************************************/
  16452. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16453. aStartAngle, aEndAngle,
  16454. aClockwise ) {
  16455. this.aX = aX;
  16456. this.aY = aY;
  16457. this.xRadius = xRadius;
  16458. this.yRadius = yRadius;
  16459. this.aStartAngle = aStartAngle;
  16460. this.aEndAngle = aEndAngle;
  16461. this.aClockwise = aClockwise;
  16462. };
  16463. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16464. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16465. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16466. if ( !this.aClockwise ) {
  16467. t = 1 - t;
  16468. }
  16469. var angle = this.aStartAngle + t * deltaAngle;
  16470. var tx = this.aX + this.xRadius * Math.cos( angle );
  16471. var ty = this.aY + this.yRadius * Math.sin( angle );
  16472. return new THREE.Vector2( tx, ty );
  16473. };
  16474. /**************************************************************
  16475. * Arc curve
  16476. **************************************************************/
  16477. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16478. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16479. };
  16480. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16481. /**************************************************************
  16482. * Utils
  16483. **************************************************************/
  16484. THREE.Curve.Utils = {
  16485. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16486. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16487. },
  16488. // Puay Bing, thanks for helping with this derivative!
  16489. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16490. return -3 * p0 * (1 - t) * (1 - t) +
  16491. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16492. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16493. 3 * t * t * p3;
  16494. },
  16495. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16496. // To check if my formulas are correct
  16497. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16498. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16499. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16500. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16501. return h00 + h10 + h01 + h11;
  16502. },
  16503. // Catmull-Rom
  16504. interpolate: function( p0, p1, p2, p3, t ) {
  16505. var v0 = ( p2 - p0 ) * 0.5;
  16506. var v1 = ( p3 - p1 ) * 0.5;
  16507. var t2 = t * t;
  16508. var t3 = t * t2;
  16509. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16510. }
  16511. };
  16512. // TODO: Transformation for Curves?
  16513. /**************************************************************
  16514. * 3D Curves
  16515. **************************************************************/
  16516. // A Factory method for creating new curve subclasses
  16517. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16518. constructor.prototype = Object.create( THREE.Curve.prototype );
  16519. constructor.prototype.getPoint = getPointFunc;
  16520. return constructor;
  16521. };
  16522. /**************************************************************
  16523. * Line3D
  16524. **************************************************************/
  16525. THREE.LineCurve3 = THREE.Curve.create(
  16526. function ( v1, v2 ) {
  16527. this.v1 = v1;
  16528. this.v2 = v2;
  16529. },
  16530. function ( t ) {
  16531. var r = new THREE.Vector3();
  16532. r.subVectors( this.v2, this.v1 ); // diff
  16533. r.multiplyScalar( t );
  16534. r.add( this.v1 );
  16535. return r;
  16536. }
  16537. );
  16538. /**************************************************************
  16539. * Quadratic Bezier 3D curve
  16540. **************************************************************/
  16541. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16542. function ( v0, v1, v2 ) {
  16543. this.v0 = v0;
  16544. this.v1 = v1;
  16545. this.v2 = v2;
  16546. },
  16547. function ( t ) {
  16548. var tx, ty, tz;
  16549. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16550. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16551. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16552. return new THREE.Vector3( tx, ty, tz );
  16553. }
  16554. );
  16555. /**************************************************************
  16556. * Cubic Bezier 3D curve
  16557. **************************************************************/
  16558. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16559. function ( v0, v1, v2, v3 ) {
  16560. this.v0 = v0;
  16561. this.v1 = v1;
  16562. this.v2 = v2;
  16563. this.v3 = v3;
  16564. },
  16565. function ( t ) {
  16566. var tx, ty, tz;
  16567. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16568. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16569. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16570. return new THREE.Vector3( tx, ty, tz );
  16571. }
  16572. );
  16573. /**************************************************************
  16574. * Spline 3D curve
  16575. **************************************************************/
  16576. THREE.SplineCurve3 = THREE.Curve.create(
  16577. function ( points /* array of Vector3 */) {
  16578. this.points = (points == undefined) ? [] : points;
  16579. },
  16580. function ( t ) {
  16581. var v = new THREE.Vector3();
  16582. var c = [];
  16583. var points = this.points, point, intPoint, weight;
  16584. point = ( points.length - 1 ) * t;
  16585. intPoint = Math.floor( point );
  16586. weight = point - intPoint;
  16587. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16588. c[ 1 ] = intPoint;
  16589. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16590. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16591. var pt0 = points[ c[0] ],
  16592. pt1 = points[ c[1] ],
  16593. pt2 = points[ c[2] ],
  16594. pt3 = points[ c[3] ];
  16595. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16596. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16597. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16598. return v;
  16599. }
  16600. );
  16601. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16602. // var v = new THREE.Vector3();
  16603. // var c = [];
  16604. // var points = this.points, point, intPoint, weight;
  16605. // point = ( points.length - 1 ) * t;
  16606. // intPoint = Math.floor( point );
  16607. // weight = point - intPoint;
  16608. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16609. // c[ 1 ] = intPoint;
  16610. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16611. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16612. // var pt0 = points[ c[0] ],
  16613. // pt1 = points[ c[1] ],
  16614. // pt2 = points[ c[2] ],
  16615. // pt3 = points[ c[3] ];
  16616. // // t = weight;
  16617. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16618. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16619. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16620. // return v;
  16621. // }
  16622. /**************************************************************
  16623. * Closed Spline 3D curve
  16624. **************************************************************/
  16625. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16626. function ( points /* array of Vector3 */) {
  16627. this.points = (points == undefined) ? [] : points;
  16628. },
  16629. function ( t ) {
  16630. var v = new THREE.Vector3();
  16631. var c = [];
  16632. var points = this.points, point, intPoint, weight;
  16633. point = ( points.length - 0 ) * t;
  16634. // This needs to be from 0-length +1
  16635. intPoint = Math.floor( point );
  16636. weight = point - intPoint;
  16637. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16638. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16639. c[ 1 ] = ( intPoint ) % points.length;
  16640. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16641. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16642. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16643. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16644. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16645. return v;
  16646. }
  16647. );
  16648. /**
  16649. * @author zz85 / http://www.lab4games.net/zz85/blog
  16650. *
  16651. **/
  16652. /**************************************************************
  16653. * Curved Path - a curve path is simply a array of connected
  16654. * curves, but retains the api of a curve
  16655. **************************************************************/
  16656. THREE.CurvePath = function () {
  16657. this.curves = [];
  16658. this.bends = [];
  16659. this.autoClose = false; // Automatically closes the path
  16660. };
  16661. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16662. THREE.CurvePath.prototype.add = function ( curve ) {
  16663. this.curves.push( curve );
  16664. };
  16665. THREE.CurvePath.prototype.checkConnection = function() {
  16666. // TODO
  16667. // If the ending of curve is not connected to the starting
  16668. // or the next curve, then, this is not a real path
  16669. };
  16670. THREE.CurvePath.prototype.closePath = function() {
  16671. // TODO Test
  16672. // and verify for vector3 (needs to implement equals)
  16673. // Add a line curve if start and end of lines are not connected
  16674. var startPoint = this.curves[0].getPoint(0);
  16675. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16676. if (!startPoint.equals(endPoint)) {
  16677. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16678. }
  16679. };
  16680. // To get accurate point with reference to
  16681. // entire path distance at time t,
  16682. // following has to be done:
  16683. // 1. Length of each sub path have to be known
  16684. // 2. Locate and identify type of curve
  16685. // 3. Get t for the curve
  16686. // 4. Return curve.getPointAt(t')
  16687. THREE.CurvePath.prototype.getPoint = function( t ) {
  16688. var d = t * this.getLength();
  16689. var curveLengths = this.getCurveLengths();
  16690. var i = 0, diff, curve;
  16691. // To think about boundaries points.
  16692. while ( i < curveLengths.length ) {
  16693. if ( curveLengths[ i ] >= d ) {
  16694. diff = curveLengths[ i ] - d;
  16695. curve = this.curves[ i ];
  16696. var u = 1 - diff / curve.getLength();
  16697. return curve.getPointAt( u );
  16698. break;
  16699. }
  16700. i ++;
  16701. }
  16702. return null;
  16703. // loop where sum != 0, sum > d , sum+1 <d
  16704. };
  16705. /*
  16706. THREE.CurvePath.prototype.getTangent = function( t ) {
  16707. };*/
  16708. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16709. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16710. // getPoint() depends on getLength
  16711. THREE.CurvePath.prototype.getLength = function() {
  16712. var lens = this.getCurveLengths();
  16713. return lens[ lens.length - 1 ];
  16714. };
  16715. // Compute lengths and cache them
  16716. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16717. THREE.CurvePath.prototype.getCurveLengths = function() {
  16718. // We use cache values if curves and cache array are same length
  16719. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16720. return this.cacheLengths;
  16721. };
  16722. // Get length of subsurve
  16723. // Push sums into cached array
  16724. var lengths = [], sums = 0;
  16725. var i, il = this.curves.length;
  16726. for ( i = 0; i < il; i ++ ) {
  16727. sums += this.curves[ i ].getLength();
  16728. lengths.push( sums );
  16729. }
  16730. this.cacheLengths = lengths;
  16731. return lengths;
  16732. };
  16733. // Returns min and max coordinates, as well as centroid
  16734. THREE.CurvePath.prototype.getBoundingBox = function () {
  16735. var points = this.getPoints();
  16736. var maxX, maxY, maxZ;
  16737. var minX, minY, minZ;
  16738. maxX = maxY = Number.NEGATIVE_INFINITY;
  16739. minX = minY = Number.POSITIVE_INFINITY;
  16740. var p, i, il, sum;
  16741. var v3 = points[0] instanceof THREE.Vector3;
  16742. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16743. for ( i = 0, il = points.length; i < il; i ++ ) {
  16744. p = points[ i ];
  16745. if ( p.x > maxX ) maxX = p.x;
  16746. else if ( p.x < minX ) minX = p.x;
  16747. if ( p.y > maxY ) maxY = p.y;
  16748. else if ( p.y < minY ) minY = p.y;
  16749. if ( v3 ) {
  16750. if ( p.z > maxZ ) maxZ = p.z;
  16751. else if ( p.z < minZ ) minZ = p.z;
  16752. }
  16753. sum.add( p );
  16754. }
  16755. var ret = {
  16756. minX: minX,
  16757. minY: minY,
  16758. maxX: maxX,
  16759. maxY: maxY,
  16760. centroid: sum.divideScalar( il )
  16761. };
  16762. if ( v3 ) {
  16763. ret.maxZ = maxZ;
  16764. ret.minZ = minZ;
  16765. }
  16766. return ret;
  16767. };
  16768. /**************************************************************
  16769. * Create Geometries Helpers
  16770. **************************************************************/
  16771. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16772. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16773. var pts = this.getPoints( divisions, true );
  16774. return this.createGeometry( pts );
  16775. };
  16776. // Generate geometry from equidistance sampling along the path
  16777. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16778. var pts = this.getSpacedPoints( divisions, true );
  16779. return this.createGeometry( pts );
  16780. };
  16781. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16782. var geometry = new THREE.Geometry();
  16783. for ( var i = 0; i < points.length; i ++ ) {
  16784. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16785. }
  16786. return geometry;
  16787. };
  16788. /**************************************************************
  16789. * Bend / Wrap Helper Methods
  16790. **************************************************************/
  16791. // Wrap path / Bend modifiers?
  16792. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16793. this.bends.push( bendpath );
  16794. };
  16795. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16796. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16797. var i, il;
  16798. if ( !bends ) {
  16799. bends = this.bends;
  16800. }
  16801. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16802. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16803. }
  16804. return oldPts;
  16805. };
  16806. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16807. var oldPts = this.getSpacedPoints( segments );
  16808. var i, il;
  16809. if ( !bends ) {
  16810. bends = this.bends;
  16811. }
  16812. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16813. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16814. }
  16815. return oldPts;
  16816. };
  16817. // This returns getPoints() bend/wrapped around the contour of a path.
  16818. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16819. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16820. var bounds = this.getBoundingBox();
  16821. var i, il, p, oldX, oldY, xNorm;
  16822. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16823. p = oldPts[ i ];
  16824. oldX = p.x;
  16825. oldY = p.y;
  16826. xNorm = oldX / bounds.maxX;
  16827. // If using actual distance, for length > path, requires line extrusions
  16828. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16829. xNorm = path.getUtoTmapping( xNorm, oldX );
  16830. // check for out of bounds?
  16831. var pathPt = path.getPoint( xNorm );
  16832. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16833. p.x = pathPt.x + normal.x;
  16834. p.y = pathPt.y + normal.y;
  16835. }
  16836. return oldPts;
  16837. };
  16838. /**
  16839. * @author alteredq / http://alteredqualia.com/
  16840. */
  16841. THREE.Gyroscope = function () {
  16842. THREE.Object3D.call( this );
  16843. };
  16844. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16845. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16846. this.matrixAutoUpdate && this.updateMatrix();
  16847. // update matrixWorld
  16848. if ( this.matrixWorldNeedsUpdate || force ) {
  16849. if ( this.parent ) {
  16850. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16851. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16852. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16853. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16854. } else {
  16855. this.matrixWorld.copy( this.matrix );
  16856. }
  16857. this.matrixWorldNeedsUpdate = false;
  16858. force = true;
  16859. }
  16860. // update children
  16861. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16862. this.children[ i ].updateMatrixWorld( force );
  16863. }
  16864. };
  16865. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16866. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16867. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16868. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16869. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16870. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16871. /**
  16872. * @author zz85 / http://www.lab4games.net/zz85/blog
  16873. * Creates free form 2d path using series of points, lines or curves.
  16874. *
  16875. **/
  16876. THREE.Path = function ( points ) {
  16877. THREE.CurvePath.call(this);
  16878. this.actions = [];
  16879. if ( points ) {
  16880. this.fromPoints( points );
  16881. }
  16882. };
  16883. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16884. THREE.PathActions = {
  16885. MOVE_TO: 'moveTo',
  16886. LINE_TO: 'lineTo',
  16887. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16888. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16889. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16890. ARC: 'arc', // Circle
  16891. ELLIPSE: 'ellipse'
  16892. };
  16893. // TODO Clean up PATH API
  16894. // Create path using straight lines to connect all points
  16895. // - vectors: array of Vector2
  16896. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16897. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16898. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16899. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16900. };
  16901. };
  16902. // startPath() endPath()?
  16903. THREE.Path.prototype.moveTo = function ( x, y ) {
  16904. var args = Array.prototype.slice.call( arguments );
  16905. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16906. };
  16907. THREE.Path.prototype.lineTo = function ( x, y ) {
  16908. var args = Array.prototype.slice.call( arguments );
  16909. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16910. var x0 = lastargs[ lastargs.length - 2 ];
  16911. var y0 = lastargs[ lastargs.length - 1 ];
  16912. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16913. this.curves.push( curve );
  16914. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16915. };
  16916. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16917. var args = Array.prototype.slice.call( arguments );
  16918. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16919. var x0 = lastargs[ lastargs.length - 2 ];
  16920. var y0 = lastargs[ lastargs.length - 1 ];
  16921. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16922. new THREE.Vector2( aCPx, aCPy ),
  16923. new THREE.Vector2( aX, aY ) );
  16924. this.curves.push( curve );
  16925. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16926. };
  16927. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16928. aCP2x, aCP2y,
  16929. aX, aY ) {
  16930. var args = Array.prototype.slice.call( arguments );
  16931. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16932. var x0 = lastargs[ lastargs.length - 2 ];
  16933. var y0 = lastargs[ lastargs.length - 1 ];
  16934. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16935. new THREE.Vector2( aCP1x, aCP1y ),
  16936. new THREE.Vector2( aCP2x, aCP2y ),
  16937. new THREE.Vector2( aX, aY ) );
  16938. this.curves.push( curve );
  16939. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16940. };
  16941. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16942. var args = Array.prototype.slice.call( arguments );
  16943. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16944. var x0 = lastargs[ lastargs.length - 2 ];
  16945. var y0 = lastargs[ lastargs.length - 1 ];
  16946. //---
  16947. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16948. Array.prototype.push.apply( npts, pts );
  16949. var curve = new THREE.SplineCurve( npts );
  16950. this.curves.push( curve );
  16951. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16952. };
  16953. // FUTURE: Change the API or follow canvas API?
  16954. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16955. aStartAngle, aEndAngle, aClockwise ) {
  16956. var lastargs = this.actions[ this.actions.length - 1].args;
  16957. var x0 = lastargs[ lastargs.length - 2 ];
  16958. var y0 = lastargs[ lastargs.length - 1 ];
  16959. this.absarc(aX + x0, aY + y0, aRadius,
  16960. aStartAngle, aEndAngle, aClockwise );
  16961. };
  16962. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16963. aStartAngle, aEndAngle, aClockwise ) {
  16964. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16965. };
  16966. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16967. aStartAngle, aEndAngle, aClockwise ) {
  16968. var lastargs = this.actions[ this.actions.length - 1].args;
  16969. var x0 = lastargs[ lastargs.length - 2 ];
  16970. var y0 = lastargs[ lastargs.length - 1 ];
  16971. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16972. aStartAngle, aEndAngle, aClockwise );
  16973. };
  16974. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16975. aStartAngle, aEndAngle, aClockwise ) {
  16976. var args = Array.prototype.slice.call( arguments );
  16977. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16978. aStartAngle, aEndAngle, aClockwise );
  16979. this.curves.push( curve );
  16980. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16981. args.push(lastPoint.x);
  16982. args.push(lastPoint.y);
  16983. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16984. };
  16985. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16986. if ( ! divisions ) divisions = 40;
  16987. var points = [];
  16988. for ( var i = 0; i < divisions; i ++ ) {
  16989. points.push( this.getPoint( i / divisions ) );
  16990. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16991. }
  16992. // if ( closedPath ) {
  16993. //
  16994. // points.push( points[ 0 ] );
  16995. //
  16996. // }
  16997. return points;
  16998. };
  16999. /* Return an array of vectors based on contour of the path */
  17000. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17001. if (this.useSpacedPoints) {
  17002. console.log('tata');
  17003. return this.getSpacedPoints( divisions, closedPath );
  17004. }
  17005. divisions = divisions || 12;
  17006. var points = [];
  17007. var i, il, item, action, args;
  17008. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17009. laste, j,
  17010. t, tx, ty;
  17011. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17012. item = this.actions[ i ];
  17013. action = item.action;
  17014. args = item.args;
  17015. switch( action ) {
  17016. case THREE.PathActions.MOVE_TO:
  17017. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17018. break;
  17019. case THREE.PathActions.LINE_TO:
  17020. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17021. break;
  17022. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17023. cpx = args[ 2 ];
  17024. cpy = args[ 3 ];
  17025. cpx1 = args[ 0 ];
  17026. cpy1 = args[ 1 ];
  17027. if ( points.length > 0 ) {
  17028. laste = points[ points.length - 1 ];
  17029. cpx0 = laste.x;
  17030. cpy0 = laste.y;
  17031. } else {
  17032. laste = this.actions[ i - 1 ].args;
  17033. cpx0 = laste[ laste.length - 2 ];
  17034. cpy0 = laste[ laste.length - 1 ];
  17035. }
  17036. for ( j = 1; j <= divisions; j ++ ) {
  17037. t = j / divisions;
  17038. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17039. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17040. points.push( new THREE.Vector2( tx, ty ) );
  17041. }
  17042. break;
  17043. case THREE.PathActions.BEZIER_CURVE_TO:
  17044. cpx = args[ 4 ];
  17045. cpy = args[ 5 ];
  17046. cpx1 = args[ 0 ];
  17047. cpy1 = args[ 1 ];
  17048. cpx2 = args[ 2 ];
  17049. cpy2 = args[ 3 ];
  17050. if ( points.length > 0 ) {
  17051. laste = points[ points.length - 1 ];
  17052. cpx0 = laste.x;
  17053. cpy0 = laste.y;
  17054. } else {
  17055. laste = this.actions[ i - 1 ].args;
  17056. cpx0 = laste[ laste.length - 2 ];
  17057. cpy0 = laste[ laste.length - 1 ];
  17058. }
  17059. for ( j = 1; j <= divisions; j ++ ) {
  17060. t = j / divisions;
  17061. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17062. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17063. points.push( new THREE.Vector2( tx, ty ) );
  17064. }
  17065. break;
  17066. case THREE.PathActions.CSPLINE_THRU:
  17067. laste = this.actions[ i - 1 ].args;
  17068. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17069. var spts = [ last ];
  17070. var n = divisions * args[ 0 ].length;
  17071. spts = spts.concat( args[ 0 ] );
  17072. var spline = new THREE.SplineCurve( spts );
  17073. for ( j = 1; j <= n; j ++ ) {
  17074. points.push( spline.getPointAt( j / n ) ) ;
  17075. }
  17076. break;
  17077. case THREE.PathActions.ARC:
  17078. var aX = args[ 0 ], aY = args[ 1 ],
  17079. aRadius = args[ 2 ],
  17080. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17081. aClockwise = !!args[ 5 ];
  17082. var deltaAngle = aEndAngle - aStartAngle;
  17083. var angle;
  17084. var tdivisions = divisions * 2;
  17085. for ( j = 1; j <= tdivisions; j ++ ) {
  17086. t = j / tdivisions;
  17087. if ( ! aClockwise ) {
  17088. t = 1 - t;
  17089. }
  17090. angle = aStartAngle + t * deltaAngle;
  17091. tx = aX + aRadius * Math.cos( angle );
  17092. ty = aY + aRadius * Math.sin( angle );
  17093. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17094. points.push( new THREE.Vector2( tx, ty ) );
  17095. }
  17096. //console.log(points);
  17097. break;
  17098. case THREE.PathActions.ELLIPSE:
  17099. var aX = args[ 0 ], aY = args[ 1 ],
  17100. xRadius = args[ 2 ],
  17101. yRadius = args[ 3 ],
  17102. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17103. aClockwise = !!args[ 6 ];
  17104. var deltaAngle = aEndAngle - aStartAngle;
  17105. var angle;
  17106. var tdivisions = divisions * 2;
  17107. for ( j = 1; j <= tdivisions; j ++ ) {
  17108. t = j / tdivisions;
  17109. if ( ! aClockwise ) {
  17110. t = 1 - t;
  17111. }
  17112. angle = aStartAngle + t * deltaAngle;
  17113. tx = aX + xRadius * Math.cos( angle );
  17114. ty = aY + yRadius * Math.sin( angle );
  17115. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17116. points.push( new THREE.Vector2( tx, ty ) );
  17117. }
  17118. //console.log(points);
  17119. break;
  17120. } // end switch
  17121. }
  17122. // Normalize to remove the closing point by default.
  17123. var lastPoint = points[ points.length - 1];
  17124. var EPSILON = 0.0000000001;
  17125. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17126. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17127. points.splice( points.length - 1, 1);
  17128. if ( closedPath ) {
  17129. points.push( points[ 0 ] );
  17130. }
  17131. return points;
  17132. };
  17133. // Breaks path into shapes
  17134. THREE.Path.prototype.toShapes = function() {
  17135. var i, il, item, action, args;
  17136. var subPaths = [], lastPath = new THREE.Path();
  17137. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17138. item = this.actions[ i ];
  17139. args = item.args;
  17140. action = item.action;
  17141. if ( action == THREE.PathActions.MOVE_TO ) {
  17142. if ( lastPath.actions.length != 0 ) {
  17143. subPaths.push( lastPath );
  17144. lastPath = new THREE.Path();
  17145. }
  17146. }
  17147. lastPath[ action ].apply( lastPath, args );
  17148. }
  17149. if ( lastPath.actions.length != 0 ) {
  17150. subPaths.push( lastPath );
  17151. }
  17152. // console.log(subPaths);
  17153. if ( subPaths.length == 0 ) return [];
  17154. var tmpPath, tmpShape, shapes = [];
  17155. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17156. // console.log("Holes first", holesFirst);
  17157. if ( subPaths.length == 1) {
  17158. tmpPath = subPaths[0];
  17159. tmpShape = new THREE.Shape();
  17160. tmpShape.actions = tmpPath.actions;
  17161. tmpShape.curves = tmpPath.curves;
  17162. shapes.push( tmpShape );
  17163. return shapes;
  17164. };
  17165. if ( holesFirst ) {
  17166. tmpShape = new THREE.Shape();
  17167. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17168. tmpPath = subPaths[ i ];
  17169. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17170. tmpShape.actions = tmpPath.actions;
  17171. tmpShape.curves = tmpPath.curves;
  17172. shapes.push( tmpShape );
  17173. tmpShape = new THREE.Shape();
  17174. //console.log('cw', i);
  17175. } else {
  17176. tmpShape.holes.push( tmpPath );
  17177. //console.log('ccw', i);
  17178. }
  17179. }
  17180. } else {
  17181. // Shapes first
  17182. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17183. tmpPath = subPaths[ i ];
  17184. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17185. if ( tmpShape ) shapes.push( tmpShape );
  17186. tmpShape = new THREE.Shape();
  17187. tmpShape.actions = tmpPath.actions;
  17188. tmpShape.curves = tmpPath.curves;
  17189. } else {
  17190. tmpShape.holes.push( tmpPath );
  17191. }
  17192. }
  17193. shapes.push( tmpShape );
  17194. }
  17195. //console.log("shape", shapes);
  17196. return shapes;
  17197. };
  17198. /**
  17199. * @author zz85 / http://www.lab4games.net/zz85/blog
  17200. * Defines a 2d shape plane using paths.
  17201. **/
  17202. // STEP 1 Create a path.
  17203. // STEP 2 Turn path into shape.
  17204. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17205. // STEP 3a - Extract points from each shape, turn to vertices
  17206. // STEP 3b - Triangulate each shape, add faces.
  17207. THREE.Shape = function () {
  17208. THREE.Path.apply( this, arguments );
  17209. this.holes = [];
  17210. };
  17211. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17212. // Convenience method to return ExtrudeGeometry
  17213. THREE.Shape.prototype.extrude = function ( options ) {
  17214. var extruded = new THREE.ExtrudeGeometry( this, options );
  17215. return extruded;
  17216. };
  17217. // Convenience method to return ShapeGeometry
  17218. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17219. var geometry = new THREE.ShapeGeometry( this, options );
  17220. return geometry;
  17221. };
  17222. // Get points of holes
  17223. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17224. var i, il = this.holes.length, holesPts = [];
  17225. for ( i = 0; i < il; i ++ ) {
  17226. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17227. }
  17228. return holesPts;
  17229. };
  17230. // Get points of holes (spaced by regular distance)
  17231. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17232. var i, il = this.holes.length, holesPts = [];
  17233. for ( i = 0; i < il; i ++ ) {
  17234. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17235. }
  17236. return holesPts;
  17237. };
  17238. // Get points of shape and holes (keypoints based on segments parameter)
  17239. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17240. return {
  17241. shape: this.getTransformedPoints( divisions ),
  17242. holes: this.getPointsHoles( divisions )
  17243. };
  17244. };
  17245. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17246. if (this.useSpacedPoints) {
  17247. return this.extractAllSpacedPoints(divisions);
  17248. }
  17249. return this.extractAllPoints(divisions);
  17250. };
  17251. //
  17252. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17253. //
  17254. // return {
  17255. //
  17256. // shape: this.transform( bend, divisions ),
  17257. // holes: this.getPointsHoles( divisions, bend )
  17258. //
  17259. // };
  17260. //
  17261. // };
  17262. // Get points of shape and holes (spaced by regular distance)
  17263. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17264. return {
  17265. shape: this.getTransformedSpacedPoints( divisions ),
  17266. holes: this.getSpacedPointsHoles( divisions )
  17267. };
  17268. };
  17269. /**************************************************************
  17270. * Utils
  17271. **************************************************************/
  17272. THREE.Shape.Utils = {
  17273. /*
  17274. contour - array of vector2 for contour
  17275. holes - array of array of vector2
  17276. */
  17277. removeHoles: function ( contour, holes ) {
  17278. var shape = contour.concat(); // work on this shape
  17279. var allpoints = shape.concat();
  17280. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17281. var prevShapeVert, nextShapeVert,
  17282. prevHoleVert, nextHoleVert,
  17283. holeIndex, shapeIndex,
  17284. shapeId, shapeGroup,
  17285. h, h2,
  17286. hole, shortest, d,
  17287. p, pts1, pts2,
  17288. tmpShape1, tmpShape2,
  17289. tmpHole1, tmpHole2,
  17290. verts = [];
  17291. for ( h = 0; h < holes.length; h ++ ) {
  17292. hole = holes[ h ];
  17293. /*
  17294. shapeholes[ h ].concat(); // preserves original
  17295. holes.push( hole );
  17296. */
  17297. Array.prototype.push.apply( allpoints, hole );
  17298. shortest = Number.POSITIVE_INFINITY;
  17299. // Find the shortest pair of pts between shape and hole
  17300. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17301. // Using distanceToSquared() intead of distanceTo() should speed a little
  17302. // since running square roots operations are reduced.
  17303. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17304. pts1 = hole[ h2 ];
  17305. var dist = [];
  17306. for ( p = 0; p < shape.length; p++ ) {
  17307. pts2 = shape[ p ];
  17308. d = pts1.distanceToSquared( pts2 );
  17309. dist.push( d );
  17310. if ( d < shortest ) {
  17311. shortest = d;
  17312. holeIndex = h2;
  17313. shapeIndex = p;
  17314. }
  17315. }
  17316. }
  17317. //console.log("shortest", shortest, dist);
  17318. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17319. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17320. var areaapts = [
  17321. hole[ holeIndex ],
  17322. shape[ shapeIndex ],
  17323. shape[ prevShapeVert ]
  17324. ];
  17325. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17326. var areabpts = [
  17327. hole[ holeIndex ],
  17328. hole[ prevHoleVert ],
  17329. shape[ shapeIndex ]
  17330. ];
  17331. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17332. var shapeOffset = 1;
  17333. var holeOffset = -1;
  17334. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17335. shapeIndex += shapeOffset;
  17336. holeIndex += holeOffset;
  17337. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17338. shapeIndex %= shape.length;
  17339. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17340. holeIndex %= hole.length;
  17341. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17342. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17343. areaapts = [
  17344. hole[ holeIndex ],
  17345. shape[ shapeIndex ],
  17346. shape[ prevShapeVert ]
  17347. ];
  17348. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17349. areabpts = [
  17350. hole[ holeIndex ],
  17351. hole[ prevHoleVert ],
  17352. shape[ shapeIndex ]
  17353. ];
  17354. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17355. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17356. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17357. // In case areas are not correct.
  17358. //console.log("USE THIS");
  17359. shapeIndex = oldShapeIndex;
  17360. holeIndex = oldHoleIndex ;
  17361. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17362. shapeIndex %= shape.length;
  17363. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17364. holeIndex %= hole.length;
  17365. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17366. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17367. } else {
  17368. //console.log("USE THAT ")
  17369. }
  17370. tmpShape1 = shape.slice( 0, shapeIndex );
  17371. tmpShape2 = shape.slice( shapeIndex );
  17372. tmpHole1 = hole.slice( holeIndex );
  17373. tmpHole2 = hole.slice( 0, holeIndex );
  17374. // Should check orders here again?
  17375. var trianglea = [
  17376. hole[ holeIndex ],
  17377. shape[ shapeIndex ],
  17378. shape[ prevShapeVert ]
  17379. ];
  17380. var triangleb = [
  17381. hole[ holeIndex ] ,
  17382. hole[ prevHoleVert ],
  17383. shape[ shapeIndex ]
  17384. ];
  17385. verts.push( trianglea );
  17386. verts.push( triangleb );
  17387. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17388. }
  17389. return {
  17390. shape:shape, /* shape with no holes */
  17391. isolatedPts: verts, /* isolated faces */
  17392. allpoints: allpoints
  17393. }
  17394. },
  17395. triangulateShape: function ( contour, holes ) {
  17396. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17397. var shape = shapeWithoutHoles.shape,
  17398. allpoints = shapeWithoutHoles.allpoints,
  17399. isolatedPts = shapeWithoutHoles.isolatedPts;
  17400. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17401. // 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.
  17402. //console.log( "triangles",triangles, triangles.length );
  17403. //console.log( "allpoints",allpoints, allpoints.length );
  17404. var i, il, f, face,
  17405. key, index,
  17406. allPointsMap = {},
  17407. isolatedPointsMap = {};
  17408. // prepare all points map
  17409. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17410. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17411. if ( allPointsMap[ key ] !== undefined ) {
  17412. console.log( "Duplicate point", key );
  17413. }
  17414. allPointsMap[ key ] = i;
  17415. }
  17416. // check all face vertices against all points map
  17417. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17418. face = triangles[ i ];
  17419. for ( f = 0; f < 3; f ++ ) {
  17420. key = face[ f ].x + ":" + face[ f ].y;
  17421. index = allPointsMap[ key ];
  17422. if ( index !== undefined ) {
  17423. face[ f ] = index;
  17424. }
  17425. }
  17426. }
  17427. // check isolated points vertices against all points map
  17428. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17429. face = isolatedPts[ i ];
  17430. for ( f = 0; f < 3; f ++ ) {
  17431. key = face[ f ].x + ":" + face[ f ].y;
  17432. index = allPointsMap[ key ];
  17433. if ( index !== undefined ) {
  17434. face[ f ] = index;
  17435. }
  17436. }
  17437. }
  17438. return triangles.concat( isolatedPts );
  17439. }, // end triangulate shapes
  17440. /*
  17441. triangulate2 : function( pts, holes ) {
  17442. // For use with Poly2Tri.js
  17443. var allpts = pts.concat();
  17444. var shape = [];
  17445. for (var p in pts) {
  17446. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17447. }
  17448. var swctx = new js.poly2tri.SweepContext(shape);
  17449. for (var h in holes) {
  17450. var aHole = holes[h];
  17451. var newHole = []
  17452. for (i in aHole) {
  17453. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17454. allpts.push(aHole[i]);
  17455. }
  17456. swctx.AddHole(newHole);
  17457. }
  17458. var find;
  17459. var findIndexForPt = function (pt) {
  17460. find = new THREE.Vector2(pt.x, pt.y);
  17461. var p;
  17462. for (p=0, pl = allpts.length; p<pl; p++) {
  17463. if (allpts[p].equals(find)) return p;
  17464. }
  17465. return -1;
  17466. };
  17467. // triangulate
  17468. js.poly2tri.sweep.Triangulate(swctx);
  17469. var triangles = swctx.GetTriangles();
  17470. var tr ;
  17471. var facesPts = [];
  17472. for (var t in triangles) {
  17473. tr = triangles[t];
  17474. facesPts.push([
  17475. findIndexForPt(tr.GetPoint(0)),
  17476. findIndexForPt(tr.GetPoint(1)),
  17477. findIndexForPt(tr.GetPoint(2))
  17478. ]);
  17479. }
  17480. // console.log(facesPts);
  17481. // console.log("triangles", triangles.length, triangles);
  17482. // Returns array of faces with 3 element each
  17483. return facesPts;
  17484. },
  17485. */
  17486. isClockWise: function ( pts ) {
  17487. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17488. },
  17489. // Bezier Curves formulas obtained from
  17490. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17491. // Quad Bezier Functions
  17492. b2p0: function ( t, p ) {
  17493. var k = 1 - t;
  17494. return k * k * p;
  17495. },
  17496. b2p1: function ( t, p ) {
  17497. return 2 * ( 1 - t ) * t * p;
  17498. },
  17499. b2p2: function ( t, p ) {
  17500. return t * t * p;
  17501. },
  17502. b2: function ( t, p0, p1, p2 ) {
  17503. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17504. },
  17505. // Cubic Bezier Functions
  17506. b3p0: function ( t, p ) {
  17507. var k = 1 - t;
  17508. return k * k * k * p;
  17509. },
  17510. b3p1: function ( t, p ) {
  17511. var k = 1 - t;
  17512. return 3 * k * k * t * p;
  17513. },
  17514. b3p2: function ( t, p ) {
  17515. var k = 1 - t;
  17516. return 3 * k * t * t * p;
  17517. },
  17518. b3p3: function ( t, p ) {
  17519. return t * t * t * p;
  17520. },
  17521. b3: function ( t, p0, p1, p2, p3 ) {
  17522. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17523. }
  17524. };
  17525. /**
  17526. * @author mikael emtinger / http://gomo.se/
  17527. */
  17528. THREE.AnimationHandler = (function() {
  17529. var playing = [];
  17530. var library = {};
  17531. var that = {};
  17532. //--- update ---
  17533. that.update = function( deltaTimeMS ) {
  17534. for( var i = 0; i < playing.length; i ++ )
  17535. playing[ i ].update( deltaTimeMS );
  17536. };
  17537. //--- add ---
  17538. that.addToUpdate = function( animation ) {
  17539. if ( playing.indexOf( animation ) === -1 )
  17540. playing.push( animation );
  17541. };
  17542. //--- remove ---
  17543. that.removeFromUpdate = function( animation ) {
  17544. var index = playing.indexOf( animation );
  17545. if( index !== -1 )
  17546. playing.splice( index, 1 );
  17547. };
  17548. //--- add ---
  17549. that.add = function( data ) {
  17550. if ( library[ data.name ] !== undefined )
  17551. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17552. library[ data.name ] = data;
  17553. initData( data );
  17554. };
  17555. //--- get ---
  17556. that.get = function( name ) {
  17557. if ( typeof name === "string" ) {
  17558. if ( library[ name ] ) {
  17559. return library[ name ];
  17560. } else {
  17561. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17562. return null;
  17563. }
  17564. } else {
  17565. // todo: add simple tween library
  17566. }
  17567. };
  17568. //--- parse ---
  17569. that.parse = function( root ) {
  17570. // setup hierarchy
  17571. var hierarchy = [];
  17572. if ( root instanceof THREE.SkinnedMesh ) {
  17573. for( var b = 0; b < root.bones.length; b++ ) {
  17574. hierarchy.push( root.bones[ b ] );
  17575. }
  17576. } else {
  17577. parseRecurseHierarchy( root, hierarchy );
  17578. }
  17579. return hierarchy;
  17580. };
  17581. var parseRecurseHierarchy = function( root, hierarchy ) {
  17582. hierarchy.push( root );
  17583. for( var c = 0; c < root.children.length; c++ )
  17584. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17585. }
  17586. //--- init data ---
  17587. var initData = function( data ) {
  17588. if( data.initialized === true )
  17589. return;
  17590. // loop through all keys
  17591. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17592. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17593. // remove minus times
  17594. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17595. data.hierarchy[ h ].keys[ k ].time = 0;
  17596. // create quaternions
  17597. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17598. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17599. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17600. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17601. }
  17602. }
  17603. // prepare morph target keys
  17604. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17605. // get all used
  17606. var usedMorphTargets = {};
  17607. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17608. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17609. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17610. usedMorphTargets[ morphTargetName ] = -1;
  17611. }
  17612. }
  17613. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17614. // set all used on all frames
  17615. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17616. var influences = {};
  17617. for ( var morphTargetName in usedMorphTargets ) {
  17618. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17619. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17620. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17621. break;
  17622. }
  17623. }
  17624. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17625. influences[ morphTargetName ] = 0;
  17626. }
  17627. }
  17628. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17629. }
  17630. }
  17631. // remove all keys that are on the same time
  17632. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17633. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17634. data.hierarchy[ h ].keys.splice( k, 1 );
  17635. k --;
  17636. }
  17637. }
  17638. // set index
  17639. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17640. data.hierarchy[ h ].keys[ k ].index = k;
  17641. }
  17642. }
  17643. // JIT
  17644. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17645. data.JIT = {};
  17646. data.JIT.hierarchy = [];
  17647. for( var h = 0; h < data.hierarchy.length; h ++ )
  17648. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17649. // done
  17650. data.initialized = true;
  17651. };
  17652. // interpolation types
  17653. that.LINEAR = 0;
  17654. that.CATMULLROM = 1;
  17655. that.CATMULLROM_FORWARD = 2;
  17656. return that;
  17657. }());
  17658. /**
  17659. * @author mikael emtinger / http://gomo.se/
  17660. * @author mrdoob / http://mrdoob.com/
  17661. * @author alteredq / http://alteredqualia.com/
  17662. */
  17663. THREE.Animation = function ( root, name, interpolationType ) {
  17664. this.root = root;
  17665. this.data = THREE.AnimationHandler.get( name );
  17666. this.hierarchy = THREE.AnimationHandler.parse( root );
  17667. this.currentTime = 0;
  17668. this.timeScale = 1;
  17669. this.isPlaying = false;
  17670. this.isPaused = true;
  17671. this.loop = true;
  17672. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17673. this.points = [];
  17674. this.target = new THREE.Vector3();
  17675. };
  17676. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17677. if ( this.isPlaying === false ) {
  17678. this.isPlaying = true;
  17679. this.loop = loop !== undefined ? loop : true;
  17680. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17681. // reset key cache
  17682. var h, hl = this.hierarchy.length,
  17683. object;
  17684. for ( h = 0; h < hl; h ++ ) {
  17685. object = this.hierarchy[ h ];
  17686. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17687. object.useQuaternion = true;
  17688. }
  17689. object.matrixAutoUpdate = true;
  17690. if ( object.animationCache === undefined ) {
  17691. object.animationCache = {};
  17692. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17693. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17694. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17695. }
  17696. var prevKey = object.animationCache.prevKey;
  17697. var nextKey = object.animationCache.nextKey;
  17698. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17699. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17700. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17701. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17702. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17703. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17704. }
  17705. this.update( 0 );
  17706. }
  17707. this.isPaused = false;
  17708. THREE.AnimationHandler.addToUpdate( this );
  17709. };
  17710. THREE.Animation.prototype.pause = function() {
  17711. if ( this.isPaused === true ) {
  17712. THREE.AnimationHandler.addToUpdate( this );
  17713. } else {
  17714. THREE.AnimationHandler.removeFromUpdate( this );
  17715. }
  17716. this.isPaused = !this.isPaused;
  17717. };
  17718. THREE.Animation.prototype.stop = function() {
  17719. this.isPlaying = false;
  17720. this.isPaused = false;
  17721. THREE.AnimationHandler.removeFromUpdate( this );
  17722. };
  17723. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17724. // early out
  17725. if ( this.isPlaying === false ) return;
  17726. // vars
  17727. var types = [ "pos", "rot", "scl" ];
  17728. var type;
  17729. var scale;
  17730. var vector;
  17731. var prevXYZ, nextXYZ;
  17732. var prevKey, nextKey;
  17733. var object;
  17734. var animationCache;
  17735. var frame;
  17736. var JIThierarchy = this.data.JIT.hierarchy;
  17737. var currentTime, unloopedCurrentTime;
  17738. var currentPoint, forwardPoint, angle;
  17739. this.currentTime += deltaTimeMS * this.timeScale;
  17740. unloopedCurrentTime = this.currentTime;
  17741. currentTime = this.currentTime = this.currentTime % this.data.length;
  17742. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17743. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17744. object = this.hierarchy[ h ];
  17745. animationCache = object.animationCache;
  17746. // loop through pos/rot/scl
  17747. for ( var t = 0; t < 3; t ++ ) {
  17748. // get keys
  17749. type = types[ t ];
  17750. prevKey = animationCache.prevKey[ type ];
  17751. nextKey = animationCache.nextKey[ type ];
  17752. // switch keys?
  17753. if ( nextKey.time <= unloopedCurrentTime ) {
  17754. // did we loop?
  17755. if ( currentTime < unloopedCurrentTime ) {
  17756. if ( this.loop ) {
  17757. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17758. nextKey = this.getNextKeyWith( type, h, 1 );
  17759. while( nextKey.time < currentTime ) {
  17760. prevKey = nextKey;
  17761. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17762. }
  17763. } else {
  17764. this.stop();
  17765. return;
  17766. }
  17767. } else {
  17768. do {
  17769. prevKey = nextKey;
  17770. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17771. } while( nextKey.time < currentTime )
  17772. }
  17773. animationCache.prevKey[ type ] = prevKey;
  17774. animationCache.nextKey[ type ] = nextKey;
  17775. }
  17776. object.matrixAutoUpdate = true;
  17777. object.matrixWorldNeedsUpdate = true;
  17778. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17779. prevXYZ = prevKey[ type ];
  17780. nextXYZ = nextKey[ type ];
  17781. // check scale error
  17782. if ( scale < 0 || scale > 1 ) {
  17783. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17784. scale = scale < 0 ? 0 : 1;
  17785. }
  17786. // interpolate
  17787. if ( type === "pos" ) {
  17788. vector = object.position;
  17789. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17790. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17791. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17792. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17793. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17794. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17795. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17796. this.points[ 1 ] = prevXYZ;
  17797. this.points[ 2 ] = nextXYZ;
  17798. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17799. scale = scale * 0.33 + 0.33;
  17800. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17801. vector.x = currentPoint[ 0 ];
  17802. vector.y = currentPoint[ 1 ];
  17803. vector.z = currentPoint[ 2 ];
  17804. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17805. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17806. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17807. this.target.sub( vector );
  17808. this.target.y = 0;
  17809. this.target.normalize();
  17810. angle = Math.atan2( this.target.x, this.target.z );
  17811. object.rotation.set( 0, angle, 0 );
  17812. }
  17813. }
  17814. } else if ( type === "rot" ) {
  17815. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17816. } else if ( type === "scl" ) {
  17817. vector = object.scale;
  17818. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17819. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17820. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17821. }
  17822. }
  17823. }
  17824. };
  17825. // Catmull-Rom spline
  17826. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17827. var c = [], v3 = [],
  17828. point, intPoint, weight, w2, w3,
  17829. pa, pb, pc, pd;
  17830. point = ( points.length - 1 ) * scale;
  17831. intPoint = Math.floor( point );
  17832. weight = point - intPoint;
  17833. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17834. c[ 1 ] = intPoint;
  17835. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17836. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17837. pa = points[ c[ 0 ] ];
  17838. pb = points[ c[ 1 ] ];
  17839. pc = points[ c[ 2 ] ];
  17840. pd = points[ c[ 3 ] ];
  17841. w2 = weight * weight;
  17842. w3 = weight * w2;
  17843. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17844. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17845. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17846. return v3;
  17847. };
  17848. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17849. var v0 = ( p2 - p0 ) * 0.5,
  17850. v1 = ( p3 - p1 ) * 0.5;
  17851. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17852. };
  17853. // Get next key with
  17854. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17855. var keys = this.data.hierarchy[ h ].keys;
  17856. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17857. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17858. key = key < keys.length - 1 ? key : keys.length - 1;
  17859. } else {
  17860. key = key % keys.length;
  17861. }
  17862. for ( ; key < keys.length; key++ ) {
  17863. if ( keys[ key ][ type ] !== undefined ) {
  17864. return keys[ key ];
  17865. }
  17866. }
  17867. return this.data.hierarchy[ h ].keys[ 0 ];
  17868. };
  17869. // Get previous key with
  17870. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17871. var keys = this.data.hierarchy[ h ].keys;
  17872. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17873. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17874. key = key > 0 ? key : 0;
  17875. } else {
  17876. key = key >= 0 ? key : key + keys.length;
  17877. }
  17878. for ( ; key >= 0; key -- ) {
  17879. if ( keys[ key ][ type ] !== undefined ) {
  17880. return keys[ key ];
  17881. }
  17882. }
  17883. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17884. };
  17885. /**
  17886. * @author mikael emtinger / http://gomo.se/
  17887. * @author mrdoob / http://mrdoob.com/
  17888. * @author alteredq / http://alteredqualia.com/
  17889. * @author khang duong
  17890. * @author erik kitson
  17891. */
  17892. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17893. this.root = root;
  17894. this.data = THREE.AnimationHandler.get( data );
  17895. this.hierarchy = THREE.AnimationHandler.parse( root );
  17896. this.currentTime = 0;
  17897. this.timeScale = 0.001;
  17898. this.isPlaying = false;
  17899. this.isPaused = true;
  17900. this.loop = true;
  17901. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17902. // initialize to first keyframes
  17903. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17904. var keys = this.data.hierarchy[h].keys,
  17905. sids = this.data.hierarchy[h].sids,
  17906. obj = this.hierarchy[h];
  17907. if ( keys.length && sids ) {
  17908. for ( var s = 0; s < sids.length; s++ ) {
  17909. var sid = sids[ s ],
  17910. next = this.getNextKeyWith( sid, h, 0 );
  17911. if ( next ) {
  17912. next.apply( sid );
  17913. }
  17914. }
  17915. obj.matrixAutoUpdate = false;
  17916. this.data.hierarchy[h].node.updateMatrix();
  17917. obj.matrixWorldNeedsUpdate = true;
  17918. }
  17919. }
  17920. };
  17921. // Play
  17922. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17923. if( !this.isPlaying ) {
  17924. this.isPlaying = true;
  17925. this.loop = loop !== undefined ? loop : true;
  17926. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17927. this.startTimeMs = startTimeMS;
  17928. this.startTime = 10000000;
  17929. this.endTime = -this.startTime;
  17930. // reset key cache
  17931. var h, hl = this.hierarchy.length,
  17932. object,
  17933. node;
  17934. for ( h = 0; h < hl; h++ ) {
  17935. object = this.hierarchy[ h ];
  17936. node = this.data.hierarchy[ h ];
  17937. object.useQuaternion = true;
  17938. if ( node.animationCache === undefined ) {
  17939. node.animationCache = {};
  17940. node.animationCache.prevKey = null;
  17941. node.animationCache.nextKey = null;
  17942. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17943. }
  17944. var keys = this.data.hierarchy[h].keys;
  17945. if (keys.length) {
  17946. node.animationCache.prevKey = keys[ 0 ];
  17947. node.animationCache.nextKey = keys[ 1 ];
  17948. this.startTime = Math.min( keys[0].time, this.startTime );
  17949. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17950. }
  17951. }
  17952. this.update( 0 );
  17953. }
  17954. this.isPaused = false;
  17955. THREE.AnimationHandler.addToUpdate( this );
  17956. };
  17957. // Pause
  17958. THREE.KeyFrameAnimation.prototype.pause = function() {
  17959. if( this.isPaused ) {
  17960. THREE.AnimationHandler.addToUpdate( this );
  17961. } else {
  17962. THREE.AnimationHandler.removeFromUpdate( this );
  17963. }
  17964. this.isPaused = !this.isPaused;
  17965. };
  17966. // Stop
  17967. THREE.KeyFrameAnimation.prototype.stop = function() {
  17968. this.isPlaying = false;
  17969. this.isPaused = false;
  17970. THREE.AnimationHandler.removeFromUpdate( this );
  17971. // reset JIT matrix and remove cache
  17972. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17973. var obj = this.hierarchy[ h ];
  17974. var node = this.data.hierarchy[ h ];
  17975. if ( node.animationCache !== undefined ) {
  17976. var original = node.animationCache.originalMatrix;
  17977. if( obj instanceof THREE.Bone ) {
  17978. original.copy( obj.skinMatrix );
  17979. obj.skinMatrix = original;
  17980. } else {
  17981. original.copy( obj.matrix );
  17982. obj.matrix = original;
  17983. }
  17984. delete node.animationCache;
  17985. }
  17986. }
  17987. };
  17988. // Update
  17989. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17990. // early out
  17991. if( !this.isPlaying ) return;
  17992. // vars
  17993. var prevKey, nextKey;
  17994. var object;
  17995. var node;
  17996. var frame;
  17997. var JIThierarchy = this.data.JIT.hierarchy;
  17998. var currentTime, unloopedCurrentTime;
  17999. var looped;
  18000. // update
  18001. this.currentTime += deltaTimeMS * this.timeScale;
  18002. unloopedCurrentTime = this.currentTime;
  18003. currentTime = this.currentTime = this.currentTime % this.data.length;
  18004. // if looped around, the current time should be based on the startTime
  18005. if ( currentTime < this.startTimeMs ) {
  18006. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18007. }
  18008. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18009. looped = currentTime < unloopedCurrentTime;
  18010. if ( looped && !this.loop ) {
  18011. // Set the animation to the last keyframes and stop
  18012. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18013. var keys = this.data.hierarchy[h].keys,
  18014. sids = this.data.hierarchy[h].sids,
  18015. end = keys.length-1,
  18016. obj = this.hierarchy[h];
  18017. if ( keys.length ) {
  18018. for ( var s = 0; s < sids.length; s++ ) {
  18019. var sid = sids[ s ],
  18020. prev = this.getPrevKeyWith( sid, h, end );
  18021. if ( prev ) {
  18022. prev.apply( sid );
  18023. }
  18024. }
  18025. this.data.hierarchy[h].node.updateMatrix();
  18026. obj.matrixWorldNeedsUpdate = true;
  18027. }
  18028. }
  18029. this.stop();
  18030. return;
  18031. }
  18032. // check pre-infinity
  18033. if ( currentTime < this.startTime ) {
  18034. return;
  18035. }
  18036. // update
  18037. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18038. object = this.hierarchy[ h ];
  18039. node = this.data.hierarchy[ h ];
  18040. var keys = node.keys,
  18041. animationCache = node.animationCache;
  18042. // use JIT?
  18043. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18044. if( object instanceof THREE.Bone ) {
  18045. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18046. object.matrixWorldNeedsUpdate = false;
  18047. } else {
  18048. object.matrix = JIThierarchy[ h ][ frame ];
  18049. object.matrixWorldNeedsUpdate = true;
  18050. }
  18051. // use interpolation
  18052. } else if ( keys.length ) {
  18053. // make sure so original matrix and not JIT matrix is set
  18054. if ( this.JITCompile && animationCache ) {
  18055. if( object instanceof THREE.Bone ) {
  18056. object.skinMatrix = animationCache.originalMatrix;
  18057. } else {
  18058. object.matrix = animationCache.originalMatrix;
  18059. }
  18060. }
  18061. prevKey = animationCache.prevKey;
  18062. nextKey = animationCache.nextKey;
  18063. if ( prevKey && nextKey ) {
  18064. // switch keys?
  18065. if ( nextKey.time <= unloopedCurrentTime ) {
  18066. // did we loop?
  18067. if ( looped && this.loop ) {
  18068. prevKey = keys[ 0 ];
  18069. nextKey = keys[ 1 ];
  18070. while ( nextKey.time < currentTime ) {
  18071. prevKey = nextKey;
  18072. nextKey = keys[ prevKey.index + 1 ];
  18073. }
  18074. } else if ( !looped ) {
  18075. var lastIndex = keys.length - 1;
  18076. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18077. prevKey = nextKey;
  18078. nextKey = keys[ prevKey.index + 1 ];
  18079. }
  18080. }
  18081. animationCache.prevKey = prevKey;
  18082. animationCache.nextKey = nextKey;
  18083. }
  18084. if(nextKey.time >= currentTime)
  18085. prevKey.interpolate( nextKey, currentTime );
  18086. else
  18087. prevKey.interpolate( nextKey, nextKey.time);
  18088. }
  18089. this.data.hierarchy[h].node.updateMatrix();
  18090. object.matrixWorldNeedsUpdate = true;
  18091. }
  18092. }
  18093. // update JIT?
  18094. if ( this.JITCompile ) {
  18095. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18096. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18097. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18098. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18099. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18100. } else {
  18101. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18102. }
  18103. }
  18104. }
  18105. }
  18106. };
  18107. // Get next key with
  18108. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18109. var keys = this.data.hierarchy[ h ].keys;
  18110. key = key % keys.length;
  18111. for ( ; key < keys.length; key++ ) {
  18112. if ( keys[ key ].hasTarget( sid ) ) {
  18113. return keys[ key ];
  18114. }
  18115. }
  18116. return keys[ 0 ];
  18117. };
  18118. // Get previous key with
  18119. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18120. var keys = this.data.hierarchy[ h ].keys;
  18121. key = key >= 0 ? key : key + keys.length;
  18122. for ( ; key >= 0; key-- ) {
  18123. if ( keys[ key ].hasTarget( sid ) ) {
  18124. return keys[ key ];
  18125. }
  18126. }
  18127. return keys[ keys.length - 1 ];
  18128. };
  18129. /**
  18130. * Camera for rendering cube maps
  18131. * - renders scene into axis-aligned cube
  18132. *
  18133. * @author alteredq / http://alteredqualia.com/
  18134. */
  18135. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18136. THREE.Object3D.call( this );
  18137. var fov = 90, aspect = 1;
  18138. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18139. cameraPX.up.set( 0, -1, 0 );
  18140. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18141. this.add( cameraPX );
  18142. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18143. cameraNX.up.set( 0, -1, 0 );
  18144. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18145. this.add( cameraNX );
  18146. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18147. cameraPY.up.set( 0, 0, 1 );
  18148. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18149. this.add( cameraPY );
  18150. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18151. cameraNY.up.set( 0, 0, -1 );
  18152. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18153. this.add( cameraNY );
  18154. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18155. cameraPZ.up.set( 0, -1, 0 );
  18156. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18157. this.add( cameraPZ );
  18158. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18159. cameraNZ.up.set( 0, -1, 0 );
  18160. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18161. this.add( cameraNZ );
  18162. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18163. this.updateCubeMap = function ( renderer, scene ) {
  18164. var renderTarget = this.renderTarget;
  18165. var generateMipmaps = renderTarget.generateMipmaps;
  18166. renderTarget.generateMipmaps = false;
  18167. renderTarget.activeCubeFace = 0;
  18168. renderer.render( scene, cameraPX, renderTarget );
  18169. renderTarget.activeCubeFace = 1;
  18170. renderer.render( scene, cameraNX, renderTarget );
  18171. renderTarget.activeCubeFace = 2;
  18172. renderer.render( scene, cameraPY, renderTarget );
  18173. renderTarget.activeCubeFace = 3;
  18174. renderer.render( scene, cameraNY, renderTarget );
  18175. renderTarget.activeCubeFace = 4;
  18176. renderer.render( scene, cameraPZ, renderTarget );
  18177. renderTarget.generateMipmaps = generateMipmaps;
  18178. renderTarget.activeCubeFace = 5;
  18179. renderer.render( scene, cameraNZ, renderTarget );
  18180. };
  18181. };
  18182. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18183. /*
  18184. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18185. *
  18186. * A general perpose camera, for setting FOV, Lens Focal Length,
  18187. * and switching between perspective and orthographic views easily.
  18188. * Use this only if you do not wish to manage
  18189. * both a Orthographic and Perspective Camera
  18190. *
  18191. */
  18192. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18193. THREE.Camera.call( this );
  18194. this.fov = fov;
  18195. this.left = -width / 2;
  18196. this.right = width / 2
  18197. this.top = height / 2;
  18198. this.bottom = -height / 2;
  18199. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18200. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18201. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18202. this.zoom = 1;
  18203. this.toPerspective();
  18204. var aspect = width/height;
  18205. };
  18206. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18207. THREE.CombinedCamera.prototype.toPerspective = function () {
  18208. // Switches to the Perspective Camera
  18209. this.near = this.cameraP.near;
  18210. this.far = this.cameraP.far;
  18211. this.cameraP.fov = this.fov / this.zoom ;
  18212. this.cameraP.updateProjectionMatrix();
  18213. this.projectionMatrix = this.cameraP.projectionMatrix;
  18214. this.inPerspectiveMode = true;
  18215. this.inOrthographicMode = false;
  18216. };
  18217. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18218. // Switches to the Orthographic camera estimating viewport from Perspective
  18219. var fov = this.fov;
  18220. var aspect = this.cameraP.aspect;
  18221. var near = this.cameraP.near;
  18222. var far = this.cameraP.far;
  18223. // The size that we set is the mid plane of the viewing frustum
  18224. var hyperfocus = ( near + far ) / 2;
  18225. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18226. var planeHeight = 2 * halfHeight;
  18227. var planeWidth = planeHeight * aspect;
  18228. var halfWidth = planeWidth / 2;
  18229. halfHeight /= this.zoom;
  18230. halfWidth /= this.zoom;
  18231. this.cameraO.left = -halfWidth;
  18232. this.cameraO.right = halfWidth;
  18233. this.cameraO.top = halfHeight;
  18234. this.cameraO.bottom = -halfHeight;
  18235. // this.cameraO.left = -farHalfWidth;
  18236. // this.cameraO.right = farHalfWidth;
  18237. // this.cameraO.top = farHalfHeight;
  18238. // this.cameraO.bottom = -farHalfHeight;
  18239. // this.cameraO.left = this.left / this.zoom;
  18240. // this.cameraO.right = this.right / this.zoom;
  18241. // this.cameraO.top = this.top / this.zoom;
  18242. // this.cameraO.bottom = this.bottom / this.zoom;
  18243. this.cameraO.updateProjectionMatrix();
  18244. this.near = this.cameraO.near;
  18245. this.far = this.cameraO.far;
  18246. this.projectionMatrix = this.cameraO.projectionMatrix;
  18247. this.inPerspectiveMode = false;
  18248. this.inOrthographicMode = true;
  18249. };
  18250. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18251. this.cameraP.aspect = width / height;
  18252. this.left = -width / 2;
  18253. this.right = width / 2
  18254. this.top = height / 2;
  18255. this.bottom = -height / 2;
  18256. };
  18257. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18258. this.fov = fov;
  18259. if ( this.inPerspectiveMode ) {
  18260. this.toPerspective();
  18261. } else {
  18262. this.toOrthographic();
  18263. }
  18264. };
  18265. // For mantaining similar API with PerspectiveCamera
  18266. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18267. if ( this.inPerspectiveMode ) {
  18268. this.toPerspective();
  18269. } else {
  18270. this.toPerspective();
  18271. this.toOrthographic();
  18272. }
  18273. };
  18274. /*
  18275. * Uses Focal Length (in mm) to estimate and set FOV
  18276. * 35mm (fullframe) camera is used if frame size is not specified;
  18277. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18278. */
  18279. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18280. if ( frameHeight === undefined ) frameHeight = 24;
  18281. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18282. this.setFov( fov );
  18283. return fov;
  18284. };
  18285. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18286. this.zoom = zoom;
  18287. if ( this.inPerspectiveMode ) {
  18288. this.toPerspective();
  18289. } else {
  18290. this.toOrthographic();
  18291. }
  18292. };
  18293. THREE.CombinedCamera.prototype.toFrontView = function() {
  18294. this.rotation.x = 0;
  18295. this.rotation.y = 0;
  18296. this.rotation.z = 0;
  18297. // should we be modifing the matrix instead?
  18298. this.rotationAutoUpdate = false;
  18299. };
  18300. THREE.CombinedCamera.prototype.toBackView = function() {
  18301. this.rotation.x = 0;
  18302. this.rotation.y = Math.PI;
  18303. this.rotation.z = 0;
  18304. this.rotationAutoUpdate = false;
  18305. };
  18306. THREE.CombinedCamera.prototype.toLeftView = function() {
  18307. this.rotation.x = 0;
  18308. this.rotation.y = - Math.PI / 2;
  18309. this.rotation.z = 0;
  18310. this.rotationAutoUpdate = false;
  18311. };
  18312. THREE.CombinedCamera.prototype.toRightView = function() {
  18313. this.rotation.x = 0;
  18314. this.rotation.y = Math.PI / 2;
  18315. this.rotation.z = 0;
  18316. this.rotationAutoUpdate = false;
  18317. };
  18318. THREE.CombinedCamera.prototype.toTopView = function() {
  18319. this.rotation.x = - Math.PI / 2;
  18320. this.rotation.y = 0;
  18321. this.rotation.z = 0;
  18322. this.rotationAutoUpdate = false;
  18323. };
  18324. THREE.CombinedCamera.prototype.toBottomView = function() {
  18325. this.rotation.x = Math.PI / 2;
  18326. this.rotation.y = 0;
  18327. this.rotation.z = 0;
  18328. this.rotationAutoUpdate = false;
  18329. };
  18330. /**
  18331. * @author alteredq / http://alteredqualia.com/
  18332. *
  18333. * - 3d asterisk shape (for line pieces THREE.Line)
  18334. */
  18335. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18336. THREE.Geometry.call( this );
  18337. var sd = innerRadius;
  18338. var ed = outerRadius;
  18339. var sd2 = 0.707 * sd;
  18340. var ed2 = 0.707 * ed;
  18341. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18342. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18343. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18344. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18345. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18346. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18347. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18348. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18349. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18350. ];
  18351. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18352. var x = rays[ i ][ 0 ];
  18353. var y = rays[ i ][ 1 ];
  18354. var z = rays[ i ][ 2 ];
  18355. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18356. }
  18357. };
  18358. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18359. * @author hughes
  18360. */
  18361. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18362. THREE.Geometry.call( this );
  18363. radius = radius || 50;
  18364. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18365. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18366. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18367. var i, uvs = [],
  18368. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18369. this.vertices.push(center);
  18370. uvs.push( centerUV );
  18371. for ( i = 0; i <= segments; i ++ ) {
  18372. var vertex = new THREE.Vector3();
  18373. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18374. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18375. this.vertices.push( vertex );
  18376. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18377. }
  18378. var n = new THREE.Vector3( 0, 0, -1 );
  18379. for ( i = 1; i <= segments; i ++ ) {
  18380. var v1 = i;
  18381. var v2 = i + 1 ;
  18382. var v3 = 0;
  18383. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18384. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18385. }
  18386. this.computeCentroids();
  18387. this.computeFaceNormals();
  18388. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18389. };
  18390. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18391. /**
  18392. * @author mrdoob / http://mrdoob.com/
  18393. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18394. */
  18395. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18396. THREE.Geometry.call( this );
  18397. var scope = this;
  18398. this.width = width;
  18399. this.height = height;
  18400. this.depth = depth;
  18401. this.widthSegments = widthSegments || 1;
  18402. this.heightSegments = heightSegments || 1;
  18403. this.depthSegments = depthSegments || 1;
  18404. var width_half = this.width / 2;
  18405. var height_half = this.height / 2;
  18406. var depth_half = this.depth / 2;
  18407. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18408. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18409. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18410. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18411. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18412. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18413. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18414. var w, ix, iy,
  18415. gridX = scope.widthSegments,
  18416. gridY = scope.heightSegments,
  18417. width_half = width / 2,
  18418. height_half = height / 2,
  18419. offset = scope.vertices.length;
  18420. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18421. w = 'z';
  18422. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18423. w = 'y';
  18424. gridY = scope.depthSegments;
  18425. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18426. w = 'x';
  18427. gridX = scope.depthSegments;
  18428. }
  18429. var gridX1 = gridX + 1,
  18430. gridY1 = gridY + 1,
  18431. segment_width = width / gridX,
  18432. segment_height = height / gridY,
  18433. normal = new THREE.Vector3();
  18434. normal[ w ] = depth > 0 ? 1 : - 1;
  18435. for ( iy = 0; iy < gridY1; iy ++ ) {
  18436. for ( ix = 0; ix < gridX1; ix ++ ) {
  18437. var vector = new THREE.Vector3();
  18438. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18439. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18440. vector[ w ] = depth;
  18441. scope.vertices.push( vector );
  18442. }
  18443. }
  18444. for ( iy = 0; iy < gridY; iy++ ) {
  18445. for ( ix = 0; ix < gridX; ix++ ) {
  18446. var a = ix + gridX1 * iy;
  18447. var b = ix + gridX1 * ( iy + 1 );
  18448. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18449. var d = ( ix + 1 ) + gridX1 * iy;
  18450. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18451. face.normal.copy( normal );
  18452. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18453. face.materialIndex = materialIndex;
  18454. scope.faces.push( face );
  18455. scope.faceVertexUvs[ 0 ].push( [
  18456. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18457. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18458. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18459. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18460. ] );
  18461. }
  18462. }
  18463. }
  18464. this.computeCentroids();
  18465. this.mergeVertices();
  18466. };
  18467. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18468. /**
  18469. * @author mrdoob / http://mrdoob.com/
  18470. */
  18471. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18472. THREE.Geometry.call( this );
  18473. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18474. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18475. height = height !== undefined ? height : 100;
  18476. var heightHalf = height / 2;
  18477. var segmentsX = radiusSegments || 8;
  18478. var segmentsY = heightSegments || 1;
  18479. var x, y, vertices = [], uvs = [];
  18480. for ( y = 0; y <= segmentsY; y ++ ) {
  18481. var verticesRow = [];
  18482. var uvsRow = [];
  18483. var v = y / segmentsY;
  18484. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18485. for ( x = 0; x <= segmentsX; x ++ ) {
  18486. var u = x / segmentsX;
  18487. var vertex = new THREE.Vector3();
  18488. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18489. vertex.y = - v * height + heightHalf;
  18490. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18491. this.vertices.push( vertex );
  18492. verticesRow.push( this.vertices.length - 1 );
  18493. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18494. }
  18495. vertices.push( verticesRow );
  18496. uvs.push( uvsRow );
  18497. }
  18498. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18499. var na, nb;
  18500. for ( x = 0; x < segmentsX; x ++ ) {
  18501. if ( radiusTop !== 0 ) {
  18502. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18503. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18504. } else {
  18505. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18506. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18507. }
  18508. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18509. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18510. for ( y = 0; y < segmentsY; y ++ ) {
  18511. var v1 = vertices[ y ][ x ];
  18512. var v2 = vertices[ y + 1 ][ x ];
  18513. var v3 = vertices[ y + 1 ][ x + 1 ];
  18514. var v4 = vertices[ y ][ x + 1 ];
  18515. var n1 = na.clone();
  18516. var n2 = na.clone();
  18517. var n3 = nb.clone();
  18518. var n4 = nb.clone();
  18519. var uv1 = uvs[ y ][ x ].clone();
  18520. var uv2 = uvs[ y + 1 ][ x ].clone();
  18521. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18522. var uv4 = uvs[ y ][ x + 1 ].clone();
  18523. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18524. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18525. }
  18526. }
  18527. // top cap
  18528. if ( !openEnded && radiusTop > 0 ) {
  18529. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18530. for ( x = 0; x < segmentsX; x ++ ) {
  18531. var v1 = vertices[ 0 ][ x ];
  18532. var v2 = vertices[ 0 ][ x + 1 ];
  18533. var v3 = this.vertices.length - 1;
  18534. var n1 = new THREE.Vector3( 0, 1, 0 );
  18535. var n2 = new THREE.Vector3( 0, 1, 0 );
  18536. var n3 = new THREE.Vector3( 0, 1, 0 );
  18537. var uv1 = uvs[ 0 ][ x ].clone();
  18538. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18539. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18540. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18541. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18542. }
  18543. }
  18544. // bottom cap
  18545. if ( !openEnded && radiusBottom > 0 ) {
  18546. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18547. for ( x = 0; x < segmentsX; x ++ ) {
  18548. var v1 = vertices[ y ][ x + 1 ];
  18549. var v2 = vertices[ y ][ x ];
  18550. var v3 = this.vertices.length - 1;
  18551. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18552. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18553. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18554. var uv1 = uvs[ y ][ x + 1 ].clone();
  18555. var uv2 = uvs[ y ][ x ].clone();
  18556. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18557. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18558. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18559. }
  18560. }
  18561. this.computeCentroids();
  18562. this.computeFaceNormals();
  18563. }
  18564. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18565. /**
  18566. * @author zz85 / http://www.lab4games.net/zz85/blog
  18567. *
  18568. * Creates extruded geometry from a path shape.
  18569. *
  18570. * parameters = {
  18571. *
  18572. * size: <float>, // size of the text
  18573. * height: <float>, // thickness to extrude text
  18574. * curveSegments: <int>, // number of points on the curves
  18575. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18576. * amount: <int>, // Amount
  18577. *
  18578. * bevelEnabled: <bool>, // turn on bevel
  18579. * bevelThickness: <float>, // how deep into text bevel goes
  18580. * bevelSize: <float>, // how far from text outline is bevel
  18581. * bevelSegments: <int>, // number of bevel layers
  18582. *
  18583. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18584. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18585. *
  18586. * material: <int> // material index for front and back faces
  18587. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18588. * uvGenerator: <Object> // object that provides UV generator functions
  18589. *
  18590. * }
  18591. **/
  18592. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18593. if ( typeof( shapes ) === "undefined" ) {
  18594. shapes = [];
  18595. return;
  18596. }
  18597. THREE.Geometry.call( this );
  18598. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18599. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18600. this.addShapeList( shapes, options );
  18601. this.computeCentroids();
  18602. this.computeFaceNormals();
  18603. // can't really use automatic vertex normals
  18604. // as then front and back sides get smoothed too
  18605. // should do separate smoothing just for sides
  18606. //this.computeVertexNormals();
  18607. //console.log( "took", ( Date.now() - startTime ) );
  18608. };
  18609. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18610. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18611. var sl = shapes.length;
  18612. for ( var s = 0; s < sl; s ++ ) {
  18613. var shape = shapes[ s ];
  18614. this.addShape( shape, options );
  18615. }
  18616. };
  18617. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18618. var amount = options.amount !== undefined ? options.amount : 100;
  18619. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18620. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18621. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18622. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18623. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18624. var steps = options.steps !== undefined ? options.steps : 1;
  18625. var extrudePath = options.extrudePath;
  18626. var extrudePts, extrudeByPath = false;
  18627. var material = options.material;
  18628. var extrudeMaterial = options.extrudeMaterial;
  18629. // Use default WorldUVGenerator if no UV generators are specified.
  18630. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18631. var shapebb = this.shapebb;
  18632. //shapebb = shape.getBoundingBox();
  18633. var splineTube, binormal, normal, position2;
  18634. if ( extrudePath ) {
  18635. extrudePts = extrudePath.getSpacedPoints( steps );
  18636. extrudeByPath = true;
  18637. bevelEnabled = false; // bevels not supported for path extrusion
  18638. // SETUP TNB variables
  18639. // Reuse TNB from TubeGeomtry for now.
  18640. // TODO1 - have a .isClosed in spline?
  18641. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18642. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18643. binormal = new THREE.Vector3();
  18644. normal = new THREE.Vector3();
  18645. position2 = new THREE.Vector3();
  18646. }
  18647. // Safeguards if bevels are not enabled
  18648. if ( ! bevelEnabled ) {
  18649. bevelSegments = 0;
  18650. bevelThickness = 0;
  18651. bevelSize = 0;
  18652. }
  18653. // Variables initalization
  18654. var ahole, h, hl; // looping of holes
  18655. var scope = this;
  18656. var bevelPoints = [];
  18657. var shapesOffset = this.vertices.length;
  18658. var shapePoints = shape.extractPoints( curveSegments );
  18659. var vertices = shapePoints.shape;
  18660. var holes = shapePoints.holes;
  18661. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18662. if ( reverse ) {
  18663. vertices = vertices.reverse();
  18664. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18665. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18666. ahole = holes[ h ];
  18667. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18668. holes[ h ] = ahole.reverse();
  18669. }
  18670. }
  18671. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18672. }
  18673. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18674. /* Vertices */
  18675. var contour = vertices; // vertices has all points but contour has only points of circumference
  18676. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18677. ahole = holes[ h ];
  18678. vertices = vertices.concat( ahole );
  18679. }
  18680. function scalePt2 ( pt, vec, size ) {
  18681. if ( !vec ) console.log( "die" );
  18682. return vec.clone().multiplyScalar( size ).add( pt );
  18683. }
  18684. var b, bs, t, z,
  18685. vert, vlen = vertices.length,
  18686. face, flen = faces.length,
  18687. cont, clen = contour.length;
  18688. // Find directions for point movement
  18689. var RAD_TO_DEGREES = 180 / Math.PI;
  18690. function getBevelVec( pt_i, pt_j, pt_k ) {
  18691. // Algorithm 2
  18692. return getBevelVec2( pt_i, pt_j, pt_k );
  18693. }
  18694. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18695. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18696. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18697. if ( anglea > angleb ) {
  18698. angleb += Math.PI * 2;
  18699. }
  18700. var anglec = ( anglea + angleb ) / 2;
  18701. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18702. var x = - Math.cos( anglec );
  18703. var y = - Math.sin( anglec );
  18704. var vec = new THREE.Vector2( x, y ); //.normalize();
  18705. return vec;
  18706. }
  18707. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18708. var a = THREE.ExtrudeGeometry.__v1,
  18709. b = THREE.ExtrudeGeometry.__v2,
  18710. v_hat = THREE.ExtrudeGeometry.__v3,
  18711. w_hat = THREE.ExtrudeGeometry.__v4,
  18712. p = THREE.ExtrudeGeometry.__v5,
  18713. q = THREE.ExtrudeGeometry.__v6,
  18714. v, w,
  18715. v_dot_w_hat, q_sub_p_dot_w_hat,
  18716. s, intersection;
  18717. // good reading for line-line intersection
  18718. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18719. // define a as vector j->i
  18720. // define b as vectot k->i
  18721. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18722. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18723. // get unit vectors
  18724. v = a.normalize();
  18725. w = b.normalize();
  18726. // normals from pt i
  18727. v_hat.set( -v.y, v.x );
  18728. w_hat.set( w.y, -w.x );
  18729. // pts from i
  18730. p.copy( pt_i ).add( v_hat );
  18731. q.copy( pt_i ).add( w_hat );
  18732. if ( p.equals( q ) ) {
  18733. //console.log("Warning: lines are straight");
  18734. return w_hat.clone();
  18735. }
  18736. // Points from j, k. helps prevents points cross overover most of the time
  18737. p.copy( pt_j ).add( v_hat );
  18738. q.copy( pt_k ).add( w_hat );
  18739. v_dot_w_hat = v.dot( w_hat );
  18740. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18741. // We should not reach these conditions
  18742. if ( v_dot_w_hat === 0 ) {
  18743. console.log( "Either infinite or no solutions!" );
  18744. if ( q_sub_p_dot_w_hat === 0 ) {
  18745. console.log( "Its finite solutions." );
  18746. } else {
  18747. console.log( "Too bad, no solutions." );
  18748. }
  18749. }
  18750. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18751. if ( s < 0 ) {
  18752. // in case of emergecy, revert to algorithm 1.
  18753. return getBevelVec1( pt_i, pt_j, pt_k );
  18754. }
  18755. intersection = v.multiplyScalar( s ).add( p );
  18756. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18757. }
  18758. var contourMovements = [];
  18759. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18760. if ( j === il ) j = 0;
  18761. if ( k === il ) k = 0;
  18762. // (j)---(i)---(k)
  18763. // console.log('i,j,k', i, j , k)
  18764. var pt_i = contour[ i ];
  18765. var pt_j = contour[ j ];
  18766. var pt_k = contour[ k ];
  18767. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18768. }
  18769. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18770. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18771. ahole = holes[ h ];
  18772. oneHoleMovements = [];
  18773. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18774. if ( j === il ) j = 0;
  18775. if ( k === il ) k = 0;
  18776. // (j)---(i)---(k)
  18777. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18778. }
  18779. holesMovements.push( oneHoleMovements );
  18780. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18781. }
  18782. // Loop bevelSegments, 1 for the front, 1 for the back
  18783. for ( b = 0; b < bevelSegments; b ++ ) {
  18784. //for ( b = bevelSegments; b > 0; b -- ) {
  18785. t = b / bevelSegments;
  18786. z = bevelThickness * ( 1 - t );
  18787. //z = bevelThickness * t;
  18788. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18789. //bs = bevelSize * t ; // linear
  18790. // contract shape
  18791. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18792. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18793. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18794. v( vert.x, vert.y, - z );
  18795. }
  18796. // expand holes
  18797. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18798. ahole = holes[ h ];
  18799. oneHoleMovements = holesMovements[ h ];
  18800. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18801. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18802. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18803. v( vert.x, vert.y, -z );
  18804. }
  18805. }
  18806. }
  18807. bs = bevelSize;
  18808. // Back facing vertices
  18809. for ( i = 0; i < vlen; i ++ ) {
  18810. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18811. if ( !extrudeByPath ) {
  18812. v( vert.x, vert.y, 0 );
  18813. } else {
  18814. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18815. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18816. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18817. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18818. v( position2.x, position2.y, position2.z );
  18819. }
  18820. }
  18821. // Add stepped vertices...
  18822. // Including front facing vertices
  18823. var s;
  18824. for ( s = 1; s <= steps; s ++ ) {
  18825. for ( i = 0; i < vlen; i ++ ) {
  18826. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18827. if ( !extrudeByPath ) {
  18828. v( vert.x, vert.y, amount / steps * s );
  18829. } else {
  18830. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18831. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18832. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18833. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18834. v( position2.x, position2.y, position2.z );
  18835. }
  18836. }
  18837. }
  18838. // Add bevel segments planes
  18839. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18840. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18841. t = b / bevelSegments;
  18842. z = bevelThickness * ( 1 - t );
  18843. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18844. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18845. // contract shape
  18846. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18847. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18848. v( vert.x, vert.y, amount + z );
  18849. }
  18850. // expand holes
  18851. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18852. ahole = holes[ h ];
  18853. oneHoleMovements = holesMovements[ h ];
  18854. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18855. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18856. if ( !extrudeByPath ) {
  18857. v( vert.x, vert.y, amount + z );
  18858. } else {
  18859. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18860. }
  18861. }
  18862. }
  18863. }
  18864. /* Faces */
  18865. // Top and bottom faces
  18866. buildLidFaces();
  18867. // Sides faces
  18868. buildSideFaces();
  18869. ///// Internal functions
  18870. function buildLidFaces() {
  18871. if ( bevelEnabled ) {
  18872. var layer = 0 ; // steps + 1
  18873. var offset = vlen * layer;
  18874. // Bottom faces
  18875. for ( i = 0; i < flen; i ++ ) {
  18876. face = faces[ i ];
  18877. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18878. }
  18879. layer = steps + bevelSegments * 2;
  18880. offset = vlen * layer;
  18881. // Top faces
  18882. for ( i = 0; i < flen; i ++ ) {
  18883. face = faces[ i ];
  18884. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18885. }
  18886. } else {
  18887. // Bottom faces
  18888. for ( i = 0; i < flen; i++ ) {
  18889. face = faces[ i ];
  18890. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18891. }
  18892. // Top faces
  18893. for ( i = 0; i < flen; i ++ ) {
  18894. face = faces[ i ];
  18895. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18896. }
  18897. }
  18898. }
  18899. // Create faces for the z-sides of the shape
  18900. function buildSideFaces() {
  18901. var layeroffset = 0;
  18902. sidewalls( contour, layeroffset );
  18903. layeroffset += contour.length;
  18904. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18905. ahole = holes[ h ];
  18906. sidewalls( ahole, layeroffset );
  18907. //, true
  18908. layeroffset += ahole.length;
  18909. }
  18910. }
  18911. function sidewalls( contour, layeroffset ) {
  18912. var j, k;
  18913. i = contour.length;
  18914. while ( --i >= 0 ) {
  18915. j = i;
  18916. k = i - 1;
  18917. if ( k < 0 ) k = contour.length - 1;
  18918. //console.log('b', i,j, i-1, k,vertices.length);
  18919. var s = 0, sl = steps + bevelSegments * 2;
  18920. for ( s = 0; s < sl; s ++ ) {
  18921. var slen1 = vlen * s;
  18922. var slen2 = vlen * ( s + 1 );
  18923. var a = layeroffset + j + slen1,
  18924. b = layeroffset + k + slen1,
  18925. c = layeroffset + k + slen2,
  18926. d = layeroffset + j + slen2;
  18927. f4( a, b, c, d, contour, s, sl, j, k );
  18928. }
  18929. }
  18930. }
  18931. function v( x, y, z ) {
  18932. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18933. }
  18934. function f3( a, b, c, isBottom ) {
  18935. a += shapesOffset;
  18936. b += shapesOffset;
  18937. c += shapesOffset;
  18938. // normal, color, material
  18939. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18940. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18941. scope.faceVertexUvs[ 0 ].push( uvs );
  18942. }
  18943. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18944. a += shapesOffset;
  18945. b += shapesOffset;
  18946. c += shapesOffset;
  18947. d += shapesOffset;
  18948. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18949. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18950. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18951. scope.faceVertexUvs[ 0 ].push( uvs );
  18952. }
  18953. };
  18954. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18955. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18956. var ax = geometry.vertices[ indexA ].x,
  18957. ay = geometry.vertices[ indexA ].y,
  18958. bx = geometry.vertices[ indexB ].x,
  18959. by = geometry.vertices[ indexB ].y,
  18960. cx = geometry.vertices[ indexC ].x,
  18961. cy = geometry.vertices[ indexC ].y;
  18962. return [
  18963. new THREE.Vector2( ax, ay ),
  18964. new THREE.Vector2( bx, by ),
  18965. new THREE.Vector2( cx, cy )
  18966. ];
  18967. },
  18968. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18969. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18970. },
  18971. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18972. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18973. contourIndex1, contourIndex2 ) {
  18974. var ax = geometry.vertices[ indexA ].x,
  18975. ay = geometry.vertices[ indexA ].y,
  18976. az = geometry.vertices[ indexA ].z,
  18977. bx = geometry.vertices[ indexB ].x,
  18978. by = geometry.vertices[ indexB ].y,
  18979. bz = geometry.vertices[ indexB ].z,
  18980. cx = geometry.vertices[ indexC ].x,
  18981. cy = geometry.vertices[ indexC ].y,
  18982. cz = geometry.vertices[ indexC ].z,
  18983. dx = geometry.vertices[ indexD ].x,
  18984. dy = geometry.vertices[ indexD ].y,
  18985. dz = geometry.vertices[ indexD ].z;
  18986. if ( Math.abs( ay - by ) < 0.01 ) {
  18987. return [
  18988. new THREE.Vector2( ax, 1 - az ),
  18989. new THREE.Vector2( bx, 1 - bz ),
  18990. new THREE.Vector2( cx, 1 - cz ),
  18991. new THREE.Vector2( dx, 1 - dz )
  18992. ];
  18993. } else {
  18994. return [
  18995. new THREE.Vector2( ay, 1 - az ),
  18996. new THREE.Vector2( by, 1 - bz ),
  18997. new THREE.Vector2( cy, 1 - cz ),
  18998. new THREE.Vector2( dy, 1 - dz )
  18999. ];
  19000. }
  19001. }
  19002. };
  19003. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19004. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19005. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19006. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19007. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19008. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19009. /**
  19010. * @author jonobr1 / http://jonobr1.com
  19011. *
  19012. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19013. * ExtrudeGeometry.
  19014. *
  19015. * parameters = {
  19016. *
  19017. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19018. *
  19019. * material: <int> // material index for front and back faces
  19020. * uvGenerator: <Object> // object that provides UV generator functions
  19021. *
  19022. * }
  19023. **/
  19024. THREE.ShapeGeometry = function ( shapes, options ) {
  19025. THREE.Geometry.call( this );
  19026. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19027. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19028. this.addShapeList( shapes, options );
  19029. this.computeCentroids();
  19030. this.computeFaceNormals();
  19031. };
  19032. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19033. /**
  19034. * Add an array of shapes to THREE.ShapeGeometry.
  19035. */
  19036. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19037. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19038. this.addShape( shapes[ i ], options );
  19039. }
  19040. return this;
  19041. };
  19042. /**
  19043. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19044. */
  19045. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19046. if ( options === undefined ) options = {};
  19047. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19048. var material = options.material;
  19049. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19050. var shapebb = this.shapebb;
  19051. //
  19052. var i, l, hole, s;
  19053. var shapesOffset = this.vertices.length;
  19054. var shapePoints = shape.extractPoints( curveSegments );
  19055. var vertices = shapePoints.shape;
  19056. var holes = shapePoints.holes;
  19057. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19058. if ( reverse ) {
  19059. vertices = vertices.reverse();
  19060. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19061. for ( i = 0, l = holes.length; i < l; i++ ) {
  19062. hole = holes[ i ];
  19063. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19064. holes[ i ] = hole.reverse();
  19065. }
  19066. }
  19067. reverse = false;
  19068. }
  19069. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19070. // Vertices
  19071. var contour = vertices;
  19072. for ( i = 0, l = holes.length; i < l; i++ ) {
  19073. hole = holes[ i ];
  19074. vertices = vertices.concat( hole );
  19075. }
  19076. //
  19077. var vert, vlen = vertices.length;
  19078. var face, flen = faces.length;
  19079. var cont, clen = contour.length;
  19080. for ( i = 0; i < vlen; i++ ) {
  19081. vert = vertices[ i ];
  19082. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19083. }
  19084. for ( i = 0; i < flen; i++ ) {
  19085. face = faces[ i ];
  19086. var a = face[ 0 ] + shapesOffset;
  19087. var b = face[ 1 ] + shapesOffset;
  19088. var c = face[ 2 ] + shapesOffset;
  19089. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19090. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19091. }
  19092. };
  19093. /**
  19094. * @author astrodud / http://astrodud.isgreat.org/
  19095. * @author zz85 / https://github.com/zz85
  19096. * @author bhouston / http://exocortex.com
  19097. */
  19098. // points - to create a closed torus, one must use a set of points
  19099. // like so: [ a, b, c, d, a ], see first is the same as last.
  19100. // segments - the number of circumference segments to create
  19101. // phiStart - the starting radian
  19102. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19103. // 2*pi is a closed lathe, less than 2PI is a portion.
  19104. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19105. THREE.Geometry.call( this );
  19106. segments = segments || 12;
  19107. phiStart = phiStart || 0;
  19108. phiLength = phiLength || 2 * Math.PI;
  19109. var inversePointLength = 1.0 / ( points.length - 1 );
  19110. var inverseSegments = 1.0 / segments;
  19111. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19112. var phi = phiStart + i * inverseSegments * phiLength;
  19113. var c = Math.cos( phi ),
  19114. s = Math.sin( phi );
  19115. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19116. var pt = points[ j ];
  19117. var vertex = new THREE.Vector3();
  19118. vertex.x = c * pt.x - s * pt.y;
  19119. vertex.y = s * pt.x + c * pt.y;
  19120. vertex.z = pt.z;
  19121. this.vertices.push( vertex );
  19122. }
  19123. }
  19124. var np = points.length;
  19125. for ( var i = 0, il = segments; i < il; i ++ ) {
  19126. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19127. var base = j + np * i;
  19128. var a = base;
  19129. var b = base + np;
  19130. var c = base + 1 + np;
  19131. var d = base + 1;
  19132. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19133. var u0 = i * inverseSegments;
  19134. var v0 = j * inversePointLength;
  19135. var u1 = u0 + inverseSegments;
  19136. var v1 = v0 + inversePointLength;
  19137. this.faceVertexUvs[ 0 ].push( [
  19138. new THREE.Vector2( u0, v0 ),
  19139. new THREE.Vector2( u1, v0 ),
  19140. new THREE.Vector2( u1, v1 ),
  19141. new THREE.Vector2( u0, v1 )
  19142. ] );
  19143. }
  19144. }
  19145. this.mergeVertices();
  19146. this.computeCentroids();
  19147. this.computeFaceNormals();
  19148. this.computeVertexNormals();
  19149. };
  19150. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19151. /**
  19152. * @author mrdoob / http://mrdoob.com/
  19153. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19154. */
  19155. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19156. THREE.Geometry.call( this );
  19157. this.width = width;
  19158. this.height = height;
  19159. this.widthSegments = widthSegments || 1;
  19160. this.heightSegments = heightSegments || 1;
  19161. var ix, iz;
  19162. var width_half = width / 2;
  19163. var height_half = height / 2;
  19164. var gridX = this.widthSegments;
  19165. var gridZ = this.heightSegments;
  19166. var gridX1 = gridX + 1;
  19167. var gridZ1 = gridZ + 1;
  19168. var segment_width = this.width / gridX;
  19169. var segment_height = this.height / gridZ;
  19170. var normal = new THREE.Vector3( 0, 0, 1 );
  19171. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19172. for ( ix = 0; ix < gridX1; ix ++ ) {
  19173. var x = ix * segment_width - width_half;
  19174. var y = iz * segment_height - height_half;
  19175. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19176. }
  19177. }
  19178. for ( iz = 0; iz < gridZ; iz ++ ) {
  19179. for ( ix = 0; ix < gridX; ix ++ ) {
  19180. var a = ix + gridX1 * iz;
  19181. var b = ix + gridX1 * ( iz + 1 );
  19182. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19183. var d = ( ix + 1 ) + gridX1 * iz;
  19184. var face = new THREE.Face4( a, b, c, d );
  19185. face.normal.copy( normal );
  19186. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19187. this.faces.push( face );
  19188. this.faceVertexUvs[ 0 ].push( [
  19189. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19190. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19191. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19192. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19193. ] );
  19194. }
  19195. }
  19196. this.computeCentroids();
  19197. };
  19198. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19199. /**
  19200. * @author mrdoob / http://mrdoob.com/
  19201. */
  19202. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19203. THREE.Geometry.call( this );
  19204. this.radius = radius || 50;
  19205. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19206. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19207. phiStart = phiStart !== undefined ? phiStart : 0;
  19208. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19209. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19210. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19211. var x, y, vertices = [], uvs = [];
  19212. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19213. var verticesRow = [];
  19214. var uvsRow = [];
  19215. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19216. var u = x / this.widthSegments;
  19217. var v = y / this.heightSegments;
  19218. var vertex = new THREE.Vector3();
  19219. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19220. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19221. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19222. this.vertices.push( vertex );
  19223. verticesRow.push( this.vertices.length - 1 );
  19224. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19225. }
  19226. vertices.push( verticesRow );
  19227. uvs.push( uvsRow );
  19228. }
  19229. for ( y = 0; y < this.heightSegments; y ++ ) {
  19230. for ( x = 0; x < this.widthSegments; x ++ ) {
  19231. var v1 = vertices[ y ][ x + 1 ];
  19232. var v2 = vertices[ y ][ x ];
  19233. var v3 = vertices[ y + 1 ][ x ];
  19234. var v4 = vertices[ y + 1 ][ x + 1 ];
  19235. var n1 = this.vertices[ v1 ].clone().normalize();
  19236. var n2 = this.vertices[ v2 ].clone().normalize();
  19237. var n3 = this.vertices[ v3 ].clone().normalize();
  19238. var n4 = this.vertices[ v4 ].clone().normalize();
  19239. var uv1 = uvs[ y ][ x + 1 ].clone();
  19240. var uv2 = uvs[ y ][ x ].clone();
  19241. var uv3 = uvs[ y + 1 ][ x ].clone();
  19242. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19243. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19244. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19245. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19246. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19247. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19248. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19249. } else {
  19250. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19251. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19252. }
  19253. }
  19254. }
  19255. this.computeCentroids();
  19256. this.computeFaceNormals();
  19257. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19258. };
  19259. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19260. /**
  19261. * @author zz85 / http://www.lab4games.net/zz85/blog
  19262. * @author alteredq / http://alteredqualia.com/
  19263. *
  19264. * For creating 3D text geometry in three.js
  19265. *
  19266. * Text = 3D Text
  19267. *
  19268. * parameters = {
  19269. * size: <float>, // size of the text
  19270. * height: <float>, // thickness to extrude text
  19271. * curveSegments: <int>, // number of points on the curves
  19272. *
  19273. * font: <string>, // font name
  19274. * weight: <string>, // font weight (normal, bold)
  19275. * style: <string>, // font style (normal, italics)
  19276. *
  19277. * bevelEnabled: <bool>, // turn on bevel
  19278. * bevelThickness: <float>, // how deep into text bevel goes
  19279. * bevelSize: <float>, // how far from text outline is bevel
  19280. * }
  19281. *
  19282. */
  19283. /* Usage Examples
  19284. // TextGeometry wrapper
  19285. var text3d = new TextGeometry( text, options );
  19286. // Complete manner
  19287. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19288. var text3d = new ExtrudeGeometry( textShapes, options );
  19289. */
  19290. THREE.TextGeometry = function ( text, parameters ) {
  19291. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19292. // translate parameters to ExtrudeGeometry API
  19293. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19294. // defaults
  19295. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19296. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19297. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19298. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19299. };
  19300. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19301. /**
  19302. * @author oosmoxiecode
  19303. * @author mrdoob / http://mrdoob.com/
  19304. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19305. */
  19306. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19307. THREE.Geometry.call( this );
  19308. var scope = this;
  19309. this.radius = radius || 100;
  19310. this.tube = tube || 40;
  19311. this.radialSegments = radialSegments || 8;
  19312. this.tubularSegments = tubularSegments || 6;
  19313. this.arc = arc || Math.PI * 2;
  19314. var center = new THREE.Vector3(), uvs = [], normals = [];
  19315. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19316. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19317. var u = i / this.tubularSegments * this.arc;
  19318. var v = j / this.radialSegments * Math.PI * 2;
  19319. center.x = this.radius * Math.cos( u );
  19320. center.y = this.radius * Math.sin( u );
  19321. var vertex = new THREE.Vector3();
  19322. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19323. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19324. vertex.z = this.tube * Math.sin( v );
  19325. this.vertices.push( vertex );
  19326. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19327. normals.push( vertex.clone().sub( center ).normalize() );
  19328. }
  19329. }
  19330. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19331. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19332. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19333. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19334. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19335. var d = ( this.tubularSegments + 1 ) * j + i;
  19336. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19337. face.normal.add( normals[ a ] );
  19338. face.normal.add( normals[ b ] );
  19339. face.normal.add( normals[ c ] );
  19340. face.normal.add( normals[ d ] );
  19341. face.normal.normalize();
  19342. this.faces.push( face );
  19343. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19344. }
  19345. }
  19346. this.computeCentroids();
  19347. };
  19348. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19349. /**
  19350. * @author oosmoxiecode
  19351. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19352. */
  19353. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19354. THREE.Geometry.call( this );
  19355. var scope = this;
  19356. this.radius = radius || 100;
  19357. this.tube = tube || 40;
  19358. this.radialSegments = radialSegments || 64;
  19359. this.tubularSegments = tubularSegments || 8;
  19360. this.p = p || 2;
  19361. this.q = q || 3;
  19362. this.heightScale = heightScale || 1;
  19363. this.grid = new Array( this.radialSegments );
  19364. var tang = new THREE.Vector3();
  19365. var n = new THREE.Vector3();
  19366. var bitan = new THREE.Vector3();
  19367. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19368. this.grid[ i ] = new Array( this.tubularSegments );
  19369. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19370. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19371. var v = j / this.tubularSegments * 2 * Math.PI;
  19372. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19373. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19374. var cx, cy;
  19375. tang.subVectors( p2, p1 );
  19376. n.addVectors( p2, p1 );
  19377. bitan.crossVectors( tang, n );
  19378. n.crossVectors( bitan, tang );
  19379. bitan.normalize();
  19380. n.normalize();
  19381. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19382. cy = this.tube * Math.sin( v );
  19383. p1.x += cx * n.x + cy * bitan.x;
  19384. p1.y += cx * n.y + cy * bitan.y;
  19385. p1.z += cx * n.z + cy * bitan.z;
  19386. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19387. }
  19388. }
  19389. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19390. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19391. var ip = ( i + 1 ) % this.radialSegments;
  19392. var jp = ( j + 1 ) % this.tubularSegments;
  19393. var a = this.grid[ i ][ j ];
  19394. var b = this.grid[ ip ][ j ];
  19395. var c = this.grid[ ip ][ jp ];
  19396. var d = this.grid[ i ][ jp ];
  19397. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19398. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19399. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19400. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19401. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19402. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19403. }
  19404. }
  19405. this.computeCentroids();
  19406. this.computeFaceNormals();
  19407. this.computeVertexNormals();
  19408. function vert( x, y, z ) {
  19409. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19410. }
  19411. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19412. var cu = Math.cos( u );
  19413. var cv = Math.cos( v );
  19414. var su = Math.sin( u );
  19415. var quOverP = in_q / in_p * u;
  19416. var cs = Math.cos( quOverP );
  19417. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19418. var ty = radius * ( 2 + cs ) * su * 0.5;
  19419. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19420. return new THREE.Vector3( tx, ty, tz );
  19421. }
  19422. };
  19423. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19424. /**
  19425. * @author WestLangley / https://github.com/WestLangley
  19426. * @author zz85 / https://github.com/zz85
  19427. * @author miningold / https://github.com/miningold
  19428. *
  19429. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19430. *
  19431. * Creates a tube which extrudes along a 3d spline
  19432. *
  19433. * Uses parallel transport frames as described in
  19434. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19435. */
  19436. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19437. THREE.Geometry.call( this );
  19438. this.path = path;
  19439. this.segments = segments || 64;
  19440. this.radius = radius || 1;
  19441. this.radiusSegments = radiusSegments || 8;
  19442. this.closed = closed || false;
  19443. if ( debug ) this.debug = new THREE.Object3D();
  19444. this.grid = [];
  19445. var scope = this,
  19446. tangent,
  19447. normal,
  19448. binormal,
  19449. numpoints = this.segments + 1,
  19450. x, y, z,
  19451. tx, ty, tz,
  19452. u, v,
  19453. cx, cy,
  19454. pos, pos2 = new THREE.Vector3(),
  19455. i, j,
  19456. ip, jp,
  19457. a, b, c, d,
  19458. uva, uvb, uvc, uvd;
  19459. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19460. tangents = frames.tangents,
  19461. normals = frames.normals,
  19462. binormals = frames.binormals;
  19463. // proxy internals
  19464. this.tangents = tangents;
  19465. this.normals = normals;
  19466. this.binormals = binormals;
  19467. function vert( x, y, z ) {
  19468. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19469. }
  19470. // consruct the grid
  19471. for ( i = 0; i < numpoints; i++ ) {
  19472. this.grid[ i ] = [];
  19473. u = i / ( numpoints - 1 );
  19474. pos = path.getPointAt( u );
  19475. tangent = tangents[ i ];
  19476. normal = normals[ i ];
  19477. binormal = binormals[ i ];
  19478. if ( this.debug ) {
  19479. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19480. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19481. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19482. }
  19483. for ( j = 0; j < this.radiusSegments; j++ ) {
  19484. v = j / this.radiusSegments * 2 * Math.PI;
  19485. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19486. cy = this.radius * Math.sin( v );
  19487. pos2.copy( pos );
  19488. pos2.x += cx * normal.x + cy * binormal.x;
  19489. pos2.y += cx * normal.y + cy * binormal.y;
  19490. pos2.z += cx * normal.z + cy * binormal.z;
  19491. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19492. }
  19493. }
  19494. // construct the mesh
  19495. for ( i = 0; i < this.segments; i++ ) {
  19496. for ( j = 0; j < this.radiusSegments; j++ ) {
  19497. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19498. jp = (j + 1) % this.radiusSegments;
  19499. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19500. b = this.grid[ ip ][ j ];
  19501. c = this.grid[ ip ][ jp ];
  19502. d = this.grid[ i ][ jp ];
  19503. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19504. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19505. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19506. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19507. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19508. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19509. }
  19510. }
  19511. this.computeCentroids();
  19512. this.computeFaceNormals();
  19513. this.computeVertexNormals();
  19514. };
  19515. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19516. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19517. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19518. var tangent = new THREE.Vector3(),
  19519. normal = new THREE.Vector3(),
  19520. binormal = new THREE.Vector3(),
  19521. tangents = [],
  19522. normals = [],
  19523. binormals = [],
  19524. vec = new THREE.Vector3(),
  19525. mat = new THREE.Matrix4(),
  19526. numpoints = segments + 1,
  19527. theta,
  19528. epsilon = 0.0001,
  19529. smallest,
  19530. tx, ty, tz,
  19531. i, u, v;
  19532. // expose internals
  19533. this.tangents = tangents;
  19534. this.normals = normals;
  19535. this.binormals = binormals;
  19536. // compute the tangent vectors for each segment on the path
  19537. for ( i = 0; i < numpoints; i++ ) {
  19538. u = i / ( numpoints - 1 );
  19539. tangents[ i ] = path.getTangentAt( u );
  19540. tangents[ i ].normalize();
  19541. }
  19542. initialNormal3();
  19543. function initialNormal1(lastBinormal) {
  19544. // fixed start binormal. Has dangers of 0 vectors
  19545. normals[ 0 ] = new THREE.Vector3();
  19546. binormals[ 0 ] = new THREE.Vector3();
  19547. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19548. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19549. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19550. }
  19551. function initialNormal2() {
  19552. // This uses the Frenet-Serret formula for deriving binormal
  19553. var t2 = path.getTangentAt( epsilon );
  19554. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19555. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19556. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19557. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19558. }
  19559. function initialNormal3() {
  19560. // select an initial normal vector perpenicular to the first tangent vector,
  19561. // and in the direction of the smallest tangent xyz component
  19562. normals[ 0 ] = new THREE.Vector3();
  19563. binormals[ 0 ] = new THREE.Vector3();
  19564. smallest = Number.MAX_VALUE;
  19565. tx = Math.abs( tangents[ 0 ].x );
  19566. ty = Math.abs( tangents[ 0 ].y );
  19567. tz = Math.abs( tangents[ 0 ].z );
  19568. if ( tx <= smallest ) {
  19569. smallest = tx;
  19570. normal.set( 1, 0, 0 );
  19571. }
  19572. if ( ty <= smallest ) {
  19573. smallest = ty;
  19574. normal.set( 0, 1, 0 );
  19575. }
  19576. if ( tz <= smallest ) {
  19577. normal.set( 0, 0, 1 );
  19578. }
  19579. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19580. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19581. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19582. }
  19583. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19584. for ( i = 1; i < numpoints; i++ ) {
  19585. normals[ i ] = normals[ i-1 ].clone();
  19586. binormals[ i ] = binormals[ i-1 ].clone();
  19587. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19588. if ( vec.length() > epsilon ) {
  19589. vec.normalize();
  19590. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19591. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19592. }
  19593. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19594. }
  19595. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19596. if ( closed ) {
  19597. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19598. theta /= ( numpoints - 1 );
  19599. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19600. theta = -theta;
  19601. }
  19602. for ( i = 1; i < numpoints; i++ ) {
  19603. // twist a little...
  19604. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19605. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19606. }
  19607. }
  19608. };
  19609. /**
  19610. * @author clockworkgeek / https://github.com/clockworkgeek
  19611. * @author timothypratley / https://github.com/timothypratley
  19612. */
  19613. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19614. THREE.Geometry.call( this );
  19615. radius = radius || 1;
  19616. detail = detail || 0;
  19617. var that = this;
  19618. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19619. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19620. }
  19621. var midpoints = [], p = this.vertices;
  19622. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19623. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19624. }
  19625. this.mergeVertices();
  19626. // Apply radius
  19627. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19628. this.vertices[ i ].multiplyScalar( radius );
  19629. }
  19630. // Project vector onto sphere's surface
  19631. function prepare( vector ) {
  19632. var vertex = vector.normalize().clone();
  19633. vertex.index = that.vertices.push( vertex ) - 1;
  19634. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19635. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19636. var v = inclination( vector ) / Math.PI + 0.5;
  19637. vertex.uv = new THREE.Vector2( u, 1 - v );
  19638. return vertex;
  19639. }
  19640. // Approximate a curved face with recursively sub-divided triangles.
  19641. function make( v1, v2, v3, detail ) {
  19642. if ( detail < 1 ) {
  19643. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19644. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19645. face.normal = face.centroid.clone().normalize();
  19646. that.faces.push( face );
  19647. var azi = azimuth( face.centroid );
  19648. that.faceVertexUvs[ 0 ].push( [
  19649. correctUV( v1.uv, v1, azi ),
  19650. correctUV( v2.uv, v2, azi ),
  19651. correctUV( v3.uv, v3, azi )
  19652. ] );
  19653. } else {
  19654. detail -= 1;
  19655. // split triangle into 4 smaller triangles
  19656. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19657. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19658. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19659. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19660. }
  19661. }
  19662. function midpoint( v1, v2 ) {
  19663. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19664. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19665. var mid = midpoints[ v1.index ][ v2.index ];
  19666. if ( mid === undefined ) {
  19667. // generate mean point and project to surface with prepare()
  19668. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19669. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19670. );
  19671. }
  19672. return mid;
  19673. }
  19674. // Angle around the Y axis, counter-clockwise when looking from above.
  19675. function azimuth( vector ) {
  19676. return Math.atan2( vector.z, -vector.x );
  19677. }
  19678. // Angle above the XZ plane.
  19679. function inclination( vector ) {
  19680. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19681. }
  19682. // Texture fixing helper. Spheres have some odd behaviours.
  19683. function correctUV( uv, vector, azimuth ) {
  19684. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19685. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19686. return uv;
  19687. }
  19688. this.computeCentroids();
  19689. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19690. };
  19691. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19692. /**
  19693. * @author timothypratley / https://github.com/timothypratley
  19694. */
  19695. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19696. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19697. var vertices = [
  19698. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19699. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19700. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19701. ];
  19702. var faces = [
  19703. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19704. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19705. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19706. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19707. ];
  19708. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19709. };
  19710. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19711. /**
  19712. * @author timothypratley / https://github.com/timothypratley
  19713. */
  19714. THREE.OctahedronGeometry = function ( radius, detail ) {
  19715. var vertices = [
  19716. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19717. ];
  19718. var faces = [
  19719. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19720. ];
  19721. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19722. };
  19723. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19724. /**
  19725. * @author timothypratley / https://github.com/timothypratley
  19726. */
  19727. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19728. var vertices = [
  19729. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19730. ];
  19731. var faces = [
  19732. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19733. ];
  19734. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19735. };
  19736. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19737. /**
  19738. * @author zz85 / https://github.com/zz85
  19739. * Parametric Surfaces Geometry
  19740. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19741. *
  19742. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19743. *
  19744. */
  19745. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19746. THREE.Geometry.call( this );
  19747. var verts = this.vertices;
  19748. var faces = this.faces;
  19749. var uvs = this.faceVertexUvs[ 0 ];
  19750. useTris = (useTris === undefined) ? false : useTris;
  19751. var i, il, j, p;
  19752. var u, v;
  19753. var stackCount = stacks + 1;
  19754. var sliceCount = slices + 1;
  19755. for ( i = 0; i <= stacks; i ++ ) {
  19756. v = i / stacks;
  19757. for ( j = 0; j <= slices; j ++ ) {
  19758. u = j / slices;
  19759. p = func( u, v );
  19760. verts.push( p );
  19761. }
  19762. }
  19763. var a, b, c, d;
  19764. var uva, uvb, uvc, uvd;
  19765. for ( i = 0; i < stacks; i ++ ) {
  19766. for ( j = 0; j < slices; j ++ ) {
  19767. a = i * sliceCount + j;
  19768. b = i * sliceCount + j + 1;
  19769. c = (i + 1) * sliceCount + j;
  19770. d = (i + 1) * sliceCount + j + 1;
  19771. uva = new THREE.Vector2( j / slices, i / stacks );
  19772. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19773. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19774. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19775. if ( useTris ) {
  19776. faces.push( new THREE.Face3( a, b, c ) );
  19777. faces.push( new THREE.Face3( b, d, c ) );
  19778. uvs.push( [ uva, uvb, uvc ] );
  19779. uvs.push( [ uvb, uvd, uvc ] );
  19780. } else {
  19781. faces.push( new THREE.Face4( a, b, d, c ) );
  19782. uvs.push( [ uva, uvb, uvd, uvc ] );
  19783. }
  19784. }
  19785. }
  19786. // console.log(this);
  19787. // magic bullet
  19788. // var diff = this.mergeVertices();
  19789. // console.log('removed ', diff, ' vertices by merging');
  19790. this.computeCentroids();
  19791. this.computeFaceNormals();
  19792. this.computeVertexNormals();
  19793. };
  19794. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19795. /**
  19796. * @author qiao / https://github.com/qiao
  19797. * @fileoverview This is a convex hull generator using the incremental method.
  19798. * The complexity is O(n^2) where n is the number of vertices.
  19799. * O(nlogn) algorithms do exist, but they are much more complicated.
  19800. *
  19801. * Benchmark:
  19802. *
  19803. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19804. *
  19805. * Num Vertices Time(ms)
  19806. *
  19807. * 10 1
  19808. * 20 3
  19809. * 30 19
  19810. * 40 48
  19811. * 50 107
  19812. */
  19813. THREE.ConvexGeometry = function( vertices ) {
  19814. THREE.Geometry.call( this );
  19815. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19816. for ( var i = 3; i < vertices.length; i++ ) {
  19817. addPoint( i );
  19818. }
  19819. function addPoint( vertexId ) {
  19820. var vertex = vertices[ vertexId ].clone();
  19821. var mag = vertex.length();
  19822. vertex.x += mag * randomOffset();
  19823. vertex.y += mag * randomOffset();
  19824. vertex.z += mag * randomOffset();
  19825. var hole = [];
  19826. for ( var f = 0; f < faces.length; ) {
  19827. var face = faces[ f ];
  19828. // for each face, if the vertex can see it,
  19829. // then we try to add the face's edges into the hole.
  19830. if ( visible( face, vertex ) ) {
  19831. for ( var e = 0; e < 3; e++ ) {
  19832. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19833. var boundary = true;
  19834. // remove duplicated edges.
  19835. for ( var h = 0; h < hole.length; h++ ) {
  19836. if ( equalEdge( hole[ h ], edge ) ) {
  19837. hole[ h ] = hole[ hole.length - 1 ];
  19838. hole.pop();
  19839. boundary = false;
  19840. break;
  19841. }
  19842. }
  19843. if ( boundary ) {
  19844. hole.push( edge );
  19845. }
  19846. }
  19847. // remove faces[ f ]
  19848. faces[ f ] = faces[ faces.length - 1 ];
  19849. faces.pop();
  19850. } else { // not visible
  19851. f++;
  19852. }
  19853. }
  19854. // construct the new faces formed by the edges of the hole and the vertex
  19855. for ( var h = 0; h < hole.length; h++ ) {
  19856. faces.push( [
  19857. hole[ h ][ 0 ],
  19858. hole[ h ][ 1 ],
  19859. vertexId
  19860. ] );
  19861. }
  19862. }
  19863. /**
  19864. * Whether the face is visible from the vertex
  19865. */
  19866. function visible( face, vertex ) {
  19867. var va = vertices[ face[ 0 ] ];
  19868. var vb = vertices[ face[ 1 ] ];
  19869. var vc = vertices[ face[ 2 ] ];
  19870. var n = normal( va, vb, vc );
  19871. // distance from face to origin
  19872. var dist = n.dot( va );
  19873. return n.dot( vertex ) >= dist;
  19874. }
  19875. /**
  19876. * Face normal
  19877. */
  19878. function normal( va, vb, vc ) {
  19879. var cb = new THREE.Vector3();
  19880. var ab = new THREE.Vector3();
  19881. cb.subVectors( vc, vb );
  19882. ab.subVectors( va, vb );
  19883. cb.cross( ab );
  19884. cb.normalize();
  19885. return cb;
  19886. }
  19887. /**
  19888. * Detect whether two edges are equal.
  19889. * Note that when constructing the convex hull, two same edges can only
  19890. * be of the negative direction.
  19891. */
  19892. function equalEdge( ea, eb ) {
  19893. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19894. }
  19895. /**
  19896. * Create a random offset between -1e-6 and 1e-6.
  19897. */
  19898. function randomOffset() {
  19899. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19900. }
  19901. /**
  19902. * XXX: Not sure if this is the correct approach. Need someone to review.
  19903. */
  19904. function vertexUv( vertex ) {
  19905. var mag = vertex.length();
  19906. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19907. }
  19908. // Push vertices into `this.vertices`, skipping those inside the hull
  19909. var id = 0;
  19910. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19911. for ( var i = 0; i < faces.length; i++ ) {
  19912. var face = faces[ i ];
  19913. for ( var j = 0; j < 3; j++ ) {
  19914. if ( newId[ face[ j ] ] === undefined ) {
  19915. newId[ face[ j ] ] = id++;
  19916. this.vertices.push( vertices[ face[ j ] ] );
  19917. }
  19918. face[ j ] = newId[ face[ j ] ];
  19919. }
  19920. }
  19921. // Convert faces into instances of THREE.Face3
  19922. for ( var i = 0; i < faces.length; i++ ) {
  19923. this.faces.push( new THREE.Face3(
  19924. faces[ i ][ 0 ],
  19925. faces[ i ][ 1 ],
  19926. faces[ i ][ 2 ]
  19927. ) );
  19928. }
  19929. // Compute UVs
  19930. for ( var i = 0; i < this.faces.length; i++ ) {
  19931. var face = this.faces[ i ];
  19932. this.faceVertexUvs[ 0 ].push( [
  19933. vertexUv( this.vertices[ face.a ] ),
  19934. vertexUv( this.vertices[ face.b ] ),
  19935. vertexUv( this.vertices[ face.c ])
  19936. ] );
  19937. }
  19938. this.computeCentroids();
  19939. this.computeFaceNormals();
  19940. this.computeVertexNormals();
  19941. };
  19942. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19943. /**
  19944. * @author sroucheray / http://sroucheray.org/
  19945. * @author mrdoob / http://mrdoob.com/
  19946. */
  19947. THREE.AxisHelper = function ( size ) {
  19948. var geometry = new THREE.Geometry();
  19949. geometry.vertices.push(
  19950. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19951. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19952. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19953. );
  19954. geometry.colors.push(
  19955. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19956. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19957. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19958. );
  19959. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19960. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19961. };
  19962. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19963. /**
  19964. * @author WestLangley / http://github.com/WestLangley
  19965. * @author zz85 / https://github.com/zz85
  19966. * @author bhouston / https://exocortex.com
  19967. *
  19968. * Creates an arrow for visualizing directions
  19969. *
  19970. * Parameters:
  19971. * dir - Vector3
  19972. * origin - Vector3
  19973. * length - Number
  19974. * hex - color in hex value
  19975. */
  19976. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19977. THREE.Object3D.call( this );
  19978. if ( length === undefined ) length = 20;
  19979. if ( hex === undefined ) hex = 0xffff00;
  19980. var lineGeometry = new THREE.Geometry();
  19981. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19982. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19983. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19984. this.add( this.line );
  19985. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19986. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19987. this.cone.position.set( 0, 1, 0 );
  19988. this.add( this.cone );
  19989. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19990. this.setDirection( dir );
  19991. this.setLength( length );
  19992. };
  19993. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19994. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19995. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19996. if ( d.y > 0.999 ) {
  19997. this.rotation.set( 0, 0, 0 );
  19998. } else if ( d.y < - 0.999 ) {
  19999. this.rotation.set( Math.PI, 0, 0 );
  20000. } else {
  20001. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  20002. var radians = Math.acos( d.y );
  20003. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  20004. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  20005. }
  20006. };
  20007. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20008. this.scale.set( length, length, length );
  20009. };
  20010. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20011. this.line.material.color.setHex( hex );
  20012. this.cone.material.color.setHex( hex );
  20013. };
  20014. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20015. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20016. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20017. /**
  20018. * @author alteredq / http://alteredqualia.com/
  20019. *
  20020. * - shows frustum, line of sight and up of the camera
  20021. * - suitable for fast updates
  20022. * - based on frustum visualization in lightgl.js shadowmap example
  20023. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20024. */
  20025. THREE.CameraHelper = function ( camera ) {
  20026. THREE.Line.call( this );
  20027. var scope = this;
  20028. this.geometry = new THREE.Geometry();
  20029. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20030. this.type = THREE.LinePieces;
  20031. this.matrixWorld = camera.matrixWorld;
  20032. this.matrixAutoUpdate = false;
  20033. this.pointMap = {};
  20034. // colors
  20035. var hexFrustum = 0xffaa00;
  20036. var hexCone = 0xff0000;
  20037. var hexUp = 0x00aaff;
  20038. var hexTarget = 0xffffff;
  20039. var hexCross = 0x333333;
  20040. // near
  20041. addLine( "n1", "n2", hexFrustum );
  20042. addLine( "n2", "n4", hexFrustum );
  20043. addLine( "n4", "n3", hexFrustum );
  20044. addLine( "n3", "n1", hexFrustum );
  20045. // far
  20046. addLine( "f1", "f2", hexFrustum );
  20047. addLine( "f2", "f4", hexFrustum );
  20048. addLine( "f4", "f3", hexFrustum );
  20049. addLine( "f3", "f1", hexFrustum );
  20050. // sides
  20051. addLine( "n1", "f1", hexFrustum );
  20052. addLine( "n2", "f2", hexFrustum );
  20053. addLine( "n3", "f3", hexFrustum );
  20054. addLine( "n4", "f4", hexFrustum );
  20055. // cone
  20056. addLine( "p", "n1", hexCone );
  20057. addLine( "p", "n2", hexCone );
  20058. addLine( "p", "n3", hexCone );
  20059. addLine( "p", "n4", hexCone );
  20060. // up
  20061. addLine( "u1", "u2", hexUp );
  20062. addLine( "u2", "u3", hexUp );
  20063. addLine( "u3", "u1", hexUp );
  20064. // target
  20065. addLine( "c", "t", hexTarget );
  20066. addLine( "p", "c", hexCross );
  20067. // cross
  20068. addLine( "cn1", "cn2", hexCross );
  20069. addLine( "cn3", "cn4", hexCross );
  20070. addLine( "cf1", "cf2", hexCross );
  20071. addLine( "cf3", "cf4", hexCross );
  20072. this.camera = camera;
  20073. function addLine( a, b, hex ) {
  20074. addPoint( a, hex );
  20075. addPoint( b, hex );
  20076. }
  20077. function addPoint( id, hex ) {
  20078. scope.geometry.vertices.push( new THREE.Vector3() );
  20079. scope.geometry.colors.push( new THREE.Color( hex ) );
  20080. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20081. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20082. }
  20083. this.update( camera );
  20084. };
  20085. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20086. THREE.CameraHelper.prototype.update = function () {
  20087. var scope = this;
  20088. var w = 1, h = 1;
  20089. // we need just camera projection matrix
  20090. // world matrix must be identity
  20091. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20092. // center / target
  20093. setPoint( "c", 0, 0, -1 );
  20094. setPoint( "t", 0, 0, 1 );
  20095. // near
  20096. setPoint( "n1", -w, -h, -1 );
  20097. setPoint( "n2", w, -h, -1 );
  20098. setPoint( "n3", -w, h, -1 );
  20099. setPoint( "n4", w, h, -1 );
  20100. // far
  20101. setPoint( "f1", -w, -h, 1 );
  20102. setPoint( "f2", w, -h, 1 );
  20103. setPoint( "f3", -w, h, 1 );
  20104. setPoint( "f4", w, h, 1 );
  20105. // up
  20106. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20107. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20108. setPoint( "u3", 0, h * 2, -1 );
  20109. // cross
  20110. setPoint( "cf1", -w, 0, 1 );
  20111. setPoint( "cf2", w, 0, 1 );
  20112. setPoint( "cf3", 0, -h, 1 );
  20113. setPoint( "cf4", 0, h, 1 );
  20114. setPoint( "cn1", -w, 0, -1 );
  20115. setPoint( "cn2", w, 0, -1 );
  20116. setPoint( "cn3", 0, -h, -1 );
  20117. setPoint( "cn4", 0, h, -1 );
  20118. function setPoint( point, x, y, z ) {
  20119. THREE.CameraHelper.__v.set( x, y, z );
  20120. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20121. var points = scope.pointMap[ point ];
  20122. if ( points !== undefined ) {
  20123. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20124. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20125. }
  20126. }
  20127. }
  20128. this.geometry.verticesNeedUpdate = true;
  20129. };
  20130. THREE.CameraHelper.__projector = new THREE.Projector();
  20131. THREE.CameraHelper.__v = new THREE.Vector3();
  20132. THREE.CameraHelper.__c = new THREE.Camera();
  20133. /**
  20134. * @author alteredq / http://alteredqualia.com/
  20135. *
  20136. * - shows directional light color, intensity, position, orientation and target
  20137. */
  20138. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20139. THREE.Object3D.call( this );
  20140. this.light = light;
  20141. // position
  20142. this.position = light.position;
  20143. // direction
  20144. this.direction = new THREE.Vector3();
  20145. this.direction.subVectors( light.target.position, light.position );
  20146. // color
  20147. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20148. this.color = light.color.clone();
  20149. this.color.multiplyScalar( intensity );
  20150. var hexColor = this.color.getHex();
  20151. // light helper
  20152. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20153. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20154. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20155. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20156. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20157. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20158. this.add( this.lightSphere );
  20159. this.add( this.lightRays );
  20160. this.lightSphere.properties.isGizmo = true;
  20161. this.lightSphere.properties.gizmoSubject = light;
  20162. this.lightSphere.properties.gizmoRoot = this;
  20163. // light target helper
  20164. this.targetSphere = null;
  20165. if ( light.target.properties.targetInverse !== undefined ) {
  20166. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20167. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20168. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20169. this.targetSphere.position = light.target.position;
  20170. this.targetSphere.properties.isGizmo = true;
  20171. this.targetSphere.properties.gizmoSubject = light.target;
  20172. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20173. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20174. var lineGeometry = new THREE.Geometry();
  20175. lineGeometry.vertices.push( this.position.clone() );
  20176. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20177. lineGeometry.computeLineDistances();
  20178. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20179. this.targetLine.properties.isGizmo = true;
  20180. }
  20181. //
  20182. this.properties.isGizmo = true;
  20183. }
  20184. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20185. THREE.DirectionalLightHelper.prototype.update = function () {
  20186. // update arrow orientation
  20187. // pointing from light to target
  20188. this.direction.subVectors( this.light.target.position, this.light.position );
  20189. // update arrow, spheres, rays and line colors to light color * light intensity
  20190. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20191. this.color.copy( this.light.color );
  20192. this.color.multiplyScalar( intensity );
  20193. this.lightSphere.material.color.copy( this.color );
  20194. this.lightRays.material.color.copy( this.color );
  20195. // Only update targetSphere and targetLine if available
  20196. if ( this.targetSphere !== null ) {
  20197. this.targetSphere.material.color.copy( this.color );
  20198. this.targetLine.material.color.copy( this.color );
  20199. // update target line vertices
  20200. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20201. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20202. this.targetLine.geometry.computeLineDistances();
  20203. this.targetLine.geometry.verticesNeedUpdate = true;
  20204. }
  20205. }
  20206. /**
  20207. * @author alteredq / http://alteredqualia.com/
  20208. *
  20209. * - shows hemisphere light intensity, sky and ground colors and directions
  20210. */
  20211. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20212. THREE.Object3D.call( this );
  20213. this.light = light;
  20214. // position
  20215. this.position = light.position;
  20216. //
  20217. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20218. // sky color
  20219. this.color = light.color.clone();
  20220. this.color.multiplyScalar( intensity );
  20221. var hexColor = this.color.getHex();
  20222. // ground color
  20223. this.groundColor = light.groundColor.clone();
  20224. this.groundColor.multiplyScalar( intensity );
  20225. var hexColorGround = this.groundColor.getHex();
  20226. // double colored light bulb
  20227. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20228. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20229. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20230. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20231. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20232. bulbGeometry.faces[ i ].materialIndex = 0;
  20233. }
  20234. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20235. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20236. }
  20237. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20238. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20239. // arrows for sky and ground light directions
  20240. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20241. this.lightArrow.rotation.x = Math.PI;
  20242. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20243. var joint = new THREE.Object3D();
  20244. joint.rotation.x = -Math.PI * 0.5;
  20245. joint.add( this.lightSphere );
  20246. joint.add( this.lightArrow );
  20247. joint.add( this.lightArrowGround );
  20248. this.add( joint );
  20249. //
  20250. this.lightSphere.properties.isGizmo = true;
  20251. this.lightSphere.properties.gizmoSubject = light;
  20252. this.lightSphere.properties.gizmoRoot = this;
  20253. //
  20254. this.properties.isGizmo = true;
  20255. //
  20256. this.target = new THREE.Vector3();
  20257. this.lookAt( this.target );
  20258. }
  20259. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20260. THREE.HemisphereLightHelper.prototype.update = function () {
  20261. // update sphere sky and ground colors to light color * light intensity
  20262. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20263. this.color.copy( this.light.color );
  20264. this.color.multiplyScalar( intensity );
  20265. this.groundColor.copy( this.light.groundColor );
  20266. this.groundColor.multiplyScalar( intensity );
  20267. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20268. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20269. this.lightArrow.setColor( this.color.getHex() );
  20270. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20271. this.lookAt( this.target );
  20272. }
  20273. /**
  20274. * @author alteredq / http://alteredqualia.com/
  20275. *
  20276. * - shows point light color, intensity, position and distance
  20277. */
  20278. THREE.PointLightHelper = function ( light, sphereSize ) {
  20279. THREE.Object3D.call( this );
  20280. this.light = light;
  20281. // position
  20282. this.position = light.position;
  20283. // color
  20284. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20285. this.color = light.color.clone();
  20286. this.color.multiplyScalar( intensity );
  20287. var hexColor = this.color.getHex();
  20288. // light helper
  20289. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20290. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20291. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20292. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20293. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20294. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20295. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20296. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20297. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20298. var d = light.distance;
  20299. if ( d === 0.0 ) {
  20300. this.lightDistance.visible = false;
  20301. } else {
  20302. this.lightDistance.scale.set( d, d, d );
  20303. }
  20304. this.add( this.lightSphere );
  20305. this.add( this.lightRays );
  20306. this.add( this.lightDistance );
  20307. //
  20308. this.lightSphere.properties.isGizmo = true;
  20309. this.lightSphere.properties.gizmoSubject = light;
  20310. this.lightSphere.properties.gizmoRoot = this;
  20311. //
  20312. this.properties.isGizmo = true;
  20313. }
  20314. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20315. THREE.PointLightHelper.prototype.update = function () {
  20316. // update sphere and rays colors to light color * light intensity
  20317. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20318. this.color.copy( this.light.color );
  20319. this.color.multiplyScalar( intensity );
  20320. this.lightSphere.material.color.copy( this.color );
  20321. this.lightRays.material.color.copy( this.color );
  20322. this.lightDistance.material.color.copy( this.color );
  20323. //
  20324. var d = this.light.distance;
  20325. if ( d === 0.0 ) {
  20326. this.lightDistance.visible = false;
  20327. } else {
  20328. this.lightDistance.visible = true;
  20329. this.lightDistance.scale.set( d, d, d );
  20330. }
  20331. }
  20332. /**
  20333. * @author alteredq / http://alteredqualia.com/
  20334. *
  20335. * - shows spot light color, intensity, position, orientation, light cone and target
  20336. */
  20337. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20338. THREE.Object3D.call( this );
  20339. this.light = light;
  20340. // position
  20341. this.position = light.position;
  20342. // direction
  20343. this.direction = new THREE.Vector3();
  20344. this.direction.subVectors( light.target.position, light.position );
  20345. // color
  20346. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20347. this.color = light.color.clone();
  20348. this.color.multiplyScalar( intensity );
  20349. var hexColor = this.color.getHex();
  20350. // light helper
  20351. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20352. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20353. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20354. var coneMatrix = new THREE.Matrix4();
  20355. coneMatrix.rotateX( -Math.PI/2 );
  20356. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20357. coneGeometry.applyMatrix( coneMatrix );
  20358. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20359. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20360. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20361. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20362. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20363. var coneLength = light.distance ? light.distance : 10000;
  20364. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20365. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20366. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20367. this.gyroscope = new THREE.Gyroscope();
  20368. this.gyroscope.add( this.lightSphere );
  20369. this.gyroscope.add( this.lightRays );
  20370. this.add( this.gyroscope );
  20371. this.add( this.lightCone );
  20372. this.lookAt( light.target.position );
  20373. this.lightSphere.properties.isGizmo = true;
  20374. this.lightSphere.properties.gizmoSubject = light;
  20375. this.lightSphere.properties.gizmoRoot = this;
  20376. // light target helper
  20377. this.targetSphere = null;
  20378. if ( light.target.properties.targetInverse !== undefined ) {
  20379. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20380. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20381. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20382. this.targetSphere.position = light.target.position;
  20383. this.targetSphere.properties.isGizmo = true;
  20384. this.targetSphere.properties.gizmoSubject = light.target;
  20385. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20386. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20387. var lineGeometry = new THREE.Geometry();
  20388. lineGeometry.vertices.push( this.position.clone() );
  20389. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20390. lineGeometry.computeLineDistances();
  20391. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20392. this.targetLine.properties.isGizmo = true;
  20393. }
  20394. //
  20395. this.properties.isGizmo = true;
  20396. }
  20397. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20398. THREE.SpotLightHelper.prototype.update = function () {
  20399. // update arrow orientation
  20400. // pointing from light to target
  20401. this.direction.subVectors( this.light.target.position, this.light.position );
  20402. // update light cone orientation and size
  20403. this.lookAt( this.light.target.position );
  20404. var coneLength = this.light.distance ? this.light.distance : 10000;
  20405. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20406. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20407. // update arrow, spheres, rays and line colors to light color * light intensity
  20408. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20409. this.color.copy( this.light.color );
  20410. this.color.multiplyScalar( intensity );
  20411. this.lightSphere.material.color.copy( this.color );
  20412. this.lightRays.material.color.copy( this.color );
  20413. this.lightCone.material.color.copy( this.color );
  20414. // Only update targetSphere and targetLine if available
  20415. if ( this.targetSphere !== null ) {
  20416. this.targetSphere.material.color.copy( this.color );
  20417. this.targetLine.material.color.copy( this.color );
  20418. // update target line vertices
  20419. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20420. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20421. this.targetLine.geometry.computeLineDistances();
  20422. this.targetLine.geometry.verticesNeedUpdate = true;
  20423. }
  20424. };
  20425. /**
  20426. * @author alteredq / http://alteredqualia.com/
  20427. */
  20428. THREE.ImmediateRenderObject = function () {
  20429. THREE.Object3D.call( this );
  20430. this.render = function ( renderCallback ) { };
  20431. };
  20432. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20433. /**
  20434. * @author mikael emtinger / http://gomo.se/
  20435. * @author alteredq / http://alteredqualia.com/
  20436. */
  20437. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20438. THREE.Object3D.call( this );
  20439. this.lensFlares = [];
  20440. this.positionScreen = new THREE.Vector3();
  20441. this.customUpdateCallback = undefined;
  20442. if( texture !== undefined ) {
  20443. this.add( texture, size, distance, blending, color );
  20444. }
  20445. };
  20446. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20447. /*
  20448. * Add: adds another flare
  20449. */
  20450. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20451. if( size === undefined ) size = -1;
  20452. if( distance === undefined ) distance = 0;
  20453. if( opacity === undefined ) opacity = 1;
  20454. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20455. if( blending === undefined ) blending = THREE.NormalBlending;
  20456. distance = Math.min( distance, Math.max( 0, distance ) );
  20457. this.lensFlares.push( { texture: texture, // THREE.Texture
  20458. size: size, // size in pixels (-1 = use texture.width)
  20459. distance: distance, // distance (0-1) from light source (0=at light source)
  20460. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20461. scale: 1, // scale
  20462. rotation: 1, // rotation
  20463. opacity: opacity, // opacity
  20464. color: color, // color
  20465. blending: blending } ); // blending
  20466. };
  20467. /*
  20468. * Update lens flares update positions on all flares based on the screen position
  20469. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20470. */
  20471. THREE.LensFlare.prototype.updateLensFlares = function () {
  20472. var f, fl = this.lensFlares.length;
  20473. var flare;
  20474. var vecX = -this.positionScreen.x * 2;
  20475. var vecY = -this.positionScreen.y * 2;
  20476. for( f = 0; f < fl; f ++ ) {
  20477. flare = this.lensFlares[ f ];
  20478. flare.x = this.positionScreen.x + vecX * flare.distance;
  20479. flare.y = this.positionScreen.y + vecY * flare.distance;
  20480. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20481. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20482. }
  20483. };
  20484. /**
  20485. * @author alteredq / http://alteredqualia.com/
  20486. */
  20487. THREE.MorphBlendMesh = function( geometry, material ) {
  20488. THREE.Mesh.call( this, geometry, material );
  20489. this.animationsMap = {};
  20490. this.animationsList = [];
  20491. // prepare default animation
  20492. // (all frames played together in 1 second)
  20493. var numFrames = this.geometry.morphTargets.length;
  20494. var name = "__default";
  20495. var startFrame = 0;
  20496. var endFrame = numFrames - 1;
  20497. var fps = numFrames / 1;
  20498. this.createAnimation( name, startFrame, endFrame, fps );
  20499. this.setAnimationWeight( name, 1 );
  20500. };
  20501. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20502. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20503. var animation = {
  20504. startFrame: start,
  20505. endFrame: end,
  20506. length: end - start + 1,
  20507. fps: fps,
  20508. duration: ( end - start ) / fps,
  20509. lastFrame: 0,
  20510. currentFrame: 0,
  20511. active: false,
  20512. time: 0,
  20513. direction: 1,
  20514. weight: 1,
  20515. directionBackwards: false,
  20516. mirroredLoop: false
  20517. };
  20518. this.animationsMap[ name ] = animation;
  20519. this.animationsList.push( animation );
  20520. };
  20521. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20522. var pattern = /([a-z]+)(\d+)/;
  20523. var firstAnimation, frameRanges = {};
  20524. var geometry = this.geometry;
  20525. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20526. var morph = geometry.morphTargets[ i ];
  20527. var chunks = morph.name.match( pattern );
  20528. if ( chunks && chunks.length > 1 ) {
  20529. var name = chunks[ 1 ];
  20530. var num = chunks[ 2 ];
  20531. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20532. var range = frameRanges[ name ];
  20533. if ( i < range.start ) range.start = i;
  20534. if ( i > range.end ) range.end = i;
  20535. if ( ! firstAnimation ) firstAnimation = name;
  20536. }
  20537. }
  20538. for ( var name in frameRanges ) {
  20539. var range = frameRanges[ name ];
  20540. this.createAnimation( name, range.start, range.end, fps );
  20541. }
  20542. this.firstAnimation = firstAnimation;
  20543. };
  20544. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20545. var animation = this.animationsMap[ name ];
  20546. if ( animation ) {
  20547. animation.direction = 1;
  20548. animation.directionBackwards = false;
  20549. }
  20550. };
  20551. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20552. var animation = this.animationsMap[ name ];
  20553. if ( animation ) {
  20554. animation.direction = -1;
  20555. animation.directionBackwards = true;
  20556. }
  20557. };
  20558. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20559. var animation = this.animationsMap[ name ];
  20560. if ( animation ) {
  20561. animation.fps = fps;
  20562. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20563. }
  20564. };
  20565. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20566. var animation = this.animationsMap[ name ];
  20567. if ( animation ) {
  20568. animation.duration = duration;
  20569. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20570. }
  20571. };
  20572. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20573. var animation = this.animationsMap[ name ];
  20574. if ( animation ) {
  20575. animation.weight = weight;
  20576. }
  20577. };
  20578. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20579. var animation = this.animationsMap[ name ];
  20580. if ( animation ) {
  20581. animation.time = time;
  20582. }
  20583. };
  20584. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20585. var time = 0;
  20586. var animation = this.animationsMap[ name ];
  20587. if ( animation ) {
  20588. time = animation.time;
  20589. }
  20590. return time;
  20591. };
  20592. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20593. var duration = -1;
  20594. var animation = this.animationsMap[ name ];
  20595. if ( animation ) {
  20596. duration = animation.duration;
  20597. }
  20598. return duration;
  20599. };
  20600. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20601. var animation = this.animationsMap[ name ];
  20602. if ( animation ) {
  20603. animation.time = 0;
  20604. animation.active = true;
  20605. } else {
  20606. console.warn( "animation[" + name + "] undefined" );
  20607. }
  20608. };
  20609. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20610. var animation = this.animationsMap[ name ];
  20611. if ( animation ) {
  20612. animation.active = false;
  20613. }
  20614. };
  20615. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20616. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20617. var animation = this.animationsList[ i ];
  20618. if ( ! animation.active ) continue;
  20619. var frameTime = animation.duration / animation.length;
  20620. animation.time += animation.direction * delta;
  20621. if ( animation.mirroredLoop ) {
  20622. if ( animation.time > animation.duration || animation.time < 0 ) {
  20623. animation.direction *= -1;
  20624. if ( animation.time > animation.duration ) {
  20625. animation.time = animation.duration;
  20626. animation.directionBackwards = true;
  20627. }
  20628. if ( animation.time < 0 ) {
  20629. animation.time = 0;
  20630. animation.directionBackwards = false;
  20631. }
  20632. }
  20633. } else {
  20634. animation.time = animation.time % animation.duration;
  20635. if ( animation.time < 0 ) animation.time += animation.duration;
  20636. }
  20637. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20638. var weight = animation.weight;
  20639. if ( keyframe !== animation.currentFrame ) {
  20640. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20641. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20642. this.morphTargetInfluences[ keyframe ] = 0;
  20643. animation.lastFrame = animation.currentFrame;
  20644. animation.currentFrame = keyframe;
  20645. }
  20646. var mix = ( animation.time % frameTime ) / frameTime;
  20647. if ( animation.directionBackwards ) mix = 1 - mix;
  20648. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20649. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20650. }
  20651. };
  20652. /**
  20653. * @author mikael emtinger / http://gomo.se/
  20654. * @author alteredq / http://alteredqualia.com/
  20655. */
  20656. THREE.LensFlarePlugin = function () {
  20657. var _gl, _renderer, _precision, _lensFlare = {};
  20658. this.init = function ( renderer ) {
  20659. _gl = renderer.context;
  20660. _renderer = renderer;
  20661. _precision = renderer.getPrecision();
  20662. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20663. _lensFlare.faces = new Uint16Array( 6 );
  20664. var i = 0;
  20665. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20666. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20667. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20668. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20669. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20670. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20671. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20672. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20673. i = 0;
  20674. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20675. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20676. // buffers
  20677. _lensFlare.vertexBuffer = _gl.createBuffer();
  20678. _lensFlare.elementBuffer = _gl.createBuffer();
  20679. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20680. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20681. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20682. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20683. // textures
  20684. _lensFlare.tempTexture = _gl.createTexture();
  20685. _lensFlare.occlusionTexture = _gl.createTexture();
  20686. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20687. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20688. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20689. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20690. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20691. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20692. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20693. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20694. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20695. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20696. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20697. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20698. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20699. _lensFlare.hasVertexTexture = false;
  20700. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20701. } else {
  20702. _lensFlare.hasVertexTexture = true;
  20703. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20704. }
  20705. _lensFlare.attributes = {};
  20706. _lensFlare.uniforms = {};
  20707. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20708. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20709. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20710. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20711. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20712. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20713. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20714. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20715. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20716. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20717. };
  20718. /*
  20719. * Render lens flares
  20720. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20721. * reads these back and calculates occlusion.
  20722. * Then _lensFlare.update_lensFlares() is called to re-position and
  20723. * update transparency of flares. Then they are rendered.
  20724. *
  20725. */
  20726. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20727. var flares = scene.__webglFlares,
  20728. nFlares = flares.length;
  20729. if ( ! nFlares ) return;
  20730. var tempPosition = new THREE.Vector3();
  20731. var invAspect = viewportHeight / viewportWidth,
  20732. halfViewportWidth = viewportWidth * 0.5,
  20733. halfViewportHeight = viewportHeight * 0.5;
  20734. var size = 16 / viewportHeight,
  20735. scale = new THREE.Vector2( size * invAspect, size );
  20736. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20737. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20738. var uniforms = _lensFlare.uniforms,
  20739. attributes = _lensFlare.attributes;
  20740. // set _lensFlare program and reset blending
  20741. _gl.useProgram( _lensFlare.program );
  20742. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20743. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20744. // loop through all lens flares to update their occlusion and positions
  20745. // setup gl and common used attribs/unforms
  20746. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20747. _gl.uniform1i( uniforms.map, 1 );
  20748. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20749. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20750. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20751. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20752. _gl.disable( _gl.CULL_FACE );
  20753. _gl.depthMask( false );
  20754. var i, j, jl, flare, sprite;
  20755. for ( i = 0; i < nFlares; i ++ ) {
  20756. size = 16 / viewportHeight;
  20757. scale.set( size * invAspect, size );
  20758. // calc object screen position
  20759. flare = flares[ i ];
  20760. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20761. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20762. tempPosition.applyProjection( camera.projectionMatrix );
  20763. // setup arrays for gl programs
  20764. screenPosition.copy( tempPosition )
  20765. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20766. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20767. // screen cull
  20768. if ( _lensFlare.hasVertexTexture || (
  20769. screenPositionPixels.x > 0 &&
  20770. screenPositionPixels.x < viewportWidth &&
  20771. screenPositionPixels.y > 0 &&
  20772. screenPositionPixels.y < viewportHeight ) ) {
  20773. // save current RGB to temp texture
  20774. _gl.activeTexture( _gl.TEXTURE1 );
  20775. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20776. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20777. // render pink quad
  20778. _gl.uniform1i( uniforms.renderType, 0 );
  20779. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20780. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20781. _gl.disable( _gl.BLEND );
  20782. _gl.enable( _gl.DEPTH_TEST );
  20783. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20784. // copy result to occlusionMap
  20785. _gl.activeTexture( _gl.TEXTURE0 );
  20786. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20787. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20788. // restore graphics
  20789. _gl.uniform1i( uniforms.renderType, 1 );
  20790. _gl.disable( _gl.DEPTH_TEST );
  20791. _gl.activeTexture( _gl.TEXTURE1 );
  20792. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20793. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20794. // update object positions
  20795. flare.positionScreen.copy( screenPosition )
  20796. if ( flare.customUpdateCallback ) {
  20797. flare.customUpdateCallback( flare );
  20798. } else {
  20799. flare.updateLensFlares();
  20800. }
  20801. // render flares
  20802. _gl.uniform1i( uniforms.renderType, 2 );
  20803. _gl.enable( _gl.BLEND );
  20804. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20805. sprite = flare.lensFlares[ j ];
  20806. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20807. screenPosition.x = sprite.x;
  20808. screenPosition.y = sprite.y;
  20809. screenPosition.z = sprite.z;
  20810. size = sprite.size * sprite.scale / viewportHeight;
  20811. scale.x = size * invAspect;
  20812. scale.y = size;
  20813. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20814. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20815. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20816. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20817. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20818. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20819. _renderer.setTexture( sprite.texture, 1 );
  20820. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20821. }
  20822. }
  20823. }
  20824. }
  20825. // restore gl
  20826. _gl.enable( _gl.CULL_FACE );
  20827. _gl.enable( _gl.DEPTH_TEST );
  20828. _gl.depthMask( true );
  20829. };
  20830. function createProgram ( shader, precision ) {
  20831. var program = _gl.createProgram();
  20832. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20833. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20834. var prefix = "precision " + precision + " float;\n";
  20835. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20836. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20837. _gl.compileShader( fragmentShader );
  20838. _gl.compileShader( vertexShader );
  20839. _gl.attachShader( program, fragmentShader );
  20840. _gl.attachShader( program, vertexShader );
  20841. _gl.linkProgram( program );
  20842. return program;
  20843. };
  20844. };
  20845. /**
  20846. * @author alteredq / http://alteredqualia.com/
  20847. */
  20848. THREE.ShadowMapPlugin = function () {
  20849. var _gl,
  20850. _renderer,
  20851. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20852. _frustum = new THREE.Frustum(),
  20853. _projScreenMatrix = new THREE.Matrix4(),
  20854. _min = new THREE.Vector3(),
  20855. _max = new THREE.Vector3(),
  20856. _matrixPosition = new THREE.Vector3();
  20857. this.init = function ( renderer ) {
  20858. _gl = renderer.context;
  20859. _renderer = renderer;
  20860. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20861. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20862. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20863. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20864. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20865. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20866. _depthMaterial._shadowPass = true;
  20867. _depthMaterialMorph._shadowPass = true;
  20868. _depthMaterialSkin._shadowPass = true;
  20869. _depthMaterialMorphSkin._shadowPass = true;
  20870. };
  20871. this.render = function ( scene, camera ) {
  20872. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20873. this.update( scene, camera );
  20874. };
  20875. this.update = function ( scene, camera ) {
  20876. var i, il, j, jl, n,
  20877. shadowMap, shadowMatrix, shadowCamera,
  20878. program, buffer, material,
  20879. webglObject, object, light,
  20880. renderList,
  20881. lights = [],
  20882. k = 0,
  20883. fog = null;
  20884. // set GL state for depth map
  20885. _gl.clearColor( 1, 1, 1, 1 );
  20886. _gl.disable( _gl.BLEND );
  20887. _gl.enable( _gl.CULL_FACE );
  20888. _gl.frontFace( _gl.CCW );
  20889. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20890. _gl.cullFace( _gl.FRONT );
  20891. } else {
  20892. _gl.cullFace( _gl.BACK );
  20893. }
  20894. _renderer.setDepthTest( true );
  20895. // preprocess lights
  20896. // - skip lights that are not casting shadows
  20897. // - create virtual lights for cascaded shadow maps
  20898. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20899. light = scene.__lights[ i ];
  20900. if ( ! light.castShadow ) continue;
  20901. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20902. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20903. var virtualLight;
  20904. if ( ! light.shadowCascadeArray[ n ] ) {
  20905. virtualLight = createVirtualLight( light, n );
  20906. virtualLight.originalCamera = camera;
  20907. var gyro = new THREE.Gyroscope();
  20908. gyro.position = light.shadowCascadeOffset;
  20909. gyro.add( virtualLight );
  20910. gyro.add( virtualLight.target );
  20911. camera.add( gyro );
  20912. light.shadowCascadeArray[ n ] = virtualLight;
  20913. console.log( "Created virtualLight", virtualLight );
  20914. } else {
  20915. virtualLight = light.shadowCascadeArray[ n ];
  20916. }
  20917. updateVirtualLight( light, n );
  20918. lights[ k ] = virtualLight;
  20919. k ++;
  20920. }
  20921. } else {
  20922. lights[ k ] = light;
  20923. k ++;
  20924. }
  20925. }
  20926. // render depth map
  20927. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20928. light = lights[ i ];
  20929. if ( ! light.shadowMap ) {
  20930. var shadowFilter = THREE.LinearFilter;
  20931. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20932. shadowFilter = THREE.NearestFilter;
  20933. }
  20934. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20935. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20936. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20937. light.shadowMatrix = new THREE.Matrix4();
  20938. }
  20939. if ( ! light.shadowCamera ) {
  20940. if ( light instanceof THREE.SpotLight ) {
  20941. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20942. } else if ( light instanceof THREE.DirectionalLight ) {
  20943. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20944. } else {
  20945. console.error( "Unsupported light type for shadow" );
  20946. continue;
  20947. }
  20948. scene.add( light.shadowCamera );
  20949. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20950. }
  20951. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20952. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20953. light.shadowCamera.add( light.cameraHelper );
  20954. }
  20955. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20956. updateShadowCamera( camera, light );
  20957. }
  20958. shadowMap = light.shadowMap;
  20959. shadowMatrix = light.shadowMatrix;
  20960. shadowCamera = light.shadowCamera;
  20961. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  20962. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  20963. shadowCamera.lookAt( _matrixPosition );
  20964. shadowCamera.updateMatrixWorld();
  20965. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20966. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20967. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20968. // compute shadow matrix
  20969. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20970. 0.0, 0.5, 0.0, 0.5,
  20971. 0.0, 0.0, 0.5, 0.5,
  20972. 0.0, 0.0, 0.0, 1.0 );
  20973. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20974. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20975. // update camera matrices and frustum
  20976. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20977. _frustum.setFromMatrix( _projScreenMatrix );
  20978. // render shadow map
  20979. _renderer.setRenderTarget( shadowMap );
  20980. _renderer.clear();
  20981. // set object matrices & frustum culling
  20982. renderList = scene.__webglObjects;
  20983. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20984. webglObject = renderList[ j ];
  20985. object = webglObject.object;
  20986. webglObject.render = false;
  20987. if ( object.visible && object.castShadow ) {
  20988. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20989. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20990. webglObject.render = true;
  20991. }
  20992. }
  20993. }
  20994. // render regular objects
  20995. var objectMaterial, useMorphing, useSkinning;
  20996. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20997. webglObject = renderList[ j ];
  20998. if ( webglObject.render ) {
  20999. object = webglObject.object;
  21000. buffer = webglObject.buffer;
  21001. // culling is overriden globally for all objects
  21002. // while rendering depth map
  21003. // need to deal with MeshFaceMaterial somehow
  21004. // in that case just use the first of material.materials for now
  21005. // (proper solution would require to break objects by materials
  21006. // similarly to regular rendering and then set corresponding
  21007. // depth materials per each chunk instead of just once per object)
  21008. objectMaterial = getObjectMaterial( object );
  21009. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21010. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21011. if ( object.customDepthMaterial ) {
  21012. material = object.customDepthMaterial;
  21013. } else if ( useSkinning ) {
  21014. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21015. } else if ( useMorphing ) {
  21016. material = _depthMaterialMorph;
  21017. } else {
  21018. material = _depthMaterial;
  21019. }
  21020. if ( buffer instanceof THREE.BufferGeometry ) {
  21021. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21022. } else {
  21023. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21024. }
  21025. }
  21026. }
  21027. // set matrices and render immediate objects
  21028. renderList = scene.__webglObjectsImmediate;
  21029. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21030. webglObject = renderList[ j ];
  21031. object = webglObject.object;
  21032. if ( object.visible && object.castShadow ) {
  21033. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21034. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21035. }
  21036. }
  21037. }
  21038. // restore GL state
  21039. var clearColor = _renderer.getClearColor(),
  21040. clearAlpha = _renderer.getClearAlpha();
  21041. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21042. _gl.enable( _gl.BLEND );
  21043. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21044. _gl.cullFace( _gl.BACK );
  21045. }
  21046. };
  21047. function createVirtualLight( light, cascade ) {
  21048. var virtualLight = new THREE.DirectionalLight();
  21049. virtualLight.isVirtual = true;
  21050. virtualLight.onlyShadow = true;
  21051. virtualLight.castShadow = true;
  21052. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21053. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21054. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21055. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21056. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21057. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21058. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21059. virtualLight.shadowDarkness = light.shadowDarkness;
  21060. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21061. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21062. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21063. virtualLight.pointsWorld = [];
  21064. virtualLight.pointsFrustum = [];
  21065. var pointsWorld = virtualLight.pointsWorld,
  21066. pointsFrustum = virtualLight.pointsFrustum;
  21067. for ( var i = 0; i < 8; i ++ ) {
  21068. pointsWorld[ i ] = new THREE.Vector3();
  21069. pointsFrustum[ i ] = new THREE.Vector3();
  21070. }
  21071. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21072. var farZ = light.shadowCascadeFarZ[ cascade ];
  21073. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21074. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21075. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21076. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21077. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21078. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21079. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21080. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21081. return virtualLight;
  21082. }
  21083. // Synchronize virtual light with the original light
  21084. function updateVirtualLight( light, cascade ) {
  21085. var virtualLight = light.shadowCascadeArray[ cascade ];
  21086. virtualLight.position.copy( light.position );
  21087. virtualLight.target.position.copy( light.target.position );
  21088. virtualLight.lookAt( virtualLight.target );
  21089. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21090. virtualLight.shadowDarkness = light.shadowDarkness;
  21091. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21092. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21093. var farZ = light.shadowCascadeFarZ[ cascade ];
  21094. var pointsFrustum = virtualLight.pointsFrustum;
  21095. pointsFrustum[ 0 ].z = nearZ;
  21096. pointsFrustum[ 1 ].z = nearZ;
  21097. pointsFrustum[ 2 ].z = nearZ;
  21098. pointsFrustum[ 3 ].z = nearZ;
  21099. pointsFrustum[ 4 ].z = farZ;
  21100. pointsFrustum[ 5 ].z = farZ;
  21101. pointsFrustum[ 6 ].z = farZ;
  21102. pointsFrustum[ 7 ].z = farZ;
  21103. }
  21104. // Fit shadow camera's ortho frustum to camera frustum
  21105. function updateShadowCamera( camera, light ) {
  21106. var shadowCamera = light.shadowCamera,
  21107. pointsFrustum = light.pointsFrustum,
  21108. pointsWorld = light.pointsWorld;
  21109. _min.set( Infinity, Infinity, Infinity );
  21110. _max.set( -Infinity, -Infinity, -Infinity );
  21111. for ( var i = 0; i < 8; i ++ ) {
  21112. var p = pointsWorld[ i ];
  21113. p.copy( pointsFrustum[ i ] );
  21114. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21115. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21116. if ( p.x < _min.x ) _min.x = p.x;
  21117. if ( p.x > _max.x ) _max.x = p.x;
  21118. if ( p.y < _min.y ) _min.y = p.y;
  21119. if ( p.y > _max.y ) _max.y = p.y;
  21120. if ( p.z < _min.z ) _min.z = p.z;
  21121. if ( p.z > _max.z ) _max.z = p.z;
  21122. }
  21123. shadowCamera.left = _min.x;
  21124. shadowCamera.right = _max.x;
  21125. shadowCamera.top = _max.y;
  21126. shadowCamera.bottom = _min.y;
  21127. // can't really fit near/far
  21128. //shadowCamera.near = _min.z;
  21129. //shadowCamera.far = _max.z;
  21130. shadowCamera.updateProjectionMatrix();
  21131. }
  21132. // For the moment just ignore objects that have multiple materials with different animation methods
  21133. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21134. function getObjectMaterial( object ) {
  21135. return object.material instanceof THREE.MeshFaceMaterial
  21136. ? object.material.materials[ 0 ]
  21137. : object.material;
  21138. };
  21139. };
  21140. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21141. /**
  21142. * @author mikael emtinger / http://gomo.se/
  21143. * @author alteredq / http://alteredqualia.com/
  21144. */
  21145. THREE.SpritePlugin = function () {
  21146. var _gl, _renderer, _precision, _sprite = {};
  21147. this.init = function ( renderer ) {
  21148. _gl = renderer.context;
  21149. _renderer = renderer;
  21150. _precision = renderer.getPrecision();
  21151. _sprite.vertices = new Float32Array( 8 + 8 );
  21152. _sprite.faces = new Uint16Array( 6 );
  21153. var i = 0;
  21154. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21155. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21156. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21157. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21158. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21159. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21160. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21161. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21162. i = 0;
  21163. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21164. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21165. _sprite.vertexBuffer = _gl.createBuffer();
  21166. _sprite.elementBuffer = _gl.createBuffer();
  21167. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21168. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21169. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21170. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21171. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21172. _sprite.attributes = {};
  21173. _sprite.uniforms = {};
  21174. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21175. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21176. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21177. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21178. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21179. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21180. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21181. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21182. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21183. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21184. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21185. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21186. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21187. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21188. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21189. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21190. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21191. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21192. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21193. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21194. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21195. };
  21196. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21197. var sprites = scene.__webglSprites,
  21198. nSprites = sprites.length;
  21199. if ( ! nSprites ) return;
  21200. var attributes = _sprite.attributes,
  21201. uniforms = _sprite.uniforms;
  21202. var invAspect = viewportHeight / viewportWidth;
  21203. var halfViewportWidth = viewportWidth * 0.5,
  21204. halfViewportHeight = viewportHeight * 0.5;
  21205. // setup gl
  21206. _gl.useProgram( _sprite.program );
  21207. _gl.enableVertexAttribArray( attributes.position );
  21208. _gl.enableVertexAttribArray( attributes.uv );
  21209. _gl.disable( _gl.CULL_FACE );
  21210. _gl.enable( _gl.BLEND );
  21211. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21212. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21213. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21214. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21215. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21216. _gl.activeTexture( _gl.TEXTURE0 );
  21217. _gl.uniform1i( uniforms.map, 0 );
  21218. var oldFogType = 0;
  21219. var sceneFogType = 0;
  21220. var fog = scene.fog;
  21221. if ( fog ) {
  21222. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21223. if ( fog instanceof THREE.Fog ) {
  21224. _gl.uniform1f( uniforms.fogNear, fog.near );
  21225. _gl.uniform1f( uniforms.fogFar, fog.far );
  21226. _gl.uniform1i( uniforms.fogType, 1 );
  21227. oldFogType = 1;
  21228. sceneFogType = 1;
  21229. } else if ( fog instanceof THREE.FogExp2 ) {
  21230. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21231. _gl.uniform1i( uniforms.fogType, 2 );
  21232. oldFogType = 2;
  21233. sceneFogType = 2;
  21234. }
  21235. } else {
  21236. _gl.uniform1i( uniforms.fogType, 0 );
  21237. oldFogType = 0;
  21238. sceneFogType = 0;
  21239. }
  21240. // update positions and sort
  21241. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21242. for( i = 0; i < nSprites; i ++ ) {
  21243. sprite = sprites[ i ];
  21244. material = sprite.material;
  21245. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21246. if ( ! material.useScreenCoordinates ) {
  21247. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21248. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21249. } else {
  21250. sprite.z = - sprite.position.z;
  21251. }
  21252. }
  21253. sprites.sort( painterSortStable );
  21254. // render all sprites
  21255. for( i = 0; i < nSprites; i ++ ) {
  21256. sprite = sprites[ i ];
  21257. material = sprite.material;
  21258. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21259. if ( material.map && material.map.image && material.map.image.width ) {
  21260. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21261. if ( material.useScreenCoordinates === true ) {
  21262. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21263. _gl.uniform3f(
  21264. uniforms.screenPosition,
  21265. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21266. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21267. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21268. );
  21269. scale[ 0 ] = _renderer.devicePixelRatio;
  21270. scale[ 1 ] = _renderer.devicePixelRatio;
  21271. } else {
  21272. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21273. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21274. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21275. scale[ 0 ] = 1;
  21276. scale[ 1 ] = 1;
  21277. }
  21278. if ( scene.fog && material.fog ) {
  21279. fogType = sceneFogType;
  21280. } else {
  21281. fogType = 0;
  21282. }
  21283. if ( oldFogType !== fogType ) {
  21284. _gl.uniform1i( uniforms.fogType, fogType );
  21285. oldFogType = fogType;
  21286. }
  21287. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21288. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21289. scale[ 1 ] *= size * sprite.scale.y;
  21290. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21291. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21292. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21293. _gl.uniform1f( uniforms.opacity, material.opacity );
  21294. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21295. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21296. _gl.uniform2fv( uniforms.scale, scale );
  21297. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21298. _renderer.setDepthTest( material.depthTest );
  21299. _renderer.setDepthWrite( material.depthWrite );
  21300. _renderer.setTexture( material.map, 0 );
  21301. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21302. }
  21303. }
  21304. // restore gl
  21305. _gl.enable( _gl.CULL_FACE );
  21306. };
  21307. function createProgram ( shader, precision ) {
  21308. var program = _gl.createProgram();
  21309. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21310. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21311. var prefix = "precision " + precision + " float;\n";
  21312. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21313. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21314. _gl.compileShader( fragmentShader );
  21315. _gl.compileShader( vertexShader );
  21316. _gl.attachShader( program, fragmentShader );
  21317. _gl.attachShader( program, vertexShader );
  21318. _gl.linkProgram( program );
  21319. return program;
  21320. };
  21321. function painterSortStable ( a, b ) {
  21322. if ( a.z !== b.z ) {
  21323. return b.z - a.z;
  21324. } else {
  21325. return b.id - a.id;
  21326. }
  21327. };
  21328. };
  21329. /**
  21330. * @author alteredq / http://alteredqualia.com/
  21331. */
  21332. THREE.DepthPassPlugin = function () {
  21333. this.enabled = false;
  21334. this.renderTarget = null;
  21335. var _gl,
  21336. _renderer,
  21337. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21338. _frustum = new THREE.Frustum(),
  21339. _projScreenMatrix = new THREE.Matrix4();
  21340. this.init = function ( renderer ) {
  21341. _gl = renderer.context;
  21342. _renderer = renderer;
  21343. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21344. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21345. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21346. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21347. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21348. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21349. _depthMaterial._shadowPass = true;
  21350. _depthMaterialMorph._shadowPass = true;
  21351. _depthMaterialSkin._shadowPass = true;
  21352. _depthMaterialMorphSkin._shadowPass = true;
  21353. };
  21354. this.render = function ( scene, camera ) {
  21355. if ( ! this.enabled ) return;
  21356. this.update( scene, camera );
  21357. };
  21358. this.update = function ( scene, camera ) {
  21359. var i, il, j, jl, n,
  21360. program, buffer, material,
  21361. webglObject, object, light,
  21362. renderList,
  21363. fog = null;
  21364. // set GL state for depth map
  21365. _gl.clearColor( 1, 1, 1, 1 );
  21366. _gl.disable( _gl.BLEND );
  21367. _renderer.setDepthTest( true );
  21368. // update scene
  21369. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21370. // update camera matrices and frustum
  21371. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21372. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21373. _frustum.setFromMatrix( _projScreenMatrix );
  21374. // render depth map
  21375. _renderer.setRenderTarget( this.renderTarget );
  21376. _renderer.clear();
  21377. // set object matrices & frustum culling
  21378. renderList = scene.__webglObjects;
  21379. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21380. webglObject = renderList[ j ];
  21381. object = webglObject.object;
  21382. webglObject.render = false;
  21383. if ( object.visible ) {
  21384. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21385. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21386. webglObject.render = true;
  21387. }
  21388. }
  21389. }
  21390. // render regular objects
  21391. var objectMaterial, useMorphing, useSkinning;
  21392. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21393. webglObject = renderList[ j ];
  21394. if ( webglObject.render ) {
  21395. object = webglObject.object;
  21396. buffer = webglObject.buffer;
  21397. // todo: create proper depth material for particles
  21398. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21399. objectMaterial = getObjectMaterial( object );
  21400. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21401. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21402. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21403. if ( object.customDepthMaterial ) {
  21404. material = object.customDepthMaterial;
  21405. } else if ( useSkinning ) {
  21406. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21407. } else if ( useMorphing ) {
  21408. material = _depthMaterialMorph;
  21409. } else {
  21410. material = _depthMaterial;
  21411. }
  21412. if ( buffer instanceof THREE.BufferGeometry ) {
  21413. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21414. } else {
  21415. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21416. }
  21417. }
  21418. }
  21419. // set matrices and render immediate objects
  21420. renderList = scene.__webglObjectsImmediate;
  21421. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21422. webglObject = renderList[ j ];
  21423. object = webglObject.object;
  21424. if ( object.visible ) {
  21425. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21426. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21427. }
  21428. }
  21429. // restore GL state
  21430. var clearColor = _renderer.getClearColor(),
  21431. clearAlpha = _renderer.getClearAlpha();
  21432. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21433. _gl.enable( _gl.BLEND );
  21434. };
  21435. // For the moment just ignore objects that have multiple materials with different animation methods
  21436. // Only the first material will be taken into account for deciding which depth material to use
  21437. function getObjectMaterial( object ) {
  21438. return object.material instanceof THREE.MeshFaceMaterial
  21439. ? object.material.materials[ 0 ]
  21440. : object.material;
  21441. };
  21442. };
  21443. /**
  21444. * @author mikael emtinger / http://gomo.se/
  21445. *
  21446. */
  21447. THREE.ShaderFlares = {
  21448. 'lensFlareVertexTexture': {
  21449. vertexShader: [
  21450. "uniform lowp int renderType;",
  21451. "uniform vec3 screenPosition;",
  21452. "uniform vec2 scale;",
  21453. "uniform float rotation;",
  21454. "uniform sampler2D occlusionMap;",
  21455. "attribute vec2 position;",
  21456. "attribute vec2 uv;",
  21457. "varying vec2 vUV;",
  21458. "varying float vVisibility;",
  21459. "void main() {",
  21460. "vUV = uv;",
  21461. "vec2 pos = position;",
  21462. "if( renderType == 2 ) {",
  21463. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21464. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21465. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21466. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21467. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21468. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21469. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21470. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21471. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21472. "vVisibility = ( visibility.r / 9.0 ) *",
  21473. "( 1.0 - visibility.g / 9.0 ) *",
  21474. "( visibility.b / 9.0 ) *",
  21475. "( 1.0 - visibility.a / 9.0 );",
  21476. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21477. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21478. "}",
  21479. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21480. "}"
  21481. ].join( "\n" ),
  21482. fragmentShader: [
  21483. "uniform lowp int renderType;",
  21484. "uniform sampler2D map;",
  21485. "uniform float opacity;",
  21486. "uniform vec3 color;",
  21487. "varying vec2 vUV;",
  21488. "varying float vVisibility;",
  21489. "void main() {",
  21490. // pink square
  21491. "if( renderType == 0 ) {",
  21492. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21493. // restore
  21494. "} else if( renderType == 1 ) {",
  21495. "gl_FragColor = texture2D( map, vUV );",
  21496. // flare
  21497. "} else {",
  21498. "vec4 texture = texture2D( map, vUV );",
  21499. "texture.a *= opacity * vVisibility;",
  21500. "gl_FragColor = texture;",
  21501. "gl_FragColor.rgb *= color;",
  21502. "}",
  21503. "}"
  21504. ].join( "\n" )
  21505. },
  21506. 'lensFlare': {
  21507. vertexShader: [
  21508. "uniform lowp int renderType;",
  21509. "uniform vec3 screenPosition;",
  21510. "uniform vec2 scale;",
  21511. "uniform float rotation;",
  21512. "attribute vec2 position;",
  21513. "attribute vec2 uv;",
  21514. "varying vec2 vUV;",
  21515. "void main() {",
  21516. "vUV = uv;",
  21517. "vec2 pos = position;",
  21518. "if( renderType == 2 ) {",
  21519. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21520. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21521. "}",
  21522. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21523. "}"
  21524. ].join( "\n" ),
  21525. fragmentShader: [
  21526. "precision mediump float;",
  21527. "uniform lowp int renderType;",
  21528. "uniform sampler2D map;",
  21529. "uniform sampler2D occlusionMap;",
  21530. "uniform float opacity;",
  21531. "uniform vec3 color;",
  21532. "varying vec2 vUV;",
  21533. "void main() {",
  21534. // pink square
  21535. "if( renderType == 0 ) {",
  21536. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21537. // restore
  21538. "} else if( renderType == 1 ) {",
  21539. "gl_FragColor = texture2D( map, vUV );",
  21540. // flare
  21541. "} else {",
  21542. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21543. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21544. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21545. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21546. "visibility = ( 1.0 - visibility / 4.0 );",
  21547. "vec4 texture = texture2D( map, vUV );",
  21548. "texture.a *= opacity * visibility;",
  21549. "gl_FragColor = texture;",
  21550. "gl_FragColor.rgb *= color;",
  21551. "}",
  21552. "}"
  21553. ].join( "\n" )
  21554. }
  21555. };
  21556. /**
  21557. * @author mikael emtinger / http://gomo.se/
  21558. * @author alteredq / http://alteredqualia.com/
  21559. *
  21560. */
  21561. THREE.ShaderSprite = {
  21562. 'sprite': {
  21563. vertexShader: [
  21564. "uniform int useScreenCoordinates;",
  21565. "uniform int sizeAttenuation;",
  21566. "uniform vec3 screenPosition;",
  21567. "uniform mat4 modelViewMatrix;",
  21568. "uniform mat4 projectionMatrix;",
  21569. "uniform float rotation;",
  21570. "uniform vec2 scale;",
  21571. "uniform vec2 alignment;",
  21572. "uniform vec2 uvOffset;",
  21573. "uniform vec2 uvScale;",
  21574. "attribute vec2 position;",
  21575. "attribute vec2 uv;",
  21576. "varying vec2 vUV;",
  21577. "void main() {",
  21578. "vUV = uvOffset + uv * uvScale;",
  21579. "vec2 alignedPosition = position + alignment;",
  21580. "vec2 rotatedPosition;",
  21581. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21582. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21583. "vec4 finalPosition;",
  21584. "if( useScreenCoordinates != 0 ) {",
  21585. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21586. "} else {",
  21587. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21588. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21589. "}",
  21590. "gl_Position = finalPosition;",
  21591. "}"
  21592. ].join( "\n" ),
  21593. fragmentShader: [
  21594. "uniform vec3 color;",
  21595. "uniform sampler2D map;",
  21596. "uniform float opacity;",
  21597. "uniform int fogType;",
  21598. "uniform vec3 fogColor;",
  21599. "uniform float fogDensity;",
  21600. "uniform float fogNear;",
  21601. "uniform float fogFar;",
  21602. "uniform float alphaTest;",
  21603. "varying vec2 vUV;",
  21604. "void main() {",
  21605. "vec4 texture = texture2D( map, vUV );",
  21606. "if ( texture.a < alphaTest ) discard;",
  21607. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21608. "if ( fogType > 0 ) {",
  21609. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21610. "float fogFactor = 0.0;",
  21611. "if ( fogType == 1 ) {",
  21612. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21613. "} else {",
  21614. "const float LOG2 = 1.442695;",
  21615. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21616. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21617. "}",
  21618. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21619. "}",
  21620. "}"
  21621. ].join( "\n" )
  21622. }
  21623. };
粤ICP备19079148号