three.js 794 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var THREE = { REVISION: '68dev' };
  5. // browserify support
  6. if ( typeof module === 'object' ) {
  7. module.exports = THREE;
  8. }
  9. // GL STATE CONSTANTS
  10. THREE.CullFaceNone = 0;
  11. THREE.CullFaceBack = 1;
  12. THREE.CullFaceFront = 2;
  13. THREE.CullFaceFrontBack = 3;
  14. THREE.FrontFaceDirectionCW = 0;
  15. THREE.FrontFaceDirectionCCW = 1;
  16. // SHADOWING TYPES
  17. THREE.BasicShadowMap = 0;
  18. THREE.PCFShadowMap = 1;
  19. THREE.PCFSoftShadowMap = 2;
  20. // MATERIAL CONSTANTS
  21. // side
  22. THREE.FrontSide = 0;
  23. THREE.BackSide = 1;
  24. THREE.DoubleSide = 2;
  25. // shading
  26. THREE.NoShading = 0;
  27. THREE.FlatShading = 1;
  28. THREE.SmoothShading = 2;
  29. // colors
  30. THREE.NoColors = 0;
  31. THREE.FaceColors = 1;
  32. THREE.VertexColors = 2;
  33. // blending modes
  34. THREE.NoBlending = 0;
  35. THREE.NormalBlending = 1;
  36. THREE.AdditiveBlending = 2;
  37. THREE.SubtractiveBlending = 3;
  38. THREE.MultiplyBlending = 4;
  39. THREE.CustomBlending = 5;
  40. // custom blending equations
  41. // (numbers start from 100 not to clash with other
  42. // mappings to OpenGL constants defined in Texture.js)
  43. THREE.AddEquation = 100;
  44. THREE.SubtractEquation = 101;
  45. THREE.ReverseSubtractEquation = 102;
  46. // custom blending destination factors
  47. THREE.ZeroFactor = 200;
  48. THREE.OneFactor = 201;
  49. THREE.SrcColorFactor = 202;
  50. THREE.OneMinusSrcColorFactor = 203;
  51. THREE.SrcAlphaFactor = 204;
  52. THREE.OneMinusSrcAlphaFactor = 205;
  53. THREE.DstAlphaFactor = 206;
  54. THREE.OneMinusDstAlphaFactor = 207;
  55. // custom blending source factors
  56. //THREE.ZeroFactor = 200;
  57. //THREE.OneFactor = 201;
  58. //THREE.SrcAlphaFactor = 204;
  59. //THREE.OneMinusSrcAlphaFactor = 205;
  60. //THREE.DstAlphaFactor = 206;
  61. //THREE.OneMinusDstAlphaFactor = 207;
  62. THREE.DstColorFactor = 208;
  63. THREE.OneMinusDstColorFactor = 209;
  64. THREE.SrcAlphaSaturateFactor = 210;
  65. // TEXTURE CONSTANTS
  66. THREE.MultiplyOperation = 0;
  67. THREE.MixOperation = 1;
  68. THREE.AddOperation = 2;
  69. // Mapping modes
  70. THREE.UVMapping = function () {};
  71. THREE.CubeReflectionMapping = function () {};
  72. THREE.CubeRefractionMapping = function () {};
  73. THREE.SphericalReflectionMapping = function () {};
  74. THREE.SphericalRefractionMapping = function () {};
  75. // Wrapping modes
  76. THREE.RepeatWrapping = 1000;
  77. THREE.ClampToEdgeWrapping = 1001;
  78. THREE.MirroredRepeatWrapping = 1002;
  79. // Filters
  80. THREE.NearestFilter = 1003;
  81. THREE.NearestMipMapNearestFilter = 1004;
  82. THREE.NearestMipMapLinearFilter = 1005;
  83. THREE.LinearFilter = 1006;
  84. THREE.LinearMipMapNearestFilter = 1007;
  85. THREE.LinearMipMapLinearFilter = 1008;
  86. // Data types
  87. THREE.UnsignedByteType = 1009;
  88. THREE.ByteType = 1010;
  89. THREE.ShortType = 1011;
  90. THREE.UnsignedShortType = 1012;
  91. THREE.IntType = 1013;
  92. THREE.UnsignedIntType = 1014;
  93. THREE.FloatType = 1015;
  94. // Pixel types
  95. //THREE.UnsignedByteType = 1009;
  96. THREE.UnsignedShort4444Type = 1016;
  97. THREE.UnsignedShort5551Type = 1017;
  98. THREE.UnsignedShort565Type = 1018;
  99. // Pixel formats
  100. THREE.AlphaFormat = 1019;
  101. THREE.RGBFormat = 1020;
  102. THREE.RGBAFormat = 1021;
  103. THREE.LuminanceFormat = 1022;
  104. THREE.LuminanceAlphaFormat = 1023;
  105. // Compressed texture formats
  106. THREE.RGB_S3TC_DXT1_Format = 2001;
  107. THREE.RGBA_S3TC_DXT1_Format = 2002;
  108. THREE.RGBA_S3TC_DXT3_Format = 2003;
  109. THREE.RGBA_S3TC_DXT5_Format = 2004;
  110. /*
  111. // Potential future PVRTC compressed texture formats
  112. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  113. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  114. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  115. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  116. */
  117. /**
  118. * @author mrdoob / http://mrdoob.com/
  119. */
  120. THREE.Color = function ( color ) {
  121. if ( arguments.length === 3 ) {
  122. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  123. }
  124. return this.set( color )
  125. };
  126. THREE.Color.prototype = {
  127. constructor: THREE.Color,
  128. r: 1, g: 1, b: 1,
  129. set: function ( value ) {
  130. if ( value instanceof THREE.Color ) {
  131. this.copy( value );
  132. } else if ( typeof value === 'number' ) {
  133. this.setHex( value );
  134. } else if ( typeof value === 'string' ) {
  135. this.setStyle( value );
  136. }
  137. return this;
  138. },
  139. setHex: function ( hex ) {
  140. hex = Math.floor( hex );
  141. this.r = ( hex >> 16 & 255 ) / 255;
  142. this.g = ( hex >> 8 & 255 ) / 255;
  143. this.b = ( hex & 255 ) / 255;
  144. return this;
  145. },
  146. setRGB: function ( r, g, b ) {
  147. this.r = r;
  148. this.g = g;
  149. this.b = b;
  150. return this;
  151. },
  152. setHSL: function ( h, s, l ) {
  153. // h,s,l ranges are in 0.0 - 1.0
  154. if ( s === 0 ) {
  155. this.r = this.g = this.b = l;
  156. } else {
  157. var hue2rgb = function ( p, q, t ) {
  158. if ( t < 0 ) t += 1;
  159. if ( t > 1 ) t -= 1;
  160. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  161. if ( t < 1 / 2 ) return q;
  162. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  163. return p;
  164. };
  165. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  166. var q = ( 2 * l ) - p;
  167. this.r = hue2rgb( q, p, h + 1 / 3 );
  168. this.g = hue2rgb( q, p, h );
  169. this.b = hue2rgb( q, p, h - 1 / 3 );
  170. }
  171. return this;
  172. },
  173. setStyle: function ( style ) {
  174. // rgb(255,0,0)
  175. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  176. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  177. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  178. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  179. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  180. return this;
  181. }
  182. // rgb(100%,0%,0%)
  183. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  184. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  185. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  186. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  187. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  188. return this;
  189. }
  190. // #ff0000
  191. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  192. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  193. this.setHex( parseInt( color[ 1 ], 16 ) );
  194. return this;
  195. }
  196. // #f00
  197. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  198. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  199. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  200. return this;
  201. }
  202. // red
  203. if ( /^(\w+)$/i.test( style ) ) {
  204. this.setHex( THREE.ColorKeywords[ style ] );
  205. return this;
  206. }
  207. },
  208. copy: function ( color ) {
  209. this.r = color.r;
  210. this.g = color.g;
  211. this.b = color.b;
  212. return this;
  213. },
  214. copyGammaToLinear: function ( color ) {
  215. this.r = color.r * color.r;
  216. this.g = color.g * color.g;
  217. this.b = color.b * color.b;
  218. return this;
  219. },
  220. copyLinearToGamma: function ( color ) {
  221. this.r = Math.sqrt( color.r );
  222. this.g = Math.sqrt( color.g );
  223. this.b = Math.sqrt( color.b );
  224. return this;
  225. },
  226. convertGammaToLinear: function () {
  227. var r = this.r, g = this.g, b = this.b;
  228. this.r = r * r;
  229. this.g = g * g;
  230. this.b = b * b;
  231. return this;
  232. },
  233. convertLinearToGamma: function () {
  234. this.r = Math.sqrt( this.r );
  235. this.g = Math.sqrt( this.g );
  236. this.b = Math.sqrt( this.b );
  237. return this;
  238. },
  239. getHex: function () {
  240. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  241. },
  242. getHexString: function () {
  243. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  244. },
  245. getHSL: function ( optionalTarget ) {
  246. // h,s,l ranges are in 0.0 - 1.0
  247. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  248. var r = this.r, g = this.g, b = this.b;
  249. var max = Math.max( r, g, b );
  250. var min = Math.min( r, g, b );
  251. var hue, saturation;
  252. var lightness = ( min + max ) / 2.0;
  253. if ( min === max ) {
  254. hue = 0;
  255. saturation = 0;
  256. } else {
  257. var delta = max - min;
  258. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  259. switch ( max ) {
  260. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  261. case g: hue = ( b - r ) / delta + 2; break;
  262. case b: hue = ( r - g ) / delta + 4; break;
  263. }
  264. hue /= 6;
  265. }
  266. hsl.h = hue;
  267. hsl.s = saturation;
  268. hsl.l = lightness;
  269. return hsl;
  270. },
  271. getStyle: function () {
  272. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  273. },
  274. offsetHSL: function ( h, s, l ) {
  275. var hsl = this.getHSL();
  276. hsl.h += h; hsl.s += s; hsl.l += l;
  277. this.setHSL( hsl.h, hsl.s, hsl.l );
  278. return this;
  279. },
  280. add: function ( color ) {
  281. this.r += color.r;
  282. this.g += color.g;
  283. this.b += color.b;
  284. return this;
  285. },
  286. addColors: function ( color1, color2 ) {
  287. this.r = color1.r + color2.r;
  288. this.g = color1.g + color2.g;
  289. this.b = color1.b + color2.b;
  290. return this;
  291. },
  292. addScalar: function ( s ) {
  293. this.r += s;
  294. this.g += s;
  295. this.b += s;
  296. return this;
  297. },
  298. multiply: function ( color ) {
  299. this.r *= color.r;
  300. this.g *= color.g;
  301. this.b *= color.b;
  302. return this;
  303. },
  304. multiplyScalar: function ( s ) {
  305. this.r *= s;
  306. this.g *= s;
  307. this.b *= s;
  308. return this;
  309. },
  310. lerp: function ( color, alpha ) {
  311. this.r += ( color.r - this.r ) * alpha;
  312. this.g += ( color.g - this.g ) * alpha;
  313. this.b += ( color.b - this.b ) * alpha;
  314. return this;
  315. },
  316. equals: function ( c ) {
  317. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  318. },
  319. fromArray: function ( array ) {
  320. this.r = array[ 0 ];
  321. this.g = array[ 1 ];
  322. this.b = array[ 2 ];
  323. return this;
  324. },
  325. toArray: function () {
  326. return [ this.r, this.g, this.b ];
  327. },
  328. clone: function () {
  329. return new THREE.Color().setRGB( this.r, this.g, this.b );
  330. }
  331. };
  332. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  333. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  334. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  335. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  336. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  337. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  338. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  339. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  340. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  341. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  342. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  343. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  344. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  345. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  346. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  347. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  348. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  349. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  350. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  351. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  352. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  353. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  354. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  355. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  356. /**
  357. * @author mikael emtinger / http://gomo.se/
  358. * @author alteredq / http://alteredqualia.com/
  359. * @author WestLangley / http://github.com/WestLangley
  360. * @author bhouston / http://exocortex.com
  361. */
  362. THREE.Quaternion = function ( x, y, z, w ) {
  363. this._x = x || 0;
  364. this._y = y || 0;
  365. this._z = z || 0;
  366. this._w = ( w !== undefined ) ? w : 1;
  367. };
  368. THREE.Quaternion.prototype = {
  369. constructor: THREE.Quaternion,
  370. _x: 0,_y: 0, _z: 0, _w: 0,
  371. get x () {
  372. return this._x;
  373. },
  374. set x ( value ) {
  375. this._x = value;
  376. this.onChangeCallback();
  377. },
  378. get y () {
  379. return this._y;
  380. },
  381. set y ( value ) {
  382. this._y = value;
  383. this.onChangeCallback();
  384. },
  385. get z () {
  386. return this._z;
  387. },
  388. set z ( value ) {
  389. this._z = value;
  390. this.onChangeCallback();
  391. },
  392. get w () {
  393. return this._w;
  394. },
  395. set w ( value ) {
  396. this._w = value;
  397. this.onChangeCallback();
  398. },
  399. set: function ( x, y, z, w ) {
  400. this._x = x;
  401. this._y = y;
  402. this._z = z;
  403. this._w = w;
  404. this.onChangeCallback();
  405. return this;
  406. },
  407. copy: function ( quaternion ) {
  408. this._x = quaternion._x;
  409. this._y = quaternion._y;
  410. this._z = quaternion._z;
  411. this._w = quaternion._w;
  412. this.onChangeCallback();
  413. return this;
  414. },
  415. setFromEuler: function ( euler, update ) {
  416. if ( euler instanceof THREE.Euler === false ) {
  417. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  418. }
  419. // http://www.mathworks.com/matlabcentral/fileexchange/
  420. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  421. // content/SpinCalc.m
  422. var c1 = Math.cos( euler._x / 2 );
  423. var c2 = Math.cos( euler._y / 2 );
  424. var c3 = Math.cos( euler._z / 2 );
  425. var s1 = Math.sin( euler._x / 2 );
  426. var s2 = Math.sin( euler._y / 2 );
  427. var s3 = Math.sin( euler._z / 2 );
  428. if ( euler.order === 'XYZ' ) {
  429. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  430. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  431. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  432. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  433. } else if ( euler.order === 'YXZ' ) {
  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 ( euler.order === 'ZXY' ) {
  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 ( euler.order === 'ZYX' ) {
  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 ( euler.order === 'YZX' ) {
  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 ( euler.order === 'XZY' ) {
  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. }
  459. if ( update !== false ) this.onChangeCallback();
  460. return this;
  461. },
  462. setFromAxisAngle: function ( axis, angle ) {
  463. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  464. // assumes axis is normalized
  465. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  466. this._x = axis.x * s;
  467. this._y = axis.y * s;
  468. this._z = axis.z * s;
  469. this._w = Math.cos( halfAngle );
  470. this.onChangeCallback();
  471. return this;
  472. },
  473. setFromRotationMatrix: function ( m ) {
  474. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  475. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  476. var te = m.elements,
  477. m11 = te[0], m12 = te[4], m13 = te[8],
  478. m21 = te[1], m22 = te[5], m23 = te[9],
  479. m31 = te[2], m32 = te[6], m33 = te[10],
  480. trace = m11 + m22 + m33,
  481. s;
  482. if ( trace > 0 ) {
  483. s = 0.5 / Math.sqrt( trace + 1.0 );
  484. this._w = 0.25 / s;
  485. this._x = ( m32 - m23 ) * s;
  486. this._y = ( m13 - m31 ) * s;
  487. this._z = ( m21 - m12 ) * s;
  488. } else if ( m11 > m22 && m11 > m33 ) {
  489. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  490. this._w = (m32 - m23 ) / s;
  491. this._x = 0.25 * s;
  492. this._y = (m12 + m21 ) / s;
  493. this._z = (m13 + m31 ) / s;
  494. } else if ( m22 > m33 ) {
  495. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  496. this._w = (m13 - m31 ) / s;
  497. this._x = (m12 + m21 ) / s;
  498. this._y = 0.25 * s;
  499. this._z = (m23 + m32 ) / s;
  500. } else {
  501. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  502. this._w = ( m21 - m12 ) / s;
  503. this._x = ( m13 + m31 ) / s;
  504. this._y = ( m23 + m32 ) / s;
  505. this._z = 0.25 * s;
  506. }
  507. this.onChangeCallback();
  508. return this;
  509. },
  510. setFromUnitVectors: function () {
  511. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  512. // assumes direction vectors vFrom and vTo are normalized
  513. var v1, r;
  514. var EPS = 0.000001;
  515. return function( vFrom, vTo ) {
  516. if ( v1 === undefined ) v1 = new THREE.Vector3();
  517. r = vFrom.dot( vTo ) + 1;
  518. if ( r < EPS ) {
  519. r = 0;
  520. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  521. v1.set( - vFrom.y, vFrom.x, 0 );
  522. } else {
  523. v1.set( 0, - vFrom.z, vFrom.y );
  524. }
  525. } else {
  526. v1.crossVectors( vFrom, vTo );
  527. }
  528. this._x = v1.x;
  529. this._y = v1.y;
  530. this._z = v1.z;
  531. this._w = r;
  532. this.normalize();
  533. return this;
  534. }
  535. }(),
  536. inverse: function () {
  537. this.conjugate().normalize();
  538. return this;
  539. },
  540. conjugate: function () {
  541. this._x *= -1;
  542. this._y *= -1;
  543. this._z *= -1;
  544. this.onChangeCallback();
  545. return this;
  546. },
  547. lengthSq: function () {
  548. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  549. },
  550. length: function () {
  551. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  552. },
  553. normalize: function () {
  554. var l = this.length();
  555. if ( l === 0 ) {
  556. this._x = 0;
  557. this._y = 0;
  558. this._z = 0;
  559. this._w = 1;
  560. } else {
  561. l = 1 / l;
  562. this._x = this._x * l;
  563. this._y = this._y * l;
  564. this._z = this._z * l;
  565. this._w = this._w * l;
  566. }
  567. this.onChangeCallback();
  568. return this;
  569. },
  570. multiply: function ( q, p ) {
  571. if ( p !== undefined ) {
  572. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  573. return this.multiplyQuaternions( q, p );
  574. }
  575. return this.multiplyQuaternions( this, q );
  576. },
  577. multiplyQuaternions: function ( a, b ) {
  578. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  579. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  580. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  581. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  582. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  583. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  584. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  585. this.onChangeCallback();
  586. return this;
  587. },
  588. multiplyVector3: function ( vector ) {
  589. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  590. return vector.applyQuaternion( this );
  591. },
  592. slerp: function ( qb, t ) {
  593. var x = this._x, y = this._y, z = this._z, w = this._w;
  594. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  595. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  596. if ( cosHalfTheta < 0 ) {
  597. this._w = -qb._w;
  598. this._x = -qb._x;
  599. this._y = -qb._y;
  600. this._z = -qb._z;
  601. cosHalfTheta = -cosHalfTheta;
  602. } else {
  603. this.copy( qb );
  604. }
  605. if ( cosHalfTheta >= 1.0 ) {
  606. this._w = w;
  607. this._x = x;
  608. this._y = y;
  609. this._z = z;
  610. return this;
  611. }
  612. var halfTheta = Math.acos( cosHalfTheta );
  613. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  614. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  615. this._w = 0.5 * ( w + this._w );
  616. this._x = 0.5 * ( x + this._x );
  617. this._y = 0.5 * ( y + this._y );
  618. this._z = 0.5 * ( z + this._z );
  619. return this;
  620. }
  621. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  622. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  623. this._w = ( w * ratioA + this._w * ratioB );
  624. this._x = ( x * ratioA + this._x * ratioB );
  625. this._y = ( y * ratioA + this._y * ratioB );
  626. this._z = ( z * ratioA + this._z * ratioB );
  627. this.onChangeCallback();
  628. return this;
  629. },
  630. equals: function ( quaternion ) {
  631. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  632. },
  633. fromArray: function ( array ) {
  634. this._x = array[ 0 ];
  635. this._y = array[ 1 ];
  636. this._z = array[ 2 ];
  637. this._w = array[ 3 ];
  638. this.onChangeCallback();
  639. return this;
  640. },
  641. toArray: function () {
  642. return [ this._x, this._y, this._z, this._w ];
  643. },
  644. onChange: function ( callback ) {
  645. this.onChangeCallback = callback;
  646. return this;
  647. },
  648. onChangeCallback: function () {},
  649. clone: function () {
  650. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  651. }
  652. };
  653. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  654. return qm.copy( qa ).slerp( qb, t );
  655. }
  656. /**
  657. * @author mrdoob / http://mrdoob.com/
  658. * @author philogb / http://blog.thejit.org/
  659. * @author egraether / http://egraether.com/
  660. * @author zz85 / http://www.lab4games.net/zz85/blog
  661. */
  662. THREE.Vector2 = function ( x, y ) {
  663. this.x = x || 0;
  664. this.y = y || 0;
  665. };
  666. THREE.Vector2.prototype = {
  667. constructor: THREE.Vector2,
  668. set: function ( x, y ) {
  669. this.x = x;
  670. this.y = y;
  671. return this;
  672. },
  673. setX: function ( x ) {
  674. this.x = x;
  675. return this;
  676. },
  677. setY: function ( y ) {
  678. this.y = y;
  679. return this;
  680. },
  681. setComponent: function ( index, value ) {
  682. switch ( index ) {
  683. case 0: this.x = value; break;
  684. case 1: this.y = value; break;
  685. default: throw new Error( "index is out of range: " + index );
  686. }
  687. },
  688. getComponent: function ( index ) {
  689. switch ( index ) {
  690. case 0: return this.x;
  691. case 1: return this.y;
  692. default: throw new Error( "index is out of range: " + index );
  693. }
  694. },
  695. copy: function ( v ) {
  696. this.x = v.x;
  697. this.y = v.y;
  698. return this;
  699. },
  700. add: function ( v, w ) {
  701. if ( w !== undefined ) {
  702. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  703. return this.addVectors( v, w );
  704. }
  705. this.x += v.x;
  706. this.y += v.y;
  707. return this;
  708. },
  709. addVectors: function ( a, b ) {
  710. this.x = a.x + b.x;
  711. this.y = a.y + b.y;
  712. return this;
  713. },
  714. addScalar: function ( s ) {
  715. this.x += s;
  716. this.y += s;
  717. return this;
  718. },
  719. sub: function ( v, w ) {
  720. if ( w !== undefined ) {
  721. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  722. return this.subVectors( v, w );
  723. }
  724. this.x -= v.x;
  725. this.y -= v.y;
  726. return this;
  727. },
  728. subVectors: function ( a, b ) {
  729. this.x = a.x - b.x;
  730. this.y = a.y - b.y;
  731. return this;
  732. },
  733. multiply: function ( v ) {
  734. this.x *= v.x;
  735. this.y *= v.y;
  736. return this;
  737. },
  738. multiplyScalar: function ( s ) {
  739. this.x *= s;
  740. this.y *= s;
  741. return this;
  742. },
  743. divide: function ( v ) {
  744. this.x /= v.x;
  745. this.y /= v.y;
  746. return this;
  747. },
  748. divideScalar: function ( scalar ) {
  749. if ( scalar !== 0 ) {
  750. var invScalar = 1 / scalar;
  751. this.x *= invScalar;
  752. this.y *= invScalar;
  753. } else {
  754. this.x = 0;
  755. this.y = 0;
  756. }
  757. return this;
  758. },
  759. min: function ( v ) {
  760. if ( this.x > v.x ) {
  761. this.x = v.x;
  762. }
  763. if ( this.y > v.y ) {
  764. this.y = v.y;
  765. }
  766. return this;
  767. },
  768. max: function ( v ) {
  769. if ( this.x < v.x ) {
  770. this.x = v.x;
  771. }
  772. if ( this.y < v.y ) {
  773. this.y = v.y;
  774. }
  775. return this;
  776. },
  777. clamp: function ( min, max ) {
  778. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  779. if ( this.x < min.x ) {
  780. this.x = min.x;
  781. } else if ( this.x > max.x ) {
  782. this.x = max.x;
  783. }
  784. if ( this.y < min.y ) {
  785. this.y = min.y;
  786. } else if ( this.y > max.y ) {
  787. this.y = max.y;
  788. }
  789. return this;
  790. },
  791. clampScalar: ( function () {
  792. var min, max;
  793. return function ( minVal, maxVal ) {
  794. if ( min === undefined ) {
  795. min = new THREE.Vector2();
  796. max = new THREE.Vector2();
  797. }
  798. min.set( minVal, minVal );
  799. max.set( maxVal, maxVal );
  800. return this.clamp( min, max );
  801. };
  802. } )(),
  803. floor: function () {
  804. this.x = Math.floor( this.x );
  805. this.y = Math.floor( this.y );
  806. return this;
  807. },
  808. ceil: function () {
  809. this.x = Math.ceil( this.x );
  810. this.y = Math.ceil( this.y );
  811. return this;
  812. },
  813. round: function () {
  814. this.x = Math.round( this.x );
  815. this.y = Math.round( this.y );
  816. return this;
  817. },
  818. roundToZero: function () {
  819. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  820. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  821. return this;
  822. },
  823. negate: function () {
  824. return this.multiplyScalar( - 1 );
  825. },
  826. dot: function ( v ) {
  827. return this.x * v.x + this.y * v.y;
  828. },
  829. lengthSq: function () {
  830. return this.x * this.x + this.y * this.y;
  831. },
  832. length: function () {
  833. return Math.sqrt( this.x * this.x + this.y * this.y );
  834. },
  835. normalize: function () {
  836. return this.divideScalar( this.length() );
  837. },
  838. distanceTo: function ( v ) {
  839. return Math.sqrt( this.distanceToSquared( v ) );
  840. },
  841. distanceToSquared: function ( v ) {
  842. var dx = this.x - v.x, dy = this.y - v.y;
  843. return dx * dx + dy * dy;
  844. },
  845. setLength: function ( l ) {
  846. var oldLength = this.length();
  847. if ( oldLength !== 0 && l !== oldLength ) {
  848. this.multiplyScalar( l / oldLength );
  849. }
  850. return this;
  851. },
  852. lerp: function ( v, alpha ) {
  853. this.x += ( v.x - this.x ) * alpha;
  854. this.y += ( v.y - this.y ) * alpha;
  855. return this;
  856. },
  857. equals: function( v ) {
  858. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  859. },
  860. fromArray: function ( array ) {
  861. this.x = array[ 0 ];
  862. this.y = array[ 1 ];
  863. return this;
  864. },
  865. toArray: function () {
  866. return [ this.x, this.y ];
  867. },
  868. clone: function () {
  869. return new THREE.Vector2( this.x, this.y );
  870. }
  871. };
  872. /**
  873. * @author mrdoob / http://mrdoob.com/
  874. * @author *kile / http://kile.stravaganza.org/
  875. * @author philogb / http://blog.thejit.org/
  876. * @author mikael emtinger / http://gomo.se/
  877. * @author egraether / http://egraether.com/
  878. * @author WestLangley / http://github.com/WestLangley
  879. */
  880. THREE.Vector3 = function ( x, y, z ) {
  881. this.x = x || 0;
  882. this.y = y || 0;
  883. this.z = z || 0;
  884. };
  885. THREE.Vector3.prototype = {
  886. constructor: THREE.Vector3,
  887. set: function ( x, y, z ) {
  888. this.x = x;
  889. this.y = y;
  890. this.z = z;
  891. return this;
  892. },
  893. setX: function ( x ) {
  894. this.x = x;
  895. return this;
  896. },
  897. setY: function ( y ) {
  898. this.y = y;
  899. return this;
  900. },
  901. setZ: function ( z ) {
  902. this.z = z;
  903. return this;
  904. },
  905. setComponent: function ( index, value ) {
  906. switch ( index ) {
  907. case 0: this.x = value; break;
  908. case 1: this.y = value; break;
  909. case 2: this.z = value; break;
  910. default: throw new Error( "index is out of range: " + index );
  911. }
  912. },
  913. getComponent: function ( index ) {
  914. switch ( index ) {
  915. case 0: return this.x;
  916. case 1: return this.y;
  917. case 2: return this.z;
  918. default: throw new Error( "index is out of range: " + index );
  919. }
  920. },
  921. copy: function ( v ) {
  922. this.x = v.x;
  923. this.y = v.y;
  924. this.z = v.z;
  925. return this;
  926. },
  927. add: function ( v, w ) {
  928. if ( w !== undefined ) {
  929. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  930. return this.addVectors( v, w );
  931. }
  932. this.x += v.x;
  933. this.y += v.y;
  934. this.z += v.z;
  935. return this;
  936. },
  937. addScalar: function ( s ) {
  938. this.x += s;
  939. this.y += s;
  940. this.z += s;
  941. return this;
  942. },
  943. addVectors: function ( a, b ) {
  944. this.x = a.x + b.x;
  945. this.y = a.y + b.y;
  946. this.z = a.z + b.z;
  947. return this;
  948. },
  949. sub: function ( v, w ) {
  950. if ( w !== undefined ) {
  951. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  952. return this.subVectors( v, w );
  953. }
  954. this.x -= v.x;
  955. this.y -= v.y;
  956. this.z -= v.z;
  957. return this;
  958. },
  959. subVectors: function ( a, b ) {
  960. this.x = a.x - b.x;
  961. this.y = a.y - b.y;
  962. this.z = a.z - b.z;
  963. return this;
  964. },
  965. multiply: function ( v, w ) {
  966. if ( w !== undefined ) {
  967. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  968. return this.multiplyVectors( v, w );
  969. }
  970. this.x *= v.x;
  971. this.y *= v.y;
  972. this.z *= v.z;
  973. return this;
  974. },
  975. multiplyScalar: function ( scalar ) {
  976. this.x *= scalar;
  977. this.y *= scalar;
  978. this.z *= scalar;
  979. return this;
  980. },
  981. multiplyVectors: function ( a, b ) {
  982. this.x = a.x * b.x;
  983. this.y = a.y * b.y;
  984. this.z = a.z * b.z;
  985. return this;
  986. },
  987. applyEuler: function () {
  988. var quaternion;
  989. return function ( euler ) {
  990. if ( euler instanceof THREE.Euler === false ) {
  991. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  992. }
  993. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  994. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  995. return this;
  996. };
  997. }(),
  998. applyAxisAngle: function () {
  999. var quaternion;
  1000. return function ( axis, angle ) {
  1001. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1002. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1003. return this;
  1004. };
  1005. }(),
  1006. applyMatrix3: function ( m ) {
  1007. var x = this.x;
  1008. var y = this.y;
  1009. var z = this.z;
  1010. var e = m.elements;
  1011. this.x = e[0] * x + e[3] * y + e[6] * z;
  1012. this.y = e[1] * x + e[4] * y + e[7] * z;
  1013. this.z = e[2] * x + e[5] * y + e[8] * z;
  1014. return this;
  1015. },
  1016. applyMatrix4: function ( m ) {
  1017. // input: THREE.Matrix4 affine matrix
  1018. var x = this.x, y = this.y, z = this.z;
  1019. var e = m.elements;
  1020. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1021. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1022. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1023. return this;
  1024. },
  1025. applyProjection: function ( m ) {
  1026. // input: THREE.Matrix4 projection matrix
  1027. var x = this.x, y = this.y, z = this.z;
  1028. var e = m.elements;
  1029. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1030. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1031. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1032. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1033. return this;
  1034. },
  1035. applyQuaternion: function ( q ) {
  1036. var x = this.x;
  1037. var y = this.y;
  1038. var z = this.z;
  1039. var qx = q.x;
  1040. var qy = q.y;
  1041. var qz = q.z;
  1042. var qw = q.w;
  1043. // calculate quat * vector
  1044. var ix = qw * x + qy * z - qz * y;
  1045. var iy = qw * y + qz * x - qx * z;
  1046. var iz = qw * z + qx * y - qy * x;
  1047. var iw = -qx * x - qy * y - qz * z;
  1048. // calculate result * inverse quat
  1049. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1050. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1051. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1052. return this;
  1053. },
  1054. transformDirection: function ( m ) {
  1055. // input: THREE.Matrix4 affine matrix
  1056. // vector interpreted as a direction
  1057. var x = this.x, y = this.y, z = this.z;
  1058. var e = m.elements;
  1059. this.x = e[0] * x + e[4] * y + e[8] * z;
  1060. this.y = e[1] * x + e[5] * y + e[9] * z;
  1061. this.z = e[2] * x + e[6] * y + e[10] * z;
  1062. this.normalize();
  1063. return this;
  1064. },
  1065. divide: function ( v ) {
  1066. this.x /= v.x;
  1067. this.y /= v.y;
  1068. this.z /= v.z;
  1069. return this;
  1070. },
  1071. divideScalar: function ( scalar ) {
  1072. if ( scalar !== 0 ) {
  1073. var invScalar = 1 / scalar;
  1074. this.x *= invScalar;
  1075. this.y *= invScalar;
  1076. this.z *= invScalar;
  1077. } else {
  1078. this.x = 0;
  1079. this.y = 0;
  1080. this.z = 0;
  1081. }
  1082. return this;
  1083. },
  1084. min: function ( v ) {
  1085. if ( this.x > v.x ) {
  1086. this.x = v.x;
  1087. }
  1088. if ( this.y > v.y ) {
  1089. this.y = v.y;
  1090. }
  1091. if ( this.z > v.z ) {
  1092. this.z = v.z;
  1093. }
  1094. return this;
  1095. },
  1096. max: function ( v ) {
  1097. if ( this.x < v.x ) {
  1098. this.x = v.x;
  1099. }
  1100. if ( this.y < v.y ) {
  1101. this.y = v.y;
  1102. }
  1103. if ( this.z < v.z ) {
  1104. this.z = v.z;
  1105. }
  1106. return this;
  1107. },
  1108. clamp: function ( min, max ) {
  1109. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1110. if ( this.x < min.x ) {
  1111. this.x = min.x;
  1112. } else if ( this.x > max.x ) {
  1113. this.x = max.x;
  1114. }
  1115. if ( this.y < min.y ) {
  1116. this.y = min.y;
  1117. } else if ( this.y > max.y ) {
  1118. this.y = max.y;
  1119. }
  1120. if ( this.z < min.z ) {
  1121. this.z = min.z;
  1122. } else if ( this.z > max.z ) {
  1123. this.z = max.z;
  1124. }
  1125. return this;
  1126. },
  1127. clampScalar: ( function () {
  1128. var min, max;
  1129. return function ( minVal, maxVal ) {
  1130. if ( min === undefined ) {
  1131. min = new THREE.Vector3();
  1132. max = new THREE.Vector3();
  1133. }
  1134. min.set( minVal, minVal, minVal );
  1135. max.set( maxVal, maxVal, maxVal );
  1136. return this.clamp( min, max );
  1137. };
  1138. } )(),
  1139. floor: function () {
  1140. this.x = Math.floor( this.x );
  1141. this.y = Math.floor( this.y );
  1142. this.z = Math.floor( this.z );
  1143. return this;
  1144. },
  1145. ceil: function () {
  1146. this.x = Math.ceil( this.x );
  1147. this.y = Math.ceil( this.y );
  1148. this.z = Math.ceil( this.z );
  1149. return this;
  1150. },
  1151. round: function () {
  1152. this.x = Math.round( this.x );
  1153. this.y = Math.round( this.y );
  1154. this.z = Math.round( this.z );
  1155. return this;
  1156. },
  1157. roundToZero: function () {
  1158. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1159. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1160. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1161. return this;
  1162. },
  1163. negate: function () {
  1164. return this.multiplyScalar( - 1 );
  1165. },
  1166. dot: function ( v ) {
  1167. return this.x * v.x + this.y * v.y + this.z * v.z;
  1168. },
  1169. lengthSq: function () {
  1170. return this.x * this.x + this.y * this.y + this.z * this.z;
  1171. },
  1172. length: function () {
  1173. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1174. },
  1175. lengthManhattan: function () {
  1176. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1177. },
  1178. normalize: function () {
  1179. return this.divideScalar( this.length() );
  1180. },
  1181. setLength: function ( l ) {
  1182. var oldLength = this.length();
  1183. if ( oldLength !== 0 && l !== oldLength ) {
  1184. this.multiplyScalar( l / oldLength );
  1185. }
  1186. return this;
  1187. },
  1188. lerp: function ( v, alpha ) {
  1189. this.x += ( v.x - this.x ) * alpha;
  1190. this.y += ( v.y - this.y ) * alpha;
  1191. this.z += ( v.z - this.z ) * alpha;
  1192. return this;
  1193. },
  1194. cross: function ( v, w ) {
  1195. if ( w !== undefined ) {
  1196. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1197. return this.crossVectors( v, w );
  1198. }
  1199. var x = this.x, y = this.y, z = this.z;
  1200. this.x = y * v.z - z * v.y;
  1201. this.y = z * v.x - x * v.z;
  1202. this.z = x * v.y - y * v.x;
  1203. return this;
  1204. },
  1205. crossVectors: function ( a, b ) {
  1206. var ax = a.x, ay = a.y, az = a.z;
  1207. var bx = b.x, by = b.y, bz = b.z;
  1208. this.x = ay * bz - az * by;
  1209. this.y = az * bx - ax * bz;
  1210. this.z = ax * by - ay * bx;
  1211. return this;
  1212. },
  1213. projectOnVector: function () {
  1214. var v1, dot;
  1215. return function ( vector ) {
  1216. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1217. v1.copy( vector ).normalize();
  1218. dot = this.dot( v1 );
  1219. return this.copy( v1 ).multiplyScalar( dot );
  1220. };
  1221. }(),
  1222. projectOnPlane: function () {
  1223. var v1;
  1224. return function ( planeNormal ) {
  1225. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1226. v1.copy( this ).projectOnVector( planeNormal );
  1227. return this.sub( v1 );
  1228. }
  1229. }(),
  1230. reflect: function () {
  1231. // reflect incident vector off plane orthogonal to normal
  1232. // normal is assumed to have unit length
  1233. var v1;
  1234. return function ( normal ) {
  1235. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1236. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1237. }
  1238. }(),
  1239. angleTo: function ( v ) {
  1240. var theta = this.dot( v ) / ( this.length() * v.length() );
  1241. // clamp, to handle numerical problems
  1242. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1243. },
  1244. distanceTo: function ( v ) {
  1245. return Math.sqrt( this.distanceToSquared( v ) );
  1246. },
  1247. distanceToSquared: function ( v ) {
  1248. var dx = this.x - v.x;
  1249. var dy = this.y - v.y;
  1250. var dz = this.z - v.z;
  1251. return dx * dx + dy * dy + dz * dz;
  1252. },
  1253. setEulerFromRotationMatrix: function ( m, order ) {
  1254. console.error( "THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.");
  1255. },
  1256. setEulerFromQuaternion: function ( q, order ) {
  1257. console.error( "THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.");
  1258. },
  1259. getPositionFromMatrix: function ( m ) {
  1260. console.warn( "THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()." );
  1261. return this.setFromMatrixPosition( m );
  1262. },
  1263. getScaleFromMatrix: function ( m ) {
  1264. console.warn( "THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()." );
  1265. return this.setFromMatrixScale( m );
  1266. },
  1267. getColumnFromMatrix: function ( index, matrix ) {
  1268. console.warn( "THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()." );
  1269. return this.setFromMatrixColumn( index, matrix );
  1270. },
  1271. setFromMatrixPosition: function ( m ) {
  1272. this.x = m.elements[ 12 ];
  1273. this.y = m.elements[ 13 ];
  1274. this.z = m.elements[ 14 ];
  1275. return this;
  1276. },
  1277. setFromMatrixScale: function ( m ) {
  1278. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1279. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1280. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1281. this.x = sx;
  1282. this.y = sy;
  1283. this.z = sz;
  1284. return this;
  1285. },
  1286. setFromMatrixColumn: function ( index, matrix ) {
  1287. var offset = index * 4;
  1288. var me = matrix.elements;
  1289. this.x = me[ offset ];
  1290. this.y = me[ offset + 1 ];
  1291. this.z = me[ offset + 2 ];
  1292. return this;
  1293. },
  1294. equals: function ( v ) {
  1295. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1296. },
  1297. fromArray: function ( array ) {
  1298. this.x = array[ 0 ];
  1299. this.y = array[ 1 ];
  1300. this.z = array[ 2 ];
  1301. return this;
  1302. },
  1303. toArray: function () {
  1304. return [ this.x, this.y, this.z ];
  1305. },
  1306. clone: function () {
  1307. return new THREE.Vector3( this.x, this.y, this.z );
  1308. }
  1309. };
  1310. /**
  1311. * @author supereggbert / http://www.paulbrunt.co.uk/
  1312. * @author philogb / http://blog.thejit.org/
  1313. * @author mikael emtinger / http://gomo.se/
  1314. * @author egraether / http://egraether.com/
  1315. * @author WestLangley / http://github.com/WestLangley
  1316. */
  1317. THREE.Vector4 = function ( x, y, z, w ) {
  1318. this.x = x || 0;
  1319. this.y = y || 0;
  1320. this.z = z || 0;
  1321. this.w = ( w !== undefined ) ? w : 1;
  1322. };
  1323. THREE.Vector4.prototype = {
  1324. constructor: THREE.Vector4,
  1325. set: function ( x, y, z, w ) {
  1326. this.x = x;
  1327. this.y = y;
  1328. this.z = z;
  1329. this.w = w;
  1330. return this;
  1331. },
  1332. setX: function ( x ) {
  1333. this.x = x;
  1334. return this;
  1335. },
  1336. setY: function ( y ) {
  1337. this.y = y;
  1338. return this;
  1339. },
  1340. setZ: function ( z ) {
  1341. this.z = z;
  1342. return this;
  1343. },
  1344. setW: function ( w ) {
  1345. this.w = w;
  1346. return this;
  1347. },
  1348. setComponent: function ( index, value ) {
  1349. switch ( index ) {
  1350. case 0: this.x = value; break;
  1351. case 1: this.y = value; break;
  1352. case 2: this.z = value; break;
  1353. case 3: this.w = value; break;
  1354. default: throw new Error( "index is out of range: " + index );
  1355. }
  1356. },
  1357. getComponent: function ( index ) {
  1358. switch ( index ) {
  1359. case 0: return this.x;
  1360. case 1: return this.y;
  1361. case 2: return this.z;
  1362. case 3: return this.w;
  1363. default: throw new Error( "index is out of range: " + index );
  1364. }
  1365. },
  1366. copy: function ( v ) {
  1367. this.x = v.x;
  1368. this.y = v.y;
  1369. this.z = v.z;
  1370. this.w = ( v.w !== undefined ) ? v.w : 1;
  1371. return this;
  1372. },
  1373. add: function ( v, w ) {
  1374. if ( w !== undefined ) {
  1375. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1376. return this.addVectors( v, w );
  1377. }
  1378. this.x += v.x;
  1379. this.y += v.y;
  1380. this.z += v.z;
  1381. this.w += v.w;
  1382. return this;
  1383. },
  1384. addScalar: function ( s ) {
  1385. this.x += s;
  1386. this.y += s;
  1387. this.z += s;
  1388. this.w += s;
  1389. return this;
  1390. },
  1391. addVectors: function ( a, b ) {
  1392. this.x = a.x + b.x;
  1393. this.y = a.y + b.y;
  1394. this.z = a.z + b.z;
  1395. this.w = a.w + b.w;
  1396. return this;
  1397. },
  1398. sub: function ( v, w ) {
  1399. if ( w !== undefined ) {
  1400. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1401. return this.subVectors( v, w );
  1402. }
  1403. this.x -= v.x;
  1404. this.y -= v.y;
  1405. this.z -= v.z;
  1406. this.w -= v.w;
  1407. return this;
  1408. },
  1409. subVectors: function ( a, b ) {
  1410. this.x = a.x - b.x;
  1411. this.y = a.y - b.y;
  1412. this.z = a.z - b.z;
  1413. this.w = a.w - b.w;
  1414. return this;
  1415. },
  1416. multiplyScalar: function ( scalar ) {
  1417. this.x *= scalar;
  1418. this.y *= scalar;
  1419. this.z *= scalar;
  1420. this.w *= scalar;
  1421. return this;
  1422. },
  1423. applyMatrix4: function ( m ) {
  1424. var x = this.x;
  1425. var y = this.y;
  1426. var z = this.z;
  1427. var w = this.w;
  1428. var e = m.elements;
  1429. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1430. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1431. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1432. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1433. return this;
  1434. },
  1435. divideScalar: function ( scalar ) {
  1436. if ( scalar !== 0 ) {
  1437. var invScalar = 1 / scalar;
  1438. this.x *= invScalar;
  1439. this.y *= invScalar;
  1440. this.z *= invScalar;
  1441. this.w *= invScalar;
  1442. } else {
  1443. this.x = 0;
  1444. this.y = 0;
  1445. this.z = 0;
  1446. this.w = 1;
  1447. }
  1448. return this;
  1449. },
  1450. setAxisAngleFromQuaternion: function ( q ) {
  1451. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1452. // q is assumed to be normalized
  1453. this.w = 2 * Math.acos( q.w );
  1454. var s = Math.sqrt( 1 - q.w * q.w );
  1455. if ( s < 0.0001 ) {
  1456. this.x = 1;
  1457. this.y = 0;
  1458. this.z = 0;
  1459. } else {
  1460. this.x = q.x / s;
  1461. this.y = q.y / s;
  1462. this.z = q.z / s;
  1463. }
  1464. return this;
  1465. },
  1466. setAxisAngleFromRotationMatrix: function ( m ) {
  1467. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1468. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1469. var angle, x, y, z, // variables for result
  1470. epsilon = 0.01, // margin to allow for rounding errors
  1471. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1472. te = m.elements,
  1473. m11 = te[0], m12 = te[4], m13 = te[8],
  1474. m21 = te[1], m22 = te[5], m23 = te[9],
  1475. m31 = te[2], m32 = te[6], m33 = te[10];
  1476. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1477. && ( Math.abs( m13 - m31 ) < epsilon )
  1478. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1479. // singularity found
  1480. // first check for identity matrix which must have +1 for all terms
  1481. // in leading diagonal and zero in other terms
  1482. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1483. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1484. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1485. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1486. // this singularity is identity matrix so angle = 0
  1487. this.set( 1, 0, 0, 0 );
  1488. return this; // zero angle, arbitrary axis
  1489. }
  1490. // otherwise this singularity is angle = 180
  1491. angle = Math.PI;
  1492. var xx = ( m11 + 1 ) / 2;
  1493. var yy = ( m22 + 1 ) / 2;
  1494. var zz = ( m33 + 1 ) / 2;
  1495. var xy = ( m12 + m21 ) / 4;
  1496. var xz = ( m13 + m31 ) / 4;
  1497. var yz = ( m23 + m32 ) / 4;
  1498. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1499. if ( xx < epsilon ) {
  1500. x = 0;
  1501. y = 0.707106781;
  1502. z = 0.707106781;
  1503. } else {
  1504. x = Math.sqrt( xx );
  1505. y = xy / x;
  1506. z = xz / x;
  1507. }
  1508. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1509. if ( yy < epsilon ) {
  1510. x = 0.707106781;
  1511. y = 0;
  1512. z = 0.707106781;
  1513. } else {
  1514. y = Math.sqrt( yy );
  1515. x = xy / y;
  1516. z = yz / y;
  1517. }
  1518. } else { // m33 is the largest diagonal term so base result on this
  1519. if ( zz < epsilon ) {
  1520. x = 0.707106781;
  1521. y = 0.707106781;
  1522. z = 0;
  1523. } else {
  1524. z = Math.sqrt( zz );
  1525. x = xz / z;
  1526. y = yz / z;
  1527. }
  1528. }
  1529. this.set( x, y, z, angle );
  1530. return this; // return 180 deg rotation
  1531. }
  1532. // as we have reached here there are no singularities so we can handle normally
  1533. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1534. + ( m13 - m31 ) * ( m13 - m31 )
  1535. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1536. if ( Math.abs( s ) < 0.001 ) s = 1;
  1537. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1538. // caught by singularity test above, but I've left it in just in case
  1539. this.x = ( m32 - m23 ) / s;
  1540. this.y = ( m13 - m31 ) / s;
  1541. this.z = ( m21 - m12 ) / s;
  1542. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1543. return this;
  1544. },
  1545. min: function ( v ) {
  1546. if ( this.x > v.x ) {
  1547. this.x = v.x;
  1548. }
  1549. if ( this.y > v.y ) {
  1550. this.y = v.y;
  1551. }
  1552. if ( this.z > v.z ) {
  1553. this.z = v.z;
  1554. }
  1555. if ( this.w > v.w ) {
  1556. this.w = v.w;
  1557. }
  1558. return this;
  1559. },
  1560. max: function ( v ) {
  1561. if ( this.x < v.x ) {
  1562. this.x = v.x;
  1563. }
  1564. if ( this.y < v.y ) {
  1565. this.y = v.y;
  1566. }
  1567. if ( this.z < v.z ) {
  1568. this.z = v.z;
  1569. }
  1570. if ( this.w < v.w ) {
  1571. this.w = v.w;
  1572. }
  1573. return this;
  1574. },
  1575. clamp: function ( min, max ) {
  1576. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1577. if ( this.x < min.x ) {
  1578. this.x = min.x;
  1579. } else if ( this.x > max.x ) {
  1580. this.x = max.x;
  1581. }
  1582. if ( this.y < min.y ) {
  1583. this.y = min.y;
  1584. } else if ( this.y > max.y ) {
  1585. this.y = max.y;
  1586. }
  1587. if ( this.z < min.z ) {
  1588. this.z = min.z;
  1589. } else if ( this.z > max.z ) {
  1590. this.z = max.z;
  1591. }
  1592. if ( this.w < min.w ) {
  1593. this.w = min.w;
  1594. } else if ( this.w > max.w ) {
  1595. this.w = max.w;
  1596. }
  1597. return this;
  1598. },
  1599. clampScalar: ( function () {
  1600. var min, max;
  1601. return function ( minVal, maxVal ) {
  1602. if ( min === undefined ) {
  1603. min = new THREE.Vector4();
  1604. max = new THREE.Vector4();
  1605. }
  1606. min.set( minVal, minVal, minVal, minVal );
  1607. max.set( maxVal, maxVal, maxVal, maxVal );
  1608. return this.clamp( min, max );
  1609. };
  1610. } )(),
  1611. floor: function () {
  1612. this.x = Math.floor( this.x );
  1613. this.y = Math.floor( this.y );
  1614. this.z = Math.floor( this.z );
  1615. this.w = Math.floor( this.w );
  1616. return this;
  1617. },
  1618. ceil: function () {
  1619. this.x = Math.ceil( this.x );
  1620. this.y = Math.ceil( this.y );
  1621. this.z = Math.ceil( this.z );
  1622. this.w = Math.ceil( this.w );
  1623. return this;
  1624. },
  1625. round: function () {
  1626. this.x = Math.round( this.x );
  1627. this.y = Math.round( this.y );
  1628. this.z = Math.round( this.z );
  1629. this.w = Math.round( this.w );
  1630. return this;
  1631. },
  1632. roundToZero: function () {
  1633. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1634. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1635. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1636. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1637. return this;
  1638. },
  1639. negate: function () {
  1640. return this.multiplyScalar( -1 );
  1641. },
  1642. dot: function ( v ) {
  1643. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1644. },
  1645. lengthSq: function () {
  1646. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1647. },
  1648. length: function () {
  1649. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1650. },
  1651. lengthManhattan: function () {
  1652. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1653. },
  1654. normalize: function () {
  1655. return this.divideScalar( this.length() );
  1656. },
  1657. setLength: function ( l ) {
  1658. var oldLength = this.length();
  1659. if ( oldLength !== 0 && l !== oldLength ) {
  1660. this.multiplyScalar( l / oldLength );
  1661. }
  1662. return this;
  1663. },
  1664. lerp: function ( v, alpha ) {
  1665. this.x += ( v.x - this.x ) * alpha;
  1666. this.y += ( v.y - this.y ) * alpha;
  1667. this.z += ( v.z - this.z ) * alpha;
  1668. this.w += ( v.w - this.w ) * alpha;
  1669. return this;
  1670. },
  1671. equals: function ( v ) {
  1672. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1673. },
  1674. fromArray: function ( array ) {
  1675. this.x = array[ 0 ];
  1676. this.y = array[ 1 ];
  1677. this.z = array[ 2 ];
  1678. this.w = array[ 3 ];
  1679. return this;
  1680. },
  1681. toArray: function () {
  1682. return [ this.x, this.y, this.z, this.w ];
  1683. },
  1684. clone: function () {
  1685. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1686. }
  1687. };
  1688. /**
  1689. * @author mrdoob / http://mrdoob.com/
  1690. * @author WestLangley / http://github.com/WestLangley
  1691. * @author bhouston / http://exocortex.com
  1692. */
  1693. THREE.Euler = function ( x, y, z, order ) {
  1694. this._x = x || 0;
  1695. this._y = y || 0;
  1696. this._z = z || 0;
  1697. this._order = order || THREE.Euler.DefaultOrder;
  1698. };
  1699. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1700. THREE.Euler.DefaultOrder = 'XYZ';
  1701. THREE.Euler.prototype = {
  1702. constructor: THREE.Euler,
  1703. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1704. get x () {
  1705. return this._x;
  1706. },
  1707. set x ( value ) {
  1708. this._x = value;
  1709. this.onChangeCallback();
  1710. },
  1711. get y () {
  1712. return this._y;
  1713. },
  1714. set y ( value ) {
  1715. this._y = value;
  1716. this.onChangeCallback();
  1717. },
  1718. get z () {
  1719. return this._z;
  1720. },
  1721. set z ( value ) {
  1722. this._z = value;
  1723. this.onChangeCallback();
  1724. },
  1725. get order () {
  1726. return this._order;
  1727. },
  1728. set order ( value ) {
  1729. this._order = value;
  1730. this.onChangeCallback();
  1731. },
  1732. set: function ( x, y, z, order ) {
  1733. this._x = x;
  1734. this._y = y;
  1735. this._z = z;
  1736. this._order = order || this._order;
  1737. this.onChangeCallback();
  1738. return this;
  1739. },
  1740. copy: function ( euler ) {
  1741. this._x = euler._x;
  1742. this._y = euler._y;
  1743. this._z = euler._z;
  1744. this._order = euler._order;
  1745. this.onChangeCallback();
  1746. return this;
  1747. },
  1748. setFromRotationMatrix: function ( m, order ) {
  1749. var clamp = THREE.Math.clamp;
  1750. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1751. var te = m.elements;
  1752. var m11 = te[0], m12 = te[4], m13 = te[8];
  1753. var m21 = te[1], m22 = te[5], m23 = te[9];
  1754. var m31 = te[2], m32 = te[6], m33 = te[10];
  1755. order = order || this._order;
  1756. if ( order === 'XYZ' ) {
  1757. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1758. if ( Math.abs( m13 ) < 0.99999 ) {
  1759. this._x = Math.atan2( - m23, m33 );
  1760. this._z = Math.atan2( - m12, m11 );
  1761. } else {
  1762. this._x = Math.atan2( m32, m22 );
  1763. this._z = 0;
  1764. }
  1765. } else if ( order === 'YXZ' ) {
  1766. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1767. if ( Math.abs( m23 ) < 0.99999 ) {
  1768. this._y = Math.atan2( m13, m33 );
  1769. this._z = Math.atan2( m21, m22 );
  1770. } else {
  1771. this._y = Math.atan2( - m31, m11 );
  1772. this._z = 0;
  1773. }
  1774. } else if ( order === 'ZXY' ) {
  1775. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1776. if ( Math.abs( m32 ) < 0.99999 ) {
  1777. this._y = Math.atan2( - m31, m33 );
  1778. this._z = Math.atan2( - m12, m22 );
  1779. } else {
  1780. this._y = 0;
  1781. this._z = Math.atan2( m21, m11 );
  1782. }
  1783. } else if ( order === 'ZYX' ) {
  1784. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1785. if ( Math.abs( m31 ) < 0.99999 ) {
  1786. this._x = Math.atan2( m32, m33 );
  1787. this._z = Math.atan2( m21, m11 );
  1788. } else {
  1789. this._x = 0;
  1790. this._z = Math.atan2( - m12, m22 );
  1791. }
  1792. } else if ( order === 'YZX' ) {
  1793. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1794. if ( Math.abs( m21 ) < 0.99999 ) {
  1795. this._x = Math.atan2( - m23, m22 );
  1796. this._y = Math.atan2( - m31, m11 );
  1797. } else {
  1798. this._x = 0;
  1799. this._y = Math.atan2( m13, m33 );
  1800. }
  1801. } else if ( order === 'XZY' ) {
  1802. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1803. if ( Math.abs( m12 ) < 0.99999 ) {
  1804. this._x = Math.atan2( m32, m22 );
  1805. this._y = Math.atan2( m13, m11 );
  1806. } else {
  1807. this._x = Math.atan2( - m23, m33 );
  1808. this._y = 0;
  1809. }
  1810. } else {
  1811. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1812. }
  1813. this._order = order;
  1814. this.onChangeCallback();
  1815. return this;
  1816. },
  1817. setFromQuaternion: function ( q, order, update ) {
  1818. var clamp = THREE.Math.clamp;
  1819. // q is assumed to be normalized
  1820. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1821. var sqx = q.x * q.x;
  1822. var sqy = q.y * q.y;
  1823. var sqz = q.z * q.z;
  1824. var sqw = q.w * q.w;
  1825. order = order || this._order;
  1826. if ( order === 'XYZ' ) {
  1827. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1828. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1829. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1830. } else if ( order === 'YXZ' ) {
  1831. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1832. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1833. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1834. } else if ( order === 'ZXY' ) {
  1835. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1836. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1837. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1838. } else if ( order === 'ZYX' ) {
  1839. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1840. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1841. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1842. } else if ( order === 'YZX' ) {
  1843. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1844. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1845. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1846. } else if ( order === 'XZY' ) {
  1847. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1848. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1849. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1850. } else {
  1851. console.warn( 'THREE.Euler: .setFromQuaternion() given unsupported order: ' + order )
  1852. }
  1853. this._order = order;
  1854. if ( update !== false ) this.onChangeCallback();
  1855. return this;
  1856. },
  1857. reorder: function () {
  1858. // WARNING: this discards revolution information -bhouston
  1859. var q = new THREE.Quaternion();
  1860. return function ( newOrder ) {
  1861. q.setFromEuler( this );
  1862. this.setFromQuaternion( q, newOrder );
  1863. };
  1864. }(),
  1865. equals: function ( euler ) {
  1866. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1867. },
  1868. fromArray: function ( array ) {
  1869. this._x = array[ 0 ];
  1870. this._y = array[ 1 ];
  1871. this._z = array[ 2 ];
  1872. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1873. this.onChangeCallback();
  1874. return this;
  1875. },
  1876. toArray: function () {
  1877. return [ this._x, this._y, this._z, this._order ];
  1878. },
  1879. onChange: function ( callback ) {
  1880. this.onChangeCallback = callback;
  1881. return this;
  1882. },
  1883. onChangeCallback: function () {},
  1884. clone: function () {
  1885. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1886. }
  1887. };
  1888. /**
  1889. * @author bhouston / http://exocortex.com
  1890. */
  1891. THREE.Line3 = function ( start, end ) {
  1892. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1893. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1894. };
  1895. THREE.Line3.prototype = {
  1896. constructor: THREE.Line3,
  1897. set: function ( start, end ) {
  1898. this.start.copy( start );
  1899. this.end.copy( end );
  1900. return this;
  1901. },
  1902. copy: function ( line ) {
  1903. this.start.copy( line.start );
  1904. this.end.copy( line.end );
  1905. return this;
  1906. },
  1907. center: function ( optionalTarget ) {
  1908. var result = optionalTarget || new THREE.Vector3();
  1909. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1910. },
  1911. delta: function ( optionalTarget ) {
  1912. var result = optionalTarget || new THREE.Vector3();
  1913. return result.subVectors( this.end, this.start );
  1914. },
  1915. distanceSq: function () {
  1916. return this.start.distanceToSquared( this.end );
  1917. },
  1918. distance: function () {
  1919. return this.start.distanceTo( this.end );
  1920. },
  1921. at: function ( t, optionalTarget ) {
  1922. var result = optionalTarget || new THREE.Vector3();
  1923. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1924. },
  1925. closestPointToPointParameter: function() {
  1926. var startP = new THREE.Vector3();
  1927. var startEnd = new THREE.Vector3();
  1928. return function ( point, clampToLine ) {
  1929. startP.subVectors( point, this.start );
  1930. startEnd.subVectors( this.end, this.start );
  1931. var startEnd2 = startEnd.dot( startEnd );
  1932. var startEnd_startP = startEnd.dot( startP );
  1933. var t = startEnd_startP / startEnd2;
  1934. if ( clampToLine ) {
  1935. t = THREE.Math.clamp( t, 0, 1 );
  1936. }
  1937. return t;
  1938. };
  1939. }(),
  1940. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1941. var t = this.closestPointToPointParameter( point, clampToLine );
  1942. var result = optionalTarget || new THREE.Vector3();
  1943. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1944. },
  1945. applyMatrix4: function ( matrix ) {
  1946. this.start.applyMatrix4( matrix );
  1947. this.end.applyMatrix4( matrix );
  1948. return this;
  1949. },
  1950. equals: function ( line ) {
  1951. return line.start.equals( this.start ) && line.end.equals( this.end );
  1952. },
  1953. clone: function () {
  1954. return new THREE.Line3().copy( this );
  1955. }
  1956. };
  1957. /**
  1958. * @author bhouston / http://exocortex.com
  1959. */
  1960. THREE.Box2 = function ( min, max ) {
  1961. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1962. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1963. };
  1964. THREE.Box2.prototype = {
  1965. constructor: THREE.Box2,
  1966. set: function ( min, max ) {
  1967. this.min.copy( min );
  1968. this.max.copy( max );
  1969. return this;
  1970. },
  1971. setFromPoints: function ( points ) {
  1972. if ( points.length > 0 ) {
  1973. var point = points[ 0 ];
  1974. this.min.copy( point );
  1975. this.max.copy( point );
  1976. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1977. point = points[ i ];
  1978. if ( point.x < this.min.x ) {
  1979. this.min.x = point.x;
  1980. } else if ( point.x > this.max.x ) {
  1981. this.max.x = point.x;
  1982. }
  1983. if ( point.y < this.min.y ) {
  1984. this.min.y = point.y;
  1985. } else if ( point.y > this.max.y ) {
  1986. this.max.y = point.y;
  1987. }
  1988. }
  1989. } else {
  1990. this.makeEmpty();
  1991. }
  1992. return this;
  1993. },
  1994. setFromCenterAndSize: function () {
  1995. var v1 = new THREE.Vector2();
  1996. return function ( center, size ) {
  1997. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1998. this.min.copy( center ).sub( halfSize );
  1999. this.max.copy( center ).add( halfSize );
  2000. return this;
  2001. };
  2002. }(),
  2003. copy: function ( box ) {
  2004. this.min.copy( box.min );
  2005. this.max.copy( box.max );
  2006. return this;
  2007. },
  2008. makeEmpty: function () {
  2009. this.min.x = this.min.y = Infinity;
  2010. this.max.x = this.max.y = -Infinity;
  2011. return this;
  2012. },
  2013. empty: function () {
  2014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2015. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2016. },
  2017. center: function ( optionalTarget ) {
  2018. var result = optionalTarget || new THREE.Vector2();
  2019. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2020. },
  2021. size: function ( optionalTarget ) {
  2022. var result = optionalTarget || new THREE.Vector2();
  2023. return result.subVectors( this.max, this.min );
  2024. },
  2025. expandByPoint: function ( point ) {
  2026. this.min.min( point );
  2027. this.max.max( point );
  2028. return this;
  2029. },
  2030. expandByVector: function ( vector ) {
  2031. this.min.sub( vector );
  2032. this.max.add( vector );
  2033. return this;
  2034. },
  2035. expandByScalar: function ( scalar ) {
  2036. this.min.addScalar( -scalar );
  2037. this.max.addScalar( scalar );
  2038. return this;
  2039. },
  2040. containsPoint: function ( point ) {
  2041. if ( point.x < this.min.x || point.x > this.max.x ||
  2042. point.y < this.min.y || point.y > this.max.y ) {
  2043. return false;
  2044. }
  2045. return true;
  2046. },
  2047. containsBox: function ( box ) {
  2048. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2049. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2050. return true;
  2051. }
  2052. return false;
  2053. },
  2054. getParameter: function ( point, optionalTarget ) {
  2055. // This can potentially have a divide by zero if the box
  2056. // has a size dimension of 0.
  2057. var result = optionalTarget || new THREE.Vector2();
  2058. return result.set(
  2059. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2060. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2061. );
  2062. },
  2063. isIntersectionBox: function ( box ) {
  2064. // using 6 splitting planes to rule out intersections.
  2065. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2066. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2067. return false;
  2068. }
  2069. return true;
  2070. },
  2071. clampPoint: function ( point, optionalTarget ) {
  2072. var result = optionalTarget || new THREE.Vector2();
  2073. return result.copy( point ).clamp( this.min, this.max );
  2074. },
  2075. distanceToPoint: function () {
  2076. var v1 = new THREE.Vector2();
  2077. return function ( point ) {
  2078. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2079. return clampedPoint.sub( point ).length();
  2080. };
  2081. }(),
  2082. intersect: function ( box ) {
  2083. this.min.max( box.min );
  2084. this.max.min( box.max );
  2085. return this;
  2086. },
  2087. union: function ( box ) {
  2088. this.min.min( box.min );
  2089. this.max.max( box.max );
  2090. return this;
  2091. },
  2092. translate: function ( offset ) {
  2093. this.min.add( offset );
  2094. this.max.add( offset );
  2095. return this;
  2096. },
  2097. equals: function ( box ) {
  2098. return box.min.equals( this.min ) && box.max.equals( this.max );
  2099. },
  2100. clone: function () {
  2101. return new THREE.Box2().copy( this );
  2102. }
  2103. };
  2104. /**
  2105. * @author bhouston / http://exocortex.com
  2106. * @author WestLangley / http://github.com/WestLangley
  2107. */
  2108. THREE.Box3 = function ( min, max ) {
  2109. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2110. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2111. };
  2112. THREE.Box3.prototype = {
  2113. constructor: THREE.Box3,
  2114. set: function ( min, max ) {
  2115. this.min.copy( min );
  2116. this.max.copy( max );
  2117. return this;
  2118. },
  2119. addPoint: function ( point ) {
  2120. if ( point.x < this.min.x ) {
  2121. this.min.x = point.x;
  2122. } else if ( point.x > this.max.x ) {
  2123. this.max.x = point.x;
  2124. }
  2125. if ( point.y < this.min.y ) {
  2126. this.min.y = point.y;
  2127. } else if ( point.y > this.max.y ) {
  2128. this.max.y = point.y;
  2129. }
  2130. if ( point.z < this.min.z ) {
  2131. this.min.z = point.z;
  2132. } else if ( point.z > this.max.z ) {
  2133. this.max.z = point.z;
  2134. }
  2135. return this;
  2136. },
  2137. setFromPoints: function ( points ) {
  2138. if ( points.length > 0 ) {
  2139. var point = points[ 0 ];
  2140. this.min.copy( point );
  2141. this.max.copy( point );
  2142. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2143. this.addPoint( points[ i ] )
  2144. }
  2145. } else {
  2146. this.makeEmpty();
  2147. }
  2148. return this;
  2149. },
  2150. setFromCenterAndSize: function() {
  2151. var v1 = new THREE.Vector3();
  2152. return function ( center, size ) {
  2153. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2154. this.min.copy( center ).sub( halfSize );
  2155. this.max.copy( center ).add( halfSize );
  2156. return this;
  2157. };
  2158. }(),
  2159. setFromObject: function() {
  2160. // Computes the world-axis-aligned bounding box of an object (including its children),
  2161. // accounting for both the object's, and childrens', world transforms
  2162. var v1 = new THREE.Vector3();
  2163. return function( object ) {
  2164. var scope = this;
  2165. object.updateMatrixWorld( true );
  2166. this.makeEmpty();
  2167. object.traverse( function ( node ) {
  2168. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2169. var vertices = node.geometry.vertices;
  2170. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2171. v1.copy( vertices[ i ] );
  2172. v1.applyMatrix4( node.matrixWorld );
  2173. scope.expandByPoint( v1 );
  2174. }
  2175. }
  2176. } );
  2177. return this;
  2178. };
  2179. }(),
  2180. copy: function ( box ) {
  2181. this.min.copy( box.min );
  2182. this.max.copy( box.max );
  2183. return this;
  2184. },
  2185. makeEmpty: function () {
  2186. this.min.x = this.min.y = this.min.z = Infinity;
  2187. this.max.x = this.max.y = this.max.z = -Infinity;
  2188. return this;
  2189. },
  2190. empty: function () {
  2191. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2192. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2193. },
  2194. center: function ( optionalTarget ) {
  2195. var result = optionalTarget || new THREE.Vector3();
  2196. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2197. },
  2198. size: function ( optionalTarget ) {
  2199. var result = optionalTarget || new THREE.Vector3();
  2200. return result.subVectors( this.max, this.min );
  2201. },
  2202. expandByPoint: function ( point ) {
  2203. this.min.min( point );
  2204. this.max.max( point );
  2205. return this;
  2206. },
  2207. expandByVector: function ( vector ) {
  2208. this.min.sub( vector );
  2209. this.max.add( vector );
  2210. return this;
  2211. },
  2212. expandByScalar: function ( scalar ) {
  2213. this.min.addScalar( -scalar );
  2214. this.max.addScalar( scalar );
  2215. return this;
  2216. },
  2217. containsPoint: function ( point ) {
  2218. if ( point.x < this.min.x || point.x > this.max.x ||
  2219. point.y < this.min.y || point.y > this.max.y ||
  2220. point.z < this.min.z || point.z > this.max.z ) {
  2221. return false;
  2222. }
  2223. return true;
  2224. },
  2225. containsBox: function ( box ) {
  2226. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2227. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2228. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2229. return true;
  2230. }
  2231. return false;
  2232. },
  2233. getParameter: function ( point, optionalTarget ) {
  2234. // This can potentially have a divide by zero if the box
  2235. // has a size dimension of 0.
  2236. var result = optionalTarget || new THREE.Vector3();
  2237. return result.set(
  2238. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2239. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2240. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2241. );
  2242. },
  2243. isIntersectionBox: function ( box ) {
  2244. // using 6 splitting planes to rule out intersections.
  2245. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2246. box.max.y < this.min.y || box.min.y > this.max.y ||
  2247. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2248. return false;
  2249. }
  2250. return true;
  2251. },
  2252. clampPoint: function ( point, optionalTarget ) {
  2253. var result = optionalTarget || new THREE.Vector3();
  2254. return result.copy( point ).clamp( this.min, this.max );
  2255. },
  2256. distanceToPoint: function() {
  2257. var v1 = new THREE.Vector3();
  2258. return function ( point ) {
  2259. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2260. return clampedPoint.sub( point ).length();
  2261. };
  2262. }(),
  2263. getBoundingSphere: function() {
  2264. var v1 = new THREE.Vector3();
  2265. return function ( optionalTarget ) {
  2266. var result = optionalTarget || new THREE.Sphere();
  2267. result.center = this.center();
  2268. result.radius = this.size( v1 ).length() * 0.5;
  2269. return result;
  2270. };
  2271. }(),
  2272. intersect: function ( box ) {
  2273. this.min.max( box.min );
  2274. this.max.min( box.max );
  2275. return this;
  2276. },
  2277. union: function ( box ) {
  2278. this.min.min( box.min );
  2279. this.max.max( box.max );
  2280. return this;
  2281. },
  2282. applyMatrix4: function() {
  2283. var points = [
  2284. new THREE.Vector3(),
  2285. new THREE.Vector3(),
  2286. new THREE.Vector3(),
  2287. new THREE.Vector3(),
  2288. new THREE.Vector3(),
  2289. new THREE.Vector3(),
  2290. new THREE.Vector3(),
  2291. new THREE.Vector3()
  2292. ];
  2293. return function ( matrix ) {
  2294. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2295. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2296. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2297. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2298. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2299. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2300. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2301. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2302. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2303. this.makeEmpty();
  2304. this.setFromPoints( points );
  2305. return this;
  2306. };
  2307. }(),
  2308. translate: function ( offset ) {
  2309. this.min.add( offset );
  2310. this.max.add( offset );
  2311. return this;
  2312. },
  2313. equals: function ( box ) {
  2314. return box.min.equals( this.min ) && box.max.equals( this.max );
  2315. },
  2316. clone: function () {
  2317. return new THREE.Box3().copy( this );
  2318. }
  2319. };
  2320. /**
  2321. * @author alteredq / http://alteredqualia.com/
  2322. * @author WestLangley / http://github.com/WestLangley
  2323. * @author bhouston / http://exocortex.com
  2324. */
  2325. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2326. this.elements = new Float32Array( 9 );
  2327. var te = this.elements;
  2328. te[0] = ( n11 !== undefined ) ? n11 : 1; te[3] = n12 || 0; te[6] = n13 || 0;
  2329. te[1] = n21 || 0; te[4] = ( n22 !== undefined ) ? n22 : 1; te[7] = n23 || 0;
  2330. te[2] = n31 || 0; te[5] = n32 || 0; te[8] = ( n33 !== undefined ) ? n33 : 1;
  2331. };
  2332. THREE.Matrix3.prototype = {
  2333. constructor: THREE.Matrix3,
  2334. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2335. var te = this.elements;
  2336. te[0] = n11; te[3] = n12; te[6] = n13;
  2337. te[1] = n21; te[4] = n22; te[7] = n23;
  2338. te[2] = n31; te[5] = n32; te[8] = n33;
  2339. return this;
  2340. },
  2341. identity: function () {
  2342. this.set(
  2343. 1, 0, 0,
  2344. 0, 1, 0,
  2345. 0, 0, 1
  2346. );
  2347. return this;
  2348. },
  2349. copy: function ( m ) {
  2350. var me = m.elements;
  2351. this.set(
  2352. me[0], me[3], me[6],
  2353. me[1], me[4], me[7],
  2354. me[2], me[5], me[8]
  2355. );
  2356. return this;
  2357. },
  2358. multiplyVector3: function ( vector ) {
  2359. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2360. return vector.applyMatrix3( this );
  2361. },
  2362. multiplyVector3Array: function ( a ) {
  2363. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2364. return this.applyToVector3Array( a );
  2365. },
  2366. applyToVector3Array: function() {
  2367. var v1 = new THREE.Vector3();
  2368. return function ( array, offset, length ) {
  2369. if ( offset === undefined ) offset = 0;
  2370. if ( length === undefined ) length = array.length;
  2371. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2372. v1.x = array[ j ];
  2373. v1.y = array[ j + 1 ];
  2374. v1.z = array[ j + 2 ];
  2375. v1.applyMatrix3( this );
  2376. array[ j ] = v1.x;
  2377. array[ j + 1 ] = v1.y;
  2378. array[ j + 2 ] = v1.z;
  2379. }
  2380. return array;
  2381. };
  2382. }(),
  2383. multiplyScalar: function ( s ) {
  2384. var te = this.elements;
  2385. te[0] *= s; te[3] *= s; te[6] *= s;
  2386. te[1] *= s; te[4] *= s; te[7] *= s;
  2387. te[2] *= s; te[5] *= s; te[8] *= s;
  2388. return this;
  2389. },
  2390. determinant: function () {
  2391. var te = this.elements;
  2392. var a = te[0], b = te[1], c = te[2],
  2393. d = te[3], e = te[4], f = te[5],
  2394. g = te[6], h = te[7], i = te[8];
  2395. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2396. },
  2397. getInverse: function ( matrix, throwOnInvertible ) {
  2398. // input: THREE.Matrix4
  2399. // ( based on http://code.google.com/p/webgl-mjs/ )
  2400. var me = matrix.elements;
  2401. var te = this.elements;
  2402. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2403. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2404. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2405. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2406. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2407. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2408. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2409. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2410. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2411. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2412. // no inverse
  2413. if ( det === 0 ) {
  2414. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2415. if ( throwOnInvertible || false ) {
  2416. throw new Error( msg );
  2417. } else {
  2418. console.warn( msg );
  2419. }
  2420. this.identity();
  2421. return this;
  2422. }
  2423. this.multiplyScalar( 1.0 / det );
  2424. return this;
  2425. },
  2426. transpose: function () {
  2427. var tmp, m = this.elements;
  2428. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2429. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2430. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2431. return this;
  2432. },
  2433. flattenToArrayOffset: function( array, offset ) {
  2434. var te = this.elements;
  2435. array[ offset ] = te[0];
  2436. array[ offset + 1 ] = te[1];
  2437. array[ offset + 2 ] = te[2];
  2438. array[ offset + 3 ] = te[3];
  2439. array[ offset + 4 ] = te[4];
  2440. array[ offset + 5 ] = te[5];
  2441. array[ offset + 6 ] = te[6];
  2442. array[ offset + 7 ] = te[7];
  2443. array[ offset + 8 ] = te[8];
  2444. return array;
  2445. },
  2446. getNormalMatrix: function ( m ) {
  2447. // input: THREE.Matrix4
  2448. this.getInverse( m ).transpose();
  2449. return this;
  2450. },
  2451. transposeIntoArray: function ( r ) {
  2452. var m = this.elements;
  2453. r[ 0 ] = m[ 0 ];
  2454. r[ 1 ] = m[ 3 ];
  2455. r[ 2 ] = m[ 6 ];
  2456. r[ 3 ] = m[ 1 ];
  2457. r[ 4 ] = m[ 4 ];
  2458. r[ 5 ] = m[ 7 ];
  2459. r[ 6 ] = m[ 2 ];
  2460. r[ 7 ] = m[ 5 ];
  2461. r[ 8 ] = m[ 8 ];
  2462. return this;
  2463. },
  2464. fromArray: function ( array ) {
  2465. this.elements.set( array );
  2466. return this;
  2467. },
  2468. toArray: function () {
  2469. var te = this.elements;
  2470. return [
  2471. te[ 0 ], te[ 1 ], te[ 2 ],
  2472. te[ 3 ], te[ 4 ], te[ 5 ],
  2473. te[ 6 ], te[ 7 ], te[ 8 ]
  2474. ];
  2475. },
  2476. clone: function () {
  2477. var te = this.elements;
  2478. return new THREE.Matrix3(
  2479. te[0], te[3], te[6],
  2480. te[1], te[4], te[7],
  2481. te[2], te[5], te[8]
  2482. );
  2483. }
  2484. };
  2485. /**
  2486. * @author mrdoob / http://mrdoob.com/
  2487. * @author supereggbert / http://www.paulbrunt.co.uk/
  2488. * @author philogb / http://blog.thejit.org/
  2489. * @author jordi_ros / http://plattsoft.com
  2490. * @author D1plo1d / http://github.com/D1plo1d
  2491. * @author alteredq / http://alteredqualia.com/
  2492. * @author mikael emtinger / http://gomo.se/
  2493. * @author timknip / http://www.floorplanner.com/
  2494. * @author bhouston / http://exocortex.com
  2495. * @author WestLangley / http://github.com/WestLangley
  2496. */
  2497. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2498. this.elements = new Float32Array( 16 );
  2499. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2500. // we should not support semi specification of Matrix4, it is just weird.
  2501. var te = this.elements;
  2502. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2503. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2504. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2505. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2506. };
  2507. THREE.Matrix4.prototype = {
  2508. constructor: THREE.Matrix4,
  2509. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2510. var te = this.elements;
  2511. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2512. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2513. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2514. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2515. return this;
  2516. },
  2517. identity: function () {
  2518. this.set(
  2519. 1, 0, 0, 0,
  2520. 0, 1, 0, 0,
  2521. 0, 0, 1, 0,
  2522. 0, 0, 0, 1
  2523. );
  2524. return this;
  2525. },
  2526. copy: function ( m ) {
  2527. this.elements.set( m.elements );
  2528. return this;
  2529. },
  2530. extractPosition: function ( m ) {
  2531. console.warn( 'THREEMatrix4: .extractPosition() has been renamed to .copyPosition().' );
  2532. return this.copyPosition( m );
  2533. },
  2534. copyPosition: function ( m ) {
  2535. var te = this.elements;
  2536. var me = m.elements;
  2537. te[12] = me[12];
  2538. te[13] = me[13];
  2539. te[14] = me[14];
  2540. return this;
  2541. },
  2542. extractRotation: function () {
  2543. var v1 = new THREE.Vector3();
  2544. return function ( m ) {
  2545. var te = this.elements;
  2546. var me = m.elements;
  2547. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2548. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2549. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2550. te[0] = me[0] * scaleX;
  2551. te[1] = me[1] * scaleX;
  2552. te[2] = me[2] * scaleX;
  2553. te[4] = me[4] * scaleY;
  2554. te[5] = me[5] * scaleY;
  2555. te[6] = me[6] * scaleY;
  2556. te[8] = me[8] * scaleZ;
  2557. te[9] = me[9] * scaleZ;
  2558. te[10] = me[10] * scaleZ;
  2559. return this;
  2560. };
  2561. }(),
  2562. makeRotationFromEuler: function ( euler ) {
  2563. if ( euler instanceof THREE.Euler === false ) {
  2564. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2565. }
  2566. var te = this.elements;
  2567. var x = euler.x, y = euler.y, z = euler.z;
  2568. var a = Math.cos( x ), b = Math.sin( x );
  2569. var c = Math.cos( y ), d = Math.sin( y );
  2570. var e = Math.cos( z ), f = Math.sin( z );
  2571. if ( euler.order === 'XYZ' ) {
  2572. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2573. te[0] = c * e;
  2574. te[4] = - c * f;
  2575. te[8] = d;
  2576. te[1] = af + be * d;
  2577. te[5] = ae - bf * d;
  2578. te[9] = - b * c;
  2579. te[2] = bf - ae * d;
  2580. te[6] = be + af * d;
  2581. te[10] = a * c;
  2582. } else if ( euler.order === 'YXZ' ) {
  2583. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2584. te[0] = ce + df * b;
  2585. te[4] = de * b - cf;
  2586. te[8] = a * d;
  2587. te[1] = a * f;
  2588. te[5] = a * e;
  2589. te[9] = - b;
  2590. te[2] = cf * b - de;
  2591. te[6] = df + ce * b;
  2592. te[10] = a * c;
  2593. } else if ( euler.order === 'ZXY' ) {
  2594. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2595. te[0] = ce - df * b;
  2596. te[4] = - a * f;
  2597. te[8] = de + cf * b;
  2598. te[1] = cf + de * b;
  2599. te[5] = a * e;
  2600. te[9] = df - ce * b;
  2601. te[2] = - a * d;
  2602. te[6] = b;
  2603. te[10] = a * c;
  2604. } else if ( euler.order === 'ZYX' ) {
  2605. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2606. te[0] = c * e;
  2607. te[4] = be * d - af;
  2608. te[8] = ae * d + bf;
  2609. te[1] = c * f;
  2610. te[5] = bf * d + ae;
  2611. te[9] = af * d - be;
  2612. te[2] = - d;
  2613. te[6] = b * c;
  2614. te[10] = a * c;
  2615. } else if ( euler.order === 'YZX' ) {
  2616. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2617. te[0] = c * e;
  2618. te[4] = bd - ac * f;
  2619. te[8] = bc * f + ad;
  2620. te[1] = f;
  2621. te[5] = a * e;
  2622. te[9] = - b * e;
  2623. te[2] = - d * e;
  2624. te[6] = ad * f + bc;
  2625. te[10] = ac - bd * f;
  2626. } else if ( euler.order === 'XZY' ) {
  2627. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2628. te[0] = c * e;
  2629. te[4] = - f;
  2630. te[8] = d * e;
  2631. te[1] = ac * f + bd;
  2632. te[5] = a * e;
  2633. te[9] = ad * f - bc;
  2634. te[2] = bc * f - ad;
  2635. te[6] = b * e;
  2636. te[10] = bd * f + ac;
  2637. }
  2638. // last column
  2639. te[3] = 0;
  2640. te[7] = 0;
  2641. te[11] = 0;
  2642. // bottom row
  2643. te[12] = 0;
  2644. te[13] = 0;
  2645. te[14] = 0;
  2646. te[15] = 1;
  2647. return this;
  2648. },
  2649. setRotationFromQuaternion: function ( q ) {
  2650. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2651. return this.makeRotationFromQuaternion( q );
  2652. },
  2653. makeRotationFromQuaternion: function ( q ) {
  2654. var te = this.elements;
  2655. var x = q.x, y = q.y, z = q.z, w = q.w;
  2656. var x2 = x + x, y2 = y + y, z2 = z + z;
  2657. var xx = x * x2, xy = x * y2, xz = x * z2;
  2658. var yy = y * y2, yz = y * z2, zz = z * z2;
  2659. var wx = w * x2, wy = w * y2, wz = w * z2;
  2660. te[0] = 1 - ( yy + zz );
  2661. te[4] = xy - wz;
  2662. te[8] = xz + wy;
  2663. te[1] = xy + wz;
  2664. te[5] = 1 - ( xx + zz );
  2665. te[9] = yz - wx;
  2666. te[2] = xz - wy;
  2667. te[6] = yz + wx;
  2668. te[10] = 1 - ( xx + yy );
  2669. // last column
  2670. te[3] = 0;
  2671. te[7] = 0;
  2672. te[11] = 0;
  2673. // bottom row
  2674. te[12] = 0;
  2675. te[13] = 0;
  2676. te[14] = 0;
  2677. te[15] = 1;
  2678. return this;
  2679. },
  2680. lookAt: function() {
  2681. var x = new THREE.Vector3();
  2682. var y = new THREE.Vector3();
  2683. var z = new THREE.Vector3();
  2684. return function ( eye, target, up ) {
  2685. var te = this.elements;
  2686. z.subVectors( eye, target ).normalize();
  2687. if ( z.length() === 0 ) {
  2688. z.z = 1;
  2689. }
  2690. x.crossVectors( up, z ).normalize();
  2691. if ( x.length() === 0 ) {
  2692. z.x += 0.0001;
  2693. x.crossVectors( up, z ).normalize();
  2694. }
  2695. y.crossVectors( z, x );
  2696. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2697. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2698. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2699. return this;
  2700. };
  2701. }(),
  2702. multiply: function ( m, n ) {
  2703. if ( n !== undefined ) {
  2704. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2705. return this.multiplyMatrices( m, n );
  2706. }
  2707. return this.multiplyMatrices( this, m );
  2708. },
  2709. multiplyMatrices: function ( a, b ) {
  2710. var ae = a.elements;
  2711. var be = b.elements;
  2712. var te = this.elements;
  2713. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2714. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2715. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2716. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2717. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2718. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2719. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2720. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2721. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2722. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2723. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2724. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2725. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2726. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2727. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2728. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2729. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2730. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2731. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2732. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2733. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2734. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2735. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2736. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2737. return this;
  2738. },
  2739. multiplyToArray: function ( a, b, r ) {
  2740. var te = this.elements;
  2741. this.multiplyMatrices( a, b );
  2742. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2743. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2744. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2745. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2746. return this;
  2747. },
  2748. multiplyScalar: function ( s ) {
  2749. var te = this.elements;
  2750. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2751. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2752. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2753. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2754. return this;
  2755. },
  2756. multiplyVector3: function ( vector ) {
  2757. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2758. return vector.applyProjection( this );
  2759. },
  2760. multiplyVector4: function ( vector ) {
  2761. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2762. return vector.applyMatrix4( this );
  2763. },
  2764. multiplyVector3Array: function ( a ) {
  2765. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2766. return this.applyToVector3Array( a );
  2767. },
  2768. applyToVector3Array: function() {
  2769. var v1 = new THREE.Vector3();
  2770. return function ( array, offset, length ) {
  2771. if ( offset === undefined ) offset = 0;
  2772. if ( length === undefined ) length = array.length;
  2773. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2774. v1.x = array[ j ];
  2775. v1.y = array[ j + 1 ];
  2776. v1.z = array[ j + 2 ];
  2777. v1.applyMatrix4( this );
  2778. array[ j ] = v1.x;
  2779. array[ j + 1 ] = v1.y;
  2780. array[ j + 2 ] = v1.z;
  2781. }
  2782. return array;
  2783. };
  2784. }(),
  2785. rotateAxis: function ( v ) {
  2786. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2787. v.transformDirection( this );
  2788. },
  2789. crossVector: function ( vector ) {
  2790. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2791. return vector.applyMatrix4( this );
  2792. },
  2793. determinant: function () {
  2794. var te = this.elements;
  2795. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2796. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2797. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2798. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2799. //TODO: make this more efficient
  2800. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2801. return (
  2802. n41 * (
  2803. +n14 * n23 * n32
  2804. -n13 * n24 * n32
  2805. -n14 * n22 * n33
  2806. +n12 * n24 * n33
  2807. +n13 * n22 * n34
  2808. -n12 * n23 * n34
  2809. ) +
  2810. n42 * (
  2811. +n11 * n23 * n34
  2812. -n11 * n24 * n33
  2813. +n14 * n21 * n33
  2814. -n13 * n21 * n34
  2815. +n13 * n24 * n31
  2816. -n14 * n23 * n31
  2817. ) +
  2818. n43 * (
  2819. +n11 * n24 * n32
  2820. -n11 * n22 * n34
  2821. -n14 * n21 * n32
  2822. +n12 * n21 * n34
  2823. +n14 * n22 * n31
  2824. -n12 * n24 * n31
  2825. ) +
  2826. n44 * (
  2827. -n13 * n22 * n31
  2828. -n11 * n23 * n32
  2829. +n11 * n22 * n33
  2830. +n13 * n21 * n32
  2831. -n12 * n21 * n33
  2832. +n12 * n23 * n31
  2833. )
  2834. );
  2835. },
  2836. transpose: function () {
  2837. var te = this.elements;
  2838. var tmp;
  2839. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2840. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2841. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2842. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2843. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2844. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2845. return this;
  2846. },
  2847. flattenToArrayOffset: function( array, offset ) {
  2848. var te = this.elements;
  2849. array[ offset ] = te[0];
  2850. array[ offset + 1 ] = te[1];
  2851. array[ offset + 2 ] = te[2];
  2852. array[ offset + 3 ] = te[3];
  2853. array[ offset + 4 ] = te[4];
  2854. array[ offset + 5 ] = te[5];
  2855. array[ offset + 6 ] = te[6];
  2856. array[ offset + 7 ] = te[7];
  2857. array[ offset + 8 ] = te[8];
  2858. array[ offset + 9 ] = te[9];
  2859. array[ offset + 10 ] = te[10];
  2860. array[ offset + 11 ] = te[11];
  2861. array[ offset + 12 ] = te[12];
  2862. array[ offset + 13 ] = te[13];
  2863. array[ offset + 14 ] = te[14];
  2864. array[ offset + 15 ] = te[15];
  2865. return array;
  2866. },
  2867. getPosition: function() {
  2868. var v1 = new THREE.Vector3();
  2869. return function () {
  2870. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2871. var te = this.elements;
  2872. return v1.set( te[12], te[13], te[14] );
  2873. };
  2874. }(),
  2875. setPosition: function ( v ) {
  2876. var te = this.elements;
  2877. te[12] = v.x;
  2878. te[13] = v.y;
  2879. te[14] = v.z;
  2880. return this;
  2881. },
  2882. getInverse: function ( m, throwOnInvertible ) {
  2883. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2884. var te = this.elements;
  2885. var me = m.elements;
  2886. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2887. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2888. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2889. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2890. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2891. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2892. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2893. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2894. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2895. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2896. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2897. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2898. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2899. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2900. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2901. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2902. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2903. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2904. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2905. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2906. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2907. if ( det == 0 ) {
  2908. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2909. if ( throwOnInvertible || false ) {
  2910. throw new Error( msg );
  2911. } else {
  2912. console.warn( msg );
  2913. }
  2914. this.identity();
  2915. return this;
  2916. }
  2917. this.multiplyScalar( 1 / det );
  2918. return this;
  2919. },
  2920. translate: function ( v ) {
  2921. console.warn( 'THREE.Matrix4: .translate() has been removed.');
  2922. },
  2923. rotateX: function ( angle ) {
  2924. console.warn( 'THREE.Matrix4: .rotateX() has been removed.');
  2925. },
  2926. rotateY: function ( angle ) {
  2927. console.warn( 'THREE.Matrix4: .rotateY() has been removed.');
  2928. },
  2929. rotateZ: function ( angle ) {
  2930. console.warn( 'THREE.Matrix4: .rotateZ() has been removed.');
  2931. },
  2932. rotateByAxis: function ( axis, angle ) {
  2933. console.warn( 'THREE.Matrix4: .rotateByAxis() has been removed.');
  2934. },
  2935. scale: function ( v ) {
  2936. var te = this.elements;
  2937. var x = v.x, y = v.y, z = v.z;
  2938. te[0] *= x; te[4] *= y; te[8] *= z;
  2939. te[1] *= x; te[5] *= y; te[9] *= z;
  2940. te[2] *= x; te[6] *= y; te[10] *= z;
  2941. te[3] *= x; te[7] *= y; te[11] *= z;
  2942. return this;
  2943. },
  2944. getMaxScaleOnAxis: function () {
  2945. var te = this.elements;
  2946. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2947. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2948. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2949. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2950. },
  2951. makeTranslation: function ( x, y, z ) {
  2952. this.set(
  2953. 1, 0, 0, x,
  2954. 0, 1, 0, y,
  2955. 0, 0, 1, z,
  2956. 0, 0, 0, 1
  2957. );
  2958. return this;
  2959. },
  2960. makeRotationX: function ( theta ) {
  2961. var c = Math.cos( theta ), s = Math.sin( theta );
  2962. this.set(
  2963. 1, 0, 0, 0,
  2964. 0, c, -s, 0,
  2965. 0, s, c, 0,
  2966. 0, 0, 0, 1
  2967. );
  2968. return this;
  2969. },
  2970. makeRotationY: function ( theta ) {
  2971. var c = Math.cos( theta ), s = Math.sin( theta );
  2972. this.set(
  2973. c, 0, s, 0,
  2974. 0, 1, 0, 0,
  2975. -s, 0, c, 0,
  2976. 0, 0, 0, 1
  2977. );
  2978. return this;
  2979. },
  2980. makeRotationZ: function ( theta ) {
  2981. var c = Math.cos( theta ), s = Math.sin( theta );
  2982. this.set(
  2983. c, -s, 0, 0,
  2984. s, c, 0, 0,
  2985. 0, 0, 1, 0,
  2986. 0, 0, 0, 1
  2987. );
  2988. return this;
  2989. },
  2990. makeRotationAxis: function ( axis, angle ) {
  2991. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2992. var c = Math.cos( angle );
  2993. var s = Math.sin( angle );
  2994. var t = 1 - c;
  2995. var x = axis.x, y = axis.y, z = axis.z;
  2996. var tx = t * x, ty = t * y;
  2997. this.set(
  2998. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2999. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3000. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3001. 0, 0, 0, 1
  3002. );
  3003. return this;
  3004. },
  3005. makeScale: function ( x, y, z ) {
  3006. this.set(
  3007. x, 0, 0, 0,
  3008. 0, y, 0, 0,
  3009. 0, 0, z, 0,
  3010. 0, 0, 0, 1
  3011. );
  3012. return this;
  3013. },
  3014. compose: function ( position, quaternion, scale ) {
  3015. this.makeRotationFromQuaternion( quaternion );
  3016. this.scale( scale );
  3017. this.setPosition( position );
  3018. return this;
  3019. },
  3020. decompose: function () {
  3021. var vector = new THREE.Vector3();
  3022. var matrix = new THREE.Matrix4();
  3023. return function ( position, quaternion, scale ) {
  3024. var te = this.elements;
  3025. var sx = vector.set( te[0], te[1], te[2] ).length();
  3026. var sy = vector.set( te[4], te[5], te[6] ).length();
  3027. var sz = vector.set( te[8], te[9], te[10] ).length();
  3028. // if determine is negative, we need to invert one scale
  3029. var det = this.determinant();
  3030. if( det < 0 ) {
  3031. sx = -sx;
  3032. }
  3033. position.x = te[12];
  3034. position.y = te[13];
  3035. position.z = te[14];
  3036. // scale the rotation part
  3037. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3038. var invSX = 1 / sx;
  3039. var invSY = 1 / sy;
  3040. var invSZ = 1 / sz;
  3041. matrix.elements[0] *= invSX;
  3042. matrix.elements[1] *= invSX;
  3043. matrix.elements[2] *= invSX;
  3044. matrix.elements[4] *= invSY;
  3045. matrix.elements[5] *= invSY;
  3046. matrix.elements[6] *= invSY;
  3047. matrix.elements[8] *= invSZ;
  3048. matrix.elements[9] *= invSZ;
  3049. matrix.elements[10] *= invSZ;
  3050. quaternion.setFromRotationMatrix( matrix );
  3051. scale.x = sx;
  3052. scale.y = sy;
  3053. scale.z = sz;
  3054. return this;
  3055. };
  3056. }(),
  3057. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3058. var te = this.elements;
  3059. var x = 2 * near / ( right - left );
  3060. var y = 2 * near / ( top - bottom );
  3061. var a = ( right + left ) / ( right - left );
  3062. var b = ( top + bottom ) / ( top - bottom );
  3063. var c = - ( far + near ) / ( far - near );
  3064. var d = - 2 * far * near / ( far - near );
  3065. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3066. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3067. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3068. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3069. return this;
  3070. },
  3071. makePerspective: function ( fov, aspect, near, far ) {
  3072. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3073. var ymin = - ymax;
  3074. var xmin = ymin * aspect;
  3075. var xmax = ymax * aspect;
  3076. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3077. },
  3078. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3079. var te = this.elements;
  3080. var w = right - left;
  3081. var h = top - bottom;
  3082. var p = far - near;
  3083. var x = ( right + left ) / w;
  3084. var y = ( top + bottom ) / h;
  3085. var z = ( far + near ) / p;
  3086. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3087. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3088. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3089. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3090. return this;
  3091. },
  3092. fromArray: function ( array ) {
  3093. this.elements.set( array );
  3094. return this;
  3095. },
  3096. toArray: function () {
  3097. var te = this.elements;
  3098. return [
  3099. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3100. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3101. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3102. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3103. ];
  3104. },
  3105. clone: function () {
  3106. var te = this.elements;
  3107. return new THREE.Matrix4(
  3108. te[0], te[4], te[8], te[12],
  3109. te[1], te[5], te[9], te[13],
  3110. te[2], te[6], te[10], te[14],
  3111. te[3], te[7], te[11], te[15]
  3112. );
  3113. }
  3114. };
  3115. /**
  3116. * @author bhouston / http://exocortex.com
  3117. */
  3118. THREE.Ray = function ( origin, direction ) {
  3119. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3120. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3121. };
  3122. THREE.Ray.prototype = {
  3123. constructor: THREE.Ray,
  3124. set: function ( origin, direction ) {
  3125. this.origin.copy( origin );
  3126. this.direction.copy( direction );
  3127. return this;
  3128. },
  3129. copy: function ( ray ) {
  3130. this.origin.copy( ray.origin );
  3131. this.direction.copy( ray.direction );
  3132. return this;
  3133. },
  3134. at: function ( t, optionalTarget ) {
  3135. var result = optionalTarget || new THREE.Vector3();
  3136. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3137. },
  3138. recast: function () {
  3139. var v1 = new THREE.Vector3();
  3140. return function ( t ) {
  3141. this.origin.copy( this.at( t, v1 ) );
  3142. return this;
  3143. };
  3144. }(),
  3145. closestPointToPoint: function ( point, optionalTarget ) {
  3146. var result = optionalTarget || new THREE.Vector3();
  3147. result.subVectors( point, this.origin );
  3148. var directionDistance = result.dot( this.direction );
  3149. if ( directionDistance < 0 ) {
  3150. return result.copy( this.origin );
  3151. }
  3152. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3153. },
  3154. distanceToPoint: function () {
  3155. var v1 = new THREE.Vector3();
  3156. return function ( point ) {
  3157. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3158. // point behind the ray
  3159. if ( directionDistance < 0 ) {
  3160. return this.origin.distanceTo( point );
  3161. }
  3162. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3163. return v1.distanceTo( point );
  3164. };
  3165. }(),
  3166. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3167. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3168. // It returns the min distance between the ray and the segment
  3169. // defined by v0 and v1
  3170. // It can also set two optional targets :
  3171. // - The closest point on the ray
  3172. // - The closest point on the segment
  3173. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3174. var segDir = v1.clone().sub( v0 ).normalize();
  3175. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3176. var diff = this.origin.clone().sub( segCenter );
  3177. var a01 = - this.direction.dot( segDir );
  3178. var b0 = diff.dot( this.direction );
  3179. var b1 = - diff.dot( segDir );
  3180. var c = diff.lengthSq();
  3181. var det = Math.abs( 1 - a01 * a01 );
  3182. var s0, s1, sqrDist, extDet;
  3183. if ( det >= 0 ) {
  3184. // The ray and segment are not parallel.
  3185. s0 = a01 * b1 - b0;
  3186. s1 = a01 * b0 - b1;
  3187. extDet = segExtent * det;
  3188. if ( s0 >= 0 ) {
  3189. if ( s1 >= - extDet ) {
  3190. if ( s1 <= extDet ) {
  3191. // region 0
  3192. // Minimum at interior points of ray and segment.
  3193. var invDet = 1 / det;
  3194. s0 *= invDet;
  3195. s1 *= invDet;
  3196. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3197. } else {
  3198. // region 1
  3199. s1 = segExtent;
  3200. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3201. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3202. }
  3203. } else {
  3204. // region 5
  3205. s1 = - segExtent;
  3206. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3207. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3208. }
  3209. } else {
  3210. if ( s1 <= - extDet) {
  3211. // region 4
  3212. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3213. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3214. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3215. } else if ( s1 <= extDet ) {
  3216. // region 3
  3217. s0 = 0;
  3218. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3219. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3220. } else {
  3221. // region 2
  3222. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3223. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3224. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3225. }
  3226. }
  3227. } else {
  3228. // Ray and segment are parallel.
  3229. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3230. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3231. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3232. }
  3233. if ( optionalPointOnRay ) {
  3234. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3235. }
  3236. if ( optionalPointOnSegment ) {
  3237. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3238. }
  3239. return sqrDist;
  3240. },
  3241. isIntersectionSphere: function ( sphere ) {
  3242. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3243. },
  3244. isIntersectionPlane: function ( plane ) {
  3245. // check if the ray lies on the plane first
  3246. var distToPoint = plane.distanceToPoint( this.origin );
  3247. if ( distToPoint === 0 ) {
  3248. return true;
  3249. }
  3250. var denominator = plane.normal.dot( this.direction );
  3251. if ( denominator * distToPoint < 0 ) {
  3252. return true
  3253. }
  3254. // ray origin is behind the plane (and is pointing behind it)
  3255. return false;
  3256. },
  3257. distanceToPlane: function ( plane ) {
  3258. var denominator = plane.normal.dot( this.direction );
  3259. if ( denominator == 0 ) {
  3260. // line is coplanar, return origin
  3261. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3262. return 0;
  3263. }
  3264. // Null is preferable to undefined since undefined means.... it is undefined
  3265. return null;
  3266. }
  3267. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3268. // Return if the ray never intersects the plane
  3269. return t >= 0 ? t : null;
  3270. },
  3271. intersectPlane: function ( plane, optionalTarget ) {
  3272. var t = this.distanceToPlane( plane );
  3273. if ( t === null ) {
  3274. return null;
  3275. }
  3276. return this.at( t, optionalTarget );
  3277. },
  3278. isIntersectionBox: function () {
  3279. var v = new THREE.Vector3();
  3280. return function ( box ) {
  3281. return this.intersectBox( box, v ) !== null;
  3282. }
  3283. }(),
  3284. intersectBox: function ( box , optionalTarget ) {
  3285. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3286. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3287. var invdirx = 1/this.direction.x,
  3288. invdiry = 1/this.direction.y,
  3289. invdirz = 1/this.direction.z;
  3290. var origin = this.origin;
  3291. if (invdirx >= 0) {
  3292. tmin = (box.min.x - origin.x) * invdirx;
  3293. tmax = (box.max.x - origin.x) * invdirx;
  3294. } else {
  3295. tmin = (box.max.x - origin.x) * invdirx;
  3296. tmax = (box.min.x - origin.x) * invdirx;
  3297. }
  3298. if (invdiry >= 0) {
  3299. tymin = (box.min.y - origin.y) * invdiry;
  3300. tymax = (box.max.y - origin.y) * invdiry;
  3301. } else {
  3302. tymin = (box.max.y - origin.y) * invdiry;
  3303. tymax = (box.min.y - origin.y) * invdiry;
  3304. }
  3305. if ((tmin > tymax) || (tymin > tmax)) return null;
  3306. // These lines also handle the case where tmin or tmax is NaN
  3307. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3308. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3309. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3310. if (invdirz >= 0) {
  3311. tzmin = (box.min.z - origin.z) * invdirz;
  3312. tzmax = (box.max.z - origin.z) * invdirz;
  3313. } else {
  3314. tzmin = (box.max.z - origin.z) * invdirz;
  3315. tzmax = (box.min.z - origin.z) * invdirz;
  3316. }
  3317. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3318. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3319. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3320. //return point closest to the ray (positive side)
  3321. if ( tmax < 0 ) return null;
  3322. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3323. },
  3324. intersectTriangle: function() {
  3325. // Compute the offset origin, edges, and normal.
  3326. var diff = new THREE.Vector3();
  3327. var edge1 = new THREE.Vector3();
  3328. var edge2 = new THREE.Vector3();
  3329. var normal = new THREE.Vector3();
  3330. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3331. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3332. edge1.subVectors( b, a );
  3333. edge2.subVectors( c, a );
  3334. normal.crossVectors( edge1, edge2 );
  3335. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3336. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3337. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3338. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3339. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3340. var DdN = this.direction.dot( normal );
  3341. var sign;
  3342. if ( DdN > 0 ) {
  3343. if ( backfaceCulling ) return null;
  3344. sign = 1;
  3345. } else if ( DdN < 0 ) {
  3346. sign = - 1;
  3347. DdN = - DdN;
  3348. } else {
  3349. return null;
  3350. }
  3351. diff.subVectors( this.origin, a );
  3352. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3353. // b1 < 0, no intersection
  3354. if ( DdQxE2 < 0 ) {
  3355. return null;
  3356. }
  3357. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3358. // b2 < 0, no intersection
  3359. if ( DdE1xQ < 0 ) {
  3360. return null;
  3361. }
  3362. // b1+b2 > 1, no intersection
  3363. if ( DdQxE2 + DdE1xQ > DdN ) {
  3364. return null;
  3365. }
  3366. // Line intersects triangle, check if ray does.
  3367. var QdN = - sign * diff.dot( normal );
  3368. // t < 0, no intersection
  3369. if ( QdN < 0 ) {
  3370. return null;
  3371. }
  3372. // Ray intersects triangle.
  3373. return this.at( QdN / DdN, optionalTarget );
  3374. }
  3375. }(),
  3376. applyMatrix4: function ( matrix4 ) {
  3377. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3378. this.origin.applyMatrix4( matrix4 );
  3379. this.direction.sub( this.origin );
  3380. this.direction.normalize();
  3381. return this;
  3382. },
  3383. equals: function ( ray ) {
  3384. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3385. },
  3386. clone: function () {
  3387. return new THREE.Ray().copy( this );
  3388. }
  3389. };
  3390. /**
  3391. * @author bhouston / http://exocortex.com
  3392. * @author mrdoob / http://mrdoob.com/
  3393. */
  3394. THREE.Sphere = function ( center, radius ) {
  3395. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3396. this.radius = ( radius !== undefined ) ? radius : 0;
  3397. };
  3398. THREE.Sphere.prototype = {
  3399. constructor: THREE.Sphere,
  3400. set: function ( center, radius ) {
  3401. this.center.copy( center );
  3402. this.radius = radius;
  3403. return this;
  3404. },
  3405. setFromPoints: function () {
  3406. var box = new THREE.Box3();
  3407. return function ( points, optionalCenter ) {
  3408. var center = this.center;
  3409. if ( optionalCenter !== undefined ) {
  3410. center.copy( optionalCenter );
  3411. } else {
  3412. box.setFromPoints( points ).center( center );
  3413. }
  3414. var maxRadiusSq = 0;
  3415. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3416. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3417. }
  3418. this.radius = Math.sqrt( maxRadiusSq );
  3419. return this;
  3420. };
  3421. }(),
  3422. copy: function ( sphere ) {
  3423. this.center.copy( sphere.center );
  3424. this.radius = sphere.radius;
  3425. return this;
  3426. },
  3427. empty: function () {
  3428. return ( this.radius <= 0 );
  3429. },
  3430. containsPoint: function ( point ) {
  3431. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3432. },
  3433. distanceToPoint: function ( point ) {
  3434. return ( point.distanceTo( this.center ) - this.radius );
  3435. },
  3436. intersectsSphere: function ( sphere ) {
  3437. var radiusSum = this.radius + sphere.radius;
  3438. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3439. },
  3440. clampPoint: function ( point, optionalTarget ) {
  3441. var deltaLengthSq = this.center.distanceToSquared( point );
  3442. var result = optionalTarget || new THREE.Vector3();
  3443. result.copy( point );
  3444. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3445. result.sub( this.center ).normalize();
  3446. result.multiplyScalar( this.radius ).add( this.center );
  3447. }
  3448. return result;
  3449. },
  3450. getBoundingBox: function ( optionalTarget ) {
  3451. var box = optionalTarget || new THREE.Box3();
  3452. box.set( this.center, this.center );
  3453. box.expandByScalar( this.radius );
  3454. return box;
  3455. },
  3456. applyMatrix4: function ( matrix ) {
  3457. this.center.applyMatrix4( matrix );
  3458. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3459. return this;
  3460. },
  3461. translate: function ( offset ) {
  3462. this.center.add( offset );
  3463. return this;
  3464. },
  3465. equals: function ( sphere ) {
  3466. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3467. },
  3468. clone: function () {
  3469. return new THREE.Sphere().copy( this );
  3470. }
  3471. };
  3472. /**
  3473. * @author mrdoob / http://mrdoob.com/
  3474. * @author alteredq / http://alteredqualia.com/
  3475. * @author bhouston / http://exocortex.com
  3476. */
  3477. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3478. this.planes = [
  3479. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3480. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3481. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3482. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3483. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3484. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3485. ];
  3486. };
  3487. THREE.Frustum.prototype = {
  3488. constructor: THREE.Frustum,
  3489. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3490. var planes = this.planes;
  3491. planes[0].copy( p0 );
  3492. planes[1].copy( p1 );
  3493. planes[2].copy( p2 );
  3494. planes[3].copy( p3 );
  3495. planes[4].copy( p4 );
  3496. planes[5].copy( p5 );
  3497. return this;
  3498. },
  3499. copy: function ( frustum ) {
  3500. var planes = this.planes;
  3501. for( var i = 0; i < 6; i ++ ) {
  3502. planes[i].copy( frustum.planes[i] );
  3503. }
  3504. return this;
  3505. },
  3506. setFromMatrix: function ( m ) {
  3507. var planes = this.planes;
  3508. var me = m.elements;
  3509. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3510. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3511. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3512. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3513. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3514. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3515. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3516. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3517. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3518. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3519. return this;
  3520. },
  3521. intersectsObject: function () {
  3522. var sphere = new THREE.Sphere();
  3523. return function ( object ) {
  3524. var geometry = object.geometry;
  3525. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3526. sphere.copy( geometry.boundingSphere );
  3527. sphere.applyMatrix4( object.matrixWorld );
  3528. return this.intersectsSphere( sphere );
  3529. };
  3530. }(),
  3531. intersectsSphere: function ( sphere ) {
  3532. var planes = this.planes;
  3533. var center = sphere.center;
  3534. var negRadius = -sphere.radius;
  3535. for ( var i = 0; i < 6; i ++ ) {
  3536. var distance = planes[ i ].distanceToPoint( center );
  3537. if ( distance < negRadius ) {
  3538. return false;
  3539. }
  3540. }
  3541. return true;
  3542. },
  3543. intersectsBox : function() {
  3544. var p1 = new THREE.Vector3(),
  3545. p2 = new THREE.Vector3();
  3546. return function( box ) {
  3547. var planes = this.planes;
  3548. for ( var i = 0; i < 6 ; i ++ ) {
  3549. var plane = planes[i];
  3550. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3551. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3552. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3553. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3554. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3555. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3556. var d1 = plane.distanceToPoint( p1 );
  3557. var d2 = plane.distanceToPoint( p2 );
  3558. // if both outside plane, no intersection
  3559. if ( d1 < 0 && d2 < 0 ) {
  3560. return false;
  3561. }
  3562. }
  3563. return true;
  3564. };
  3565. }(),
  3566. containsPoint: function ( point ) {
  3567. var planes = this.planes;
  3568. for ( var i = 0; i < 6; i ++ ) {
  3569. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3570. return false;
  3571. }
  3572. }
  3573. return true;
  3574. },
  3575. clone: function () {
  3576. return new THREE.Frustum().copy( this );
  3577. }
  3578. };
  3579. /**
  3580. * @author bhouston / http://exocortex.com
  3581. */
  3582. THREE.Plane = function ( normal, constant ) {
  3583. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3584. this.constant = ( constant !== undefined ) ? constant : 0;
  3585. };
  3586. THREE.Plane.prototype = {
  3587. constructor: THREE.Plane,
  3588. set: function ( normal, constant ) {
  3589. this.normal.copy( normal );
  3590. this.constant = constant;
  3591. return this;
  3592. },
  3593. setComponents: function ( x, y, z, w ) {
  3594. this.normal.set( x, y, z );
  3595. this.constant = w;
  3596. return this;
  3597. },
  3598. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3599. this.normal.copy( normal );
  3600. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3601. return this;
  3602. },
  3603. setFromCoplanarPoints: function() {
  3604. var v1 = new THREE.Vector3();
  3605. var v2 = new THREE.Vector3();
  3606. return function ( a, b, c ) {
  3607. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3608. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3609. this.setFromNormalAndCoplanarPoint( normal, a );
  3610. return this;
  3611. };
  3612. }(),
  3613. copy: function ( plane ) {
  3614. this.normal.copy( plane.normal );
  3615. this.constant = plane.constant;
  3616. return this;
  3617. },
  3618. normalize: function () {
  3619. // Note: will lead to a divide by zero if the plane is invalid.
  3620. var inverseNormalLength = 1.0 / this.normal.length();
  3621. this.normal.multiplyScalar( inverseNormalLength );
  3622. this.constant *= inverseNormalLength;
  3623. return this;
  3624. },
  3625. negate: function () {
  3626. this.constant *= -1;
  3627. this.normal.negate();
  3628. return this;
  3629. },
  3630. distanceToPoint: function ( point ) {
  3631. return this.normal.dot( point ) + this.constant;
  3632. },
  3633. distanceToSphere: function ( sphere ) {
  3634. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3635. },
  3636. projectPoint: function ( point, optionalTarget ) {
  3637. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3638. },
  3639. orthoPoint: function ( point, optionalTarget ) {
  3640. var perpendicularMagnitude = this.distanceToPoint( point );
  3641. var result = optionalTarget || new THREE.Vector3();
  3642. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3643. },
  3644. isIntersectionLine: function ( line ) {
  3645. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3646. var startSign = this.distanceToPoint( line.start );
  3647. var endSign = this.distanceToPoint( line.end );
  3648. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3649. },
  3650. intersectLine: function() {
  3651. var v1 = new THREE.Vector3();
  3652. return function ( line, optionalTarget ) {
  3653. var result = optionalTarget || new THREE.Vector3();
  3654. var direction = line.delta( v1 );
  3655. var denominator = this.normal.dot( direction );
  3656. if ( denominator == 0 ) {
  3657. // line is coplanar, return origin
  3658. if( this.distanceToPoint( line.start ) == 0 ) {
  3659. return result.copy( line.start );
  3660. }
  3661. // Unsure if this is the correct method to handle this case.
  3662. return undefined;
  3663. }
  3664. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3665. if( t < 0 || t > 1 ) {
  3666. return undefined;
  3667. }
  3668. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3669. };
  3670. }(),
  3671. coplanarPoint: function ( optionalTarget ) {
  3672. var result = optionalTarget || new THREE.Vector3();
  3673. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3674. },
  3675. applyMatrix4: function() {
  3676. var v1 = new THREE.Vector3();
  3677. var v2 = new THREE.Vector3();
  3678. var m1 = new THREE.Matrix3();
  3679. return function ( matrix, optionalNormalMatrix ) {
  3680. // compute new normal based on theory here:
  3681. // http://www.songho.ca/opengl/gl_normaltransform.html
  3682. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3683. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3684. var newCoplanarPoint = this.coplanarPoint( v2 );
  3685. newCoplanarPoint.applyMatrix4( matrix );
  3686. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3687. return this;
  3688. };
  3689. }(),
  3690. translate: function ( offset ) {
  3691. this.constant = this.constant - offset.dot( this.normal );
  3692. return this;
  3693. },
  3694. equals: function ( plane ) {
  3695. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3696. },
  3697. clone: function () {
  3698. return new THREE.Plane().copy( this );
  3699. }
  3700. };
  3701. /**
  3702. * @author alteredq / http://alteredqualia.com/
  3703. * @author mrdoob / http://mrdoob.com/
  3704. */
  3705. THREE.Math = {
  3706. generateUUID: function () {
  3707. // http://www.broofa.com/Tools/Math.uuid.htm
  3708. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3709. var uuid = new Array(36);
  3710. var rnd = 0, r;
  3711. return function () {
  3712. for ( var i = 0; i < 36; i ++ ) {
  3713. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3714. uuid[ i ] = '-';
  3715. } else if ( i == 14 ) {
  3716. uuid[ i ] = '4';
  3717. } else {
  3718. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3719. r = rnd & 0xf;
  3720. rnd = rnd >> 4;
  3721. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3722. }
  3723. }
  3724. return uuid.join('');
  3725. };
  3726. }(),
  3727. // Clamp value to range <a, b>
  3728. clamp: function ( x, a, b ) {
  3729. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3730. },
  3731. // Clamp value to range <a, inf)
  3732. clampBottom: function ( x, a ) {
  3733. return x < a ? a : x;
  3734. },
  3735. // Linear mapping from range <a1, a2> to range <b1, b2>
  3736. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3737. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3738. },
  3739. // http://en.wikipedia.org/wiki/Smoothstep
  3740. smoothstep: function ( x, min, max ) {
  3741. if ( x <= min ) return 0;
  3742. if ( x >= max ) return 1;
  3743. x = ( x - min )/( max - min );
  3744. return x*x*(3 - 2*x);
  3745. },
  3746. smootherstep: function ( x, min, max ) {
  3747. if ( x <= min ) return 0;
  3748. if ( x >= max ) return 1;
  3749. x = ( x - min )/( max - min );
  3750. return x*x*x*(x*(x*6 - 15) + 10);
  3751. },
  3752. // Random float from <0, 1> with 16 bits of randomness
  3753. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3754. random16: function () {
  3755. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3756. },
  3757. // Random integer from <low, high> interval
  3758. randInt: function ( low, high ) {
  3759. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3760. },
  3761. // Random float from <low, high> interval
  3762. randFloat: function ( low, high ) {
  3763. return low + Math.random() * ( high - low );
  3764. },
  3765. // Random float from <-range/2, range/2> interval
  3766. randFloatSpread: function ( range ) {
  3767. return range * ( 0.5 - Math.random() );
  3768. },
  3769. sign: function ( x ) {
  3770. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3771. },
  3772. degToRad: function() {
  3773. var degreeToRadiansFactor = Math.PI / 180;
  3774. return function ( degrees ) {
  3775. return degrees * degreeToRadiansFactor;
  3776. };
  3777. }(),
  3778. radToDeg: function() {
  3779. var radianToDegreesFactor = 180 / Math.PI;
  3780. return function ( radians ) {
  3781. return radians * radianToDegreesFactor;
  3782. };
  3783. }(),
  3784. isPowerOfTwo: function ( value ) {
  3785. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3786. }
  3787. };
  3788. /**
  3789. * Spline from Tween.js, slightly optimized (and trashed)
  3790. * http://sole.github.com/tween.js/examples/05_spline.html
  3791. *
  3792. * @author mrdoob / http://mrdoob.com/
  3793. * @author alteredq / http://alteredqualia.com/
  3794. */
  3795. THREE.Spline = function ( points ) {
  3796. this.points = points;
  3797. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3798. point, intPoint, weight, w2, w3,
  3799. pa, pb, pc, pd;
  3800. this.initFromArray = function( a ) {
  3801. this.points = [];
  3802. for ( var i = 0; i < a.length; i++ ) {
  3803. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3804. }
  3805. };
  3806. this.getPoint = function ( k ) {
  3807. point = ( this.points.length - 1 ) * k;
  3808. intPoint = Math.floor( point );
  3809. weight = point - intPoint;
  3810. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3811. c[ 1 ] = intPoint;
  3812. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3813. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3814. pa = this.points[ c[ 0 ] ];
  3815. pb = this.points[ c[ 1 ] ];
  3816. pc = this.points[ c[ 2 ] ];
  3817. pd = this.points[ c[ 3 ] ];
  3818. w2 = weight * weight;
  3819. w3 = weight * w2;
  3820. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3821. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3822. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3823. return v3;
  3824. };
  3825. this.getControlPointsArray = function () {
  3826. var i, p, l = this.points.length,
  3827. coords = [];
  3828. for ( i = 0; i < l; i ++ ) {
  3829. p = this.points[ i ];
  3830. coords[ i ] = [ p.x, p.y, p.z ];
  3831. }
  3832. return coords;
  3833. };
  3834. // approximate length by summing linear segments
  3835. this.getLength = function ( nSubDivisions ) {
  3836. var i, index, nSamples, position,
  3837. point = 0, intPoint = 0, oldIntPoint = 0,
  3838. oldPosition = new THREE.Vector3(),
  3839. tmpVec = new THREE.Vector3(),
  3840. chunkLengths = [],
  3841. totalLength = 0;
  3842. // first point has 0 length
  3843. chunkLengths[ 0 ] = 0;
  3844. if ( !nSubDivisions ) nSubDivisions = 100;
  3845. nSamples = this.points.length * nSubDivisions;
  3846. oldPosition.copy( this.points[ 0 ] );
  3847. for ( i = 1; i < nSamples; i ++ ) {
  3848. index = i / nSamples;
  3849. position = this.getPoint( index );
  3850. tmpVec.copy( position );
  3851. totalLength += tmpVec.distanceTo( oldPosition );
  3852. oldPosition.copy( position );
  3853. point = ( this.points.length - 1 ) * index;
  3854. intPoint = Math.floor( point );
  3855. if ( intPoint != oldIntPoint ) {
  3856. chunkLengths[ intPoint ] = totalLength;
  3857. oldIntPoint = intPoint;
  3858. }
  3859. }
  3860. // last point ends with total length
  3861. chunkLengths[ chunkLengths.length ] = totalLength;
  3862. return { chunks: chunkLengths, total: totalLength };
  3863. };
  3864. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3865. var i, j,
  3866. index, indexCurrent, indexNext,
  3867. linearDistance, realDistance,
  3868. sampling, position,
  3869. newpoints = [],
  3870. tmpVec = new THREE.Vector3(),
  3871. sl = this.getLength();
  3872. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3873. for ( i = 1; i < this.points.length; i++ ) {
  3874. //tmpVec.copy( this.points[ i - 1 ] );
  3875. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3876. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3877. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3878. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3879. indexNext = i / ( this.points.length - 1 );
  3880. for ( j = 1; j < sampling - 1; j++ ) {
  3881. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3882. position = this.getPoint( index );
  3883. newpoints.push( tmpVec.copy( position ).clone() );
  3884. }
  3885. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3886. }
  3887. this.points = newpoints;
  3888. };
  3889. // Catmull-Rom
  3890. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3891. var v0 = ( p2 - p0 ) * 0.5,
  3892. v1 = ( p3 - p1 ) * 0.5;
  3893. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3894. };
  3895. };
  3896. /**
  3897. * @author bhouston / http://exocortex.com
  3898. * @author mrdoob / http://mrdoob.com/
  3899. */
  3900. THREE.Triangle = function ( a, b, c ) {
  3901. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3902. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3903. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3904. };
  3905. THREE.Triangle.normal = function() {
  3906. var v0 = new THREE.Vector3();
  3907. return function ( a, b, c, optionalTarget ) {
  3908. var result = optionalTarget || new THREE.Vector3();
  3909. result.subVectors( c, b );
  3910. v0.subVectors( a, b );
  3911. result.cross( v0 );
  3912. var resultLengthSq = result.lengthSq();
  3913. if( resultLengthSq > 0 ) {
  3914. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3915. }
  3916. return result.set( 0, 0, 0 );
  3917. };
  3918. }();
  3919. // static/instance method to calculate barycoordinates
  3920. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3921. THREE.Triangle.barycoordFromPoint = function() {
  3922. var v0 = new THREE.Vector3();
  3923. var v1 = new THREE.Vector3();
  3924. var v2 = new THREE.Vector3();
  3925. return function ( point, a, b, c, optionalTarget ) {
  3926. v0.subVectors( c, a );
  3927. v1.subVectors( b, a );
  3928. v2.subVectors( point, a );
  3929. var dot00 = v0.dot( v0 );
  3930. var dot01 = v0.dot( v1 );
  3931. var dot02 = v0.dot( v2 );
  3932. var dot11 = v1.dot( v1 );
  3933. var dot12 = v1.dot( v2 );
  3934. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3935. var result = optionalTarget || new THREE.Vector3();
  3936. // colinear or singular triangle
  3937. if( denom == 0 ) {
  3938. // arbitrary location outside of triangle?
  3939. // not sure if this is the best idea, maybe should be returning undefined
  3940. return result.set( -2, -1, -1 );
  3941. }
  3942. var invDenom = 1 / denom;
  3943. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3944. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3945. // barycoordinates must always sum to 1
  3946. return result.set( 1 - u - v, v, u );
  3947. };
  3948. }();
  3949. THREE.Triangle.containsPoint = function() {
  3950. var v1 = new THREE.Vector3();
  3951. return function ( point, a, b, c ) {
  3952. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3953. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3954. };
  3955. }();
  3956. THREE.Triangle.prototype = {
  3957. constructor: THREE.Triangle,
  3958. set: function ( a, b, c ) {
  3959. this.a.copy( a );
  3960. this.b.copy( b );
  3961. this.c.copy( c );
  3962. return this;
  3963. },
  3964. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3965. this.a.copy( points[i0] );
  3966. this.b.copy( points[i1] );
  3967. this.c.copy( points[i2] );
  3968. return this;
  3969. },
  3970. copy: function ( triangle ) {
  3971. this.a.copy( triangle.a );
  3972. this.b.copy( triangle.b );
  3973. this.c.copy( triangle.c );
  3974. return this;
  3975. },
  3976. area: function() {
  3977. var v0 = new THREE.Vector3();
  3978. var v1 = new THREE.Vector3();
  3979. return function () {
  3980. v0.subVectors( this.c, this.b );
  3981. v1.subVectors( this.a, this.b );
  3982. return v0.cross( v1 ).length() * 0.5;
  3983. };
  3984. }(),
  3985. midpoint: function ( optionalTarget ) {
  3986. var result = optionalTarget || new THREE.Vector3();
  3987. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3988. },
  3989. normal: function ( optionalTarget ) {
  3990. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3991. },
  3992. plane: function ( optionalTarget ) {
  3993. var result = optionalTarget || new THREE.Plane();
  3994. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3995. },
  3996. barycoordFromPoint: function ( point, optionalTarget ) {
  3997. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3998. },
  3999. containsPoint: function ( point ) {
  4000. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4001. },
  4002. equals: function ( triangle ) {
  4003. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4004. },
  4005. clone: function () {
  4006. return new THREE.Triangle().copy( this );
  4007. }
  4008. };
  4009. /**
  4010. * @author alteredq / http://alteredqualia.com/
  4011. */
  4012. THREE.Clock = function ( autoStart ) {
  4013. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4014. this.startTime = 0;
  4015. this.oldTime = 0;
  4016. this.elapsedTime = 0;
  4017. this.running = false;
  4018. };
  4019. THREE.Clock.prototype = {
  4020. constructor: THREE.Clock,
  4021. start: function () {
  4022. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4023. ? self.performance.now()
  4024. : Date.now();
  4025. this.oldTime = this.startTime;
  4026. this.running = true;
  4027. },
  4028. stop: function () {
  4029. this.getElapsedTime();
  4030. this.running = false;
  4031. },
  4032. getElapsedTime: function () {
  4033. this.getDelta();
  4034. return this.elapsedTime;
  4035. },
  4036. getDelta: function () {
  4037. var diff = 0;
  4038. if ( this.autoStart && ! this.running ) {
  4039. this.start();
  4040. }
  4041. if ( this.running ) {
  4042. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4043. ? self.performance.now()
  4044. : Date.now();
  4045. diff = 0.001 * ( newTime - this.oldTime );
  4046. this.oldTime = newTime;
  4047. this.elapsedTime += diff;
  4048. }
  4049. return diff;
  4050. }
  4051. };
  4052. /**
  4053. * https://github.com/mrdoob/eventdispatcher.js/
  4054. */
  4055. THREE.EventDispatcher = function () {}
  4056. THREE.EventDispatcher.prototype = {
  4057. constructor: THREE.EventDispatcher,
  4058. apply: function ( object ) {
  4059. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4060. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4061. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4062. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4063. },
  4064. addEventListener: function ( type, listener ) {
  4065. if ( this._listeners === undefined ) this._listeners = {};
  4066. var listeners = this._listeners;
  4067. if ( listeners[ type ] === undefined ) {
  4068. listeners[ type ] = [];
  4069. }
  4070. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4071. listeners[ type ].push( listener );
  4072. }
  4073. },
  4074. hasEventListener: function ( type, listener ) {
  4075. if ( this._listeners === undefined ) return false;
  4076. var listeners = this._listeners;
  4077. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4078. return true;
  4079. }
  4080. return false;
  4081. },
  4082. removeEventListener: function ( type, listener ) {
  4083. if ( this._listeners === undefined ) return;
  4084. var listeners = this._listeners;
  4085. var listenerArray = listeners[ type ];
  4086. if ( listenerArray !== undefined ) {
  4087. var index = listenerArray.indexOf( listener );
  4088. if ( index !== - 1 ) {
  4089. listenerArray.splice( index, 1 );
  4090. }
  4091. }
  4092. },
  4093. dispatchEvent: function ( event ) {
  4094. if ( this._listeners === undefined ) return;
  4095. var listeners = this._listeners;
  4096. var listenerArray = listeners[ event.type ];
  4097. if ( listenerArray !== undefined ) {
  4098. event.target = this;
  4099. var array = [];
  4100. var length = listenerArray.length;
  4101. for ( var i = 0; i < length; i ++ ) {
  4102. array[ i ] = listenerArray[ i ];
  4103. }
  4104. for ( var i = 0; i < length; i ++ ) {
  4105. array[ i ].call( this, event );
  4106. }
  4107. }
  4108. }
  4109. };
  4110. /**
  4111. * @author mrdoob / http://mrdoob.com/
  4112. * @author bhouston / http://exocortex.com/
  4113. * @author stephomi / http://stephaneginier.com/
  4114. */
  4115. ( function ( THREE ) {
  4116. THREE.Raycaster = function ( origin, direction, near, far ) {
  4117. this.ray = new THREE.Ray( origin, direction );
  4118. // direction is assumed to be normalized (for accurate distance calculations)
  4119. this.near = near || 0;
  4120. this.far = far || Infinity;
  4121. this.params = {
  4122. Sprite: {},
  4123. Mesh: {},
  4124. PointCloud: { threshold: 1 },
  4125. LOD: {},
  4126. Line: {}
  4127. };
  4128. };
  4129. var descSort = function ( a, b ) {
  4130. return a.distance - b.distance;
  4131. };
  4132. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4133. object.raycast( raycaster, intersects );
  4134. if ( recursive === true ) {
  4135. var children = object.children;
  4136. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4137. intersectObject( children[ i ], raycaster, intersects, true );
  4138. }
  4139. }
  4140. };
  4141. //
  4142. THREE.Raycaster.prototype.precision = 0.0001;
  4143. THREE.Raycaster.prototype.linePrecision = 1;
  4144. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4145. this.ray.set( origin, direction );
  4146. // direction is assumed to be normalized (for accurate distance calculations)
  4147. };
  4148. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4149. var intersects = [];
  4150. intersectObject( object, this, intersects, recursive );
  4151. intersects.sort( descSort );
  4152. return intersects;
  4153. };
  4154. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4155. var intersects = [];
  4156. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4157. intersectObject( objects[ i ], this, intersects, recursive );
  4158. }
  4159. intersects.sort( descSort );
  4160. return intersects;
  4161. };
  4162. }( THREE ) );
  4163. /**
  4164. * @author mrdoob / http://mrdoob.com/
  4165. * @author mikael emtinger / http://gomo.se/
  4166. * @author alteredq / http://alteredqualia.com/
  4167. * @author WestLangley / http://github.com/WestLangley
  4168. */
  4169. THREE.Object3D = function () {
  4170. this.id = THREE.Object3DIdCount ++;
  4171. this.uuid = THREE.Math.generateUUID();
  4172. this.name = '';
  4173. this.parent = undefined;
  4174. this.children = [];
  4175. this.up = THREE.Object3D.DefaultUp.clone();
  4176. var scope = this;
  4177. var position = new THREE.Vector3();
  4178. var rotation = new THREE.Euler();
  4179. var quaternion = new THREE.Quaternion();
  4180. var scale = new THREE.Vector3( 1, 1, 1 );
  4181. rotation.onChange( function () {
  4182. quaternion.setFromEuler( rotation, false );
  4183. } );
  4184. quaternion.onChange( function () {
  4185. rotation.setFromQuaternion( quaternion, undefined, false );
  4186. } );
  4187. Object.defineProperties( this, {
  4188. position: {
  4189. enumerable: true,
  4190. get: function () {
  4191. return position;
  4192. },
  4193. set: function ( value ) {
  4194. console.error( 'THREE.Object3D: .position = new THREE.Vector3() pattern no longer works. Use .position.copy() instead.' );
  4195. position.copy( value );
  4196. }
  4197. },
  4198. rotation: {
  4199. enumerable: true,
  4200. get: function () {
  4201. return rotation;
  4202. },
  4203. set: function ( value ) {
  4204. console.error( 'THREE.Object3D: .rotation = new THREE.Euler() pattern no longer works. Use .rotation.copy() instead.' );
  4205. rotation.copy( value );
  4206. }
  4207. },
  4208. quaternion: {
  4209. enumerable: true,
  4210. get: function () {
  4211. return quaternion;
  4212. },
  4213. set: function ( value ) {
  4214. console.error( 'THREE.Object3D: .quaternion = new THREE.Quaternion() pattern no longer works. Use .quaternion.copy() instead.' );
  4215. quaternion.copy( value );
  4216. }
  4217. },
  4218. scale: {
  4219. enumerable: true,
  4220. get: function () {
  4221. return scale;
  4222. },
  4223. set: function ( value ) {
  4224. console.error( 'THREE.Object3D: .scale = new THREE.Vector3() pattern no longer works. Use .scale.copy() instead.' );
  4225. scale.copy( value );
  4226. }
  4227. }
  4228. } );
  4229. this.renderDepth = null;
  4230. this.rotationAutoUpdate = true;
  4231. this.matrix = new THREE.Matrix4();
  4232. this.matrixWorld = new THREE.Matrix4();
  4233. this.matrixAutoUpdate = true;
  4234. this.matrixWorldNeedsUpdate = false;
  4235. this.visible = true;
  4236. this.castShadow = false;
  4237. this.receiveShadow = false;
  4238. this.frustumCulled = true;
  4239. this.userData = {};
  4240. };
  4241. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4242. THREE.Object3D.prototype = {
  4243. constructor: THREE.Object3D,
  4244. get eulerOrder () {
  4245. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4246. return this.rotation.order;
  4247. },
  4248. set eulerOrder ( value ) {
  4249. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4250. this.rotation.order = value;
  4251. },
  4252. get useQuaternion () {
  4253. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4254. },
  4255. set useQuaternion ( value ) {
  4256. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4257. },
  4258. applyMatrix: function ( matrix ) {
  4259. this.matrix.multiplyMatrices( matrix, this.matrix );
  4260. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4261. },
  4262. setRotationFromAxisAngle: function ( axis, angle ) {
  4263. // assumes axis is normalized
  4264. this.quaternion.setFromAxisAngle( axis, angle );
  4265. },
  4266. setRotationFromEuler: function ( euler ) {
  4267. this.quaternion.setFromEuler( euler, true );
  4268. },
  4269. setRotationFromMatrix: function ( m ) {
  4270. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4271. this.quaternion.setFromRotationMatrix( m );
  4272. },
  4273. setRotationFromQuaternion: function ( q ) {
  4274. // assumes q is normalized
  4275. this.quaternion.copy( q );
  4276. },
  4277. rotateOnAxis: function() {
  4278. // rotate object on axis in object space
  4279. // axis is assumed to be normalized
  4280. var q1 = new THREE.Quaternion();
  4281. return function ( axis, angle ) {
  4282. q1.setFromAxisAngle( axis, angle );
  4283. this.quaternion.multiply( q1 );
  4284. return this;
  4285. }
  4286. }(),
  4287. rotateX: function () {
  4288. var v1 = new THREE.Vector3( 1, 0, 0 );
  4289. return function ( angle ) {
  4290. return this.rotateOnAxis( v1, angle );
  4291. };
  4292. }(),
  4293. rotateY: function () {
  4294. var v1 = new THREE.Vector3( 0, 1, 0 );
  4295. return function ( angle ) {
  4296. return this.rotateOnAxis( v1, angle );
  4297. };
  4298. }(),
  4299. rotateZ: function () {
  4300. var v1 = new THREE.Vector3( 0, 0, 1 );
  4301. return function ( angle ) {
  4302. return this.rotateOnAxis( v1, angle );
  4303. };
  4304. }(),
  4305. translateOnAxis: function () {
  4306. // translate object by distance along axis in object space
  4307. // axis is assumed to be normalized
  4308. var v1 = new THREE.Vector3();
  4309. return function ( axis, distance ) {
  4310. v1.copy( axis );
  4311. v1.applyQuaternion( this.quaternion );
  4312. this.position.add( v1.multiplyScalar( distance ) );
  4313. return this;
  4314. }
  4315. }(),
  4316. translate: function ( distance, axis ) {
  4317. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4318. return this.translateOnAxis( axis, distance );
  4319. },
  4320. translateX: function () {
  4321. var v1 = new THREE.Vector3( 1, 0, 0 );
  4322. return function ( distance ) {
  4323. return this.translateOnAxis( v1, distance );
  4324. };
  4325. }(),
  4326. translateY: function () {
  4327. var v1 = new THREE.Vector3( 0, 1, 0 );
  4328. return function ( distance ) {
  4329. return this.translateOnAxis( v1, distance );
  4330. };
  4331. }(),
  4332. translateZ: function () {
  4333. var v1 = new THREE.Vector3( 0, 0, 1 );
  4334. return function ( distance ) {
  4335. return this.translateOnAxis( v1, distance );
  4336. };
  4337. }(),
  4338. localToWorld: function ( vector ) {
  4339. return vector.applyMatrix4( this.matrixWorld );
  4340. },
  4341. worldToLocal: function () {
  4342. var m1 = new THREE.Matrix4();
  4343. return function ( vector ) {
  4344. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4345. };
  4346. }(),
  4347. lookAt: function () {
  4348. // This routine does not support objects with rotated and/or translated parent(s)
  4349. var m1 = new THREE.Matrix4();
  4350. return function ( vector ) {
  4351. m1.lookAt( vector, this.position, this.up );
  4352. this.quaternion.setFromRotationMatrix( m1 );
  4353. };
  4354. }(),
  4355. add: function ( object ) {
  4356. if ( object === this ) {
  4357. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4358. return;
  4359. }
  4360. if ( object instanceof THREE.Object3D ) {
  4361. if ( object.parent !== undefined ) {
  4362. object.parent.remove( object );
  4363. }
  4364. object.parent = this;
  4365. object.dispatchEvent( { type: 'added' } );
  4366. this.children.push( object );
  4367. // add to scene
  4368. var scene = this;
  4369. while ( scene.parent !== undefined ) {
  4370. scene = scene.parent;
  4371. }
  4372. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4373. scene.__addObject( object );
  4374. }
  4375. }
  4376. },
  4377. remove: function ( object ) {
  4378. var index = this.children.indexOf( object );
  4379. if ( index !== - 1 ) {
  4380. object.parent = undefined;
  4381. object.dispatchEvent( { type: 'removed' } );
  4382. this.children.splice( index, 1 );
  4383. // remove from scene
  4384. var scene = this;
  4385. while ( scene.parent !== undefined ) {
  4386. scene = scene.parent;
  4387. }
  4388. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4389. scene.__removeObject( object );
  4390. }
  4391. }
  4392. },
  4393. raycast: function () {},
  4394. traverse: function ( callback ) {
  4395. callback( this );
  4396. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4397. this.children[ i ].traverse( callback );
  4398. }
  4399. },
  4400. getObjectById: function ( id, recursive ) {
  4401. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4402. var child = this.children[ i ];
  4403. if ( child.id === id ) {
  4404. return child;
  4405. }
  4406. if ( recursive === true ) {
  4407. child = child.getObjectById( id, recursive );
  4408. if ( child !== undefined ) {
  4409. return child;
  4410. }
  4411. }
  4412. }
  4413. return undefined;
  4414. },
  4415. getObjectByName: function ( name, recursive ) {
  4416. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4417. var child = this.children[ i ];
  4418. if ( child.name === name ) {
  4419. return child;
  4420. }
  4421. if ( recursive === true ) {
  4422. child = child.getObjectByName( name, recursive );
  4423. if ( child !== undefined ) {
  4424. return child;
  4425. }
  4426. }
  4427. }
  4428. return undefined;
  4429. },
  4430. getChildByName: function ( name, recursive ) {
  4431. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4432. return this.getObjectByName( name, recursive );
  4433. },
  4434. updateMatrix: function () {
  4435. this.matrix.compose( this.position, this.quaternion, this.scale );
  4436. this.matrixWorldNeedsUpdate = true;
  4437. },
  4438. updateMatrixWorld: function ( force ) {
  4439. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4440. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4441. if ( this.parent === undefined ) {
  4442. this.matrixWorld.copy( this.matrix );
  4443. } else {
  4444. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4445. }
  4446. this.matrixWorldNeedsUpdate = false;
  4447. force = true;
  4448. }
  4449. // update children
  4450. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4451. this.children[ i ].updateMatrixWorld( force );
  4452. }
  4453. },
  4454. clone: function ( object, recursive ) {
  4455. if ( object === undefined ) object = new THREE.Object3D();
  4456. if ( recursive === undefined ) recursive = true;
  4457. object.name = this.name;
  4458. object.up.copy( this.up );
  4459. object.position.copy( this.position );
  4460. object.quaternion.copy( this.quaternion );
  4461. object.scale.copy( this.scale );
  4462. object.renderDepth = this.renderDepth;
  4463. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4464. object.matrix.copy( this.matrix );
  4465. object.matrixWorld.copy( this.matrixWorld );
  4466. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4467. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4468. object.visible = this.visible;
  4469. object.castShadow = this.castShadow;
  4470. object.receiveShadow = this.receiveShadow;
  4471. object.frustumCulled = this.frustumCulled;
  4472. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4473. if ( recursive === true ) {
  4474. for ( var i = 0; i < this.children.length; i ++ ) {
  4475. var child = this.children[ i ];
  4476. object.add( child.clone() );
  4477. }
  4478. }
  4479. return object;
  4480. }
  4481. };
  4482. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4483. THREE.Object3DIdCount = 0;
  4484. /**
  4485. * @author mrdoob / http://mrdoob.com/
  4486. * @author supereggbert / http://www.paulbrunt.co.uk/
  4487. * @author julianwa / https://github.com/julianwa
  4488. */
  4489. THREE.Projector = function () {
  4490. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4491. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4492. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4493. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4494. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4495. _renderData = { objects: [], lights: [], elements: [] },
  4496. _vA = new THREE.Vector3(),
  4497. _vB = new THREE.Vector3(),
  4498. _vC = new THREE.Vector3(),
  4499. _vector3 = new THREE.Vector3(),
  4500. _vector4 = new THREE.Vector4(),
  4501. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4502. _boundingBox = new THREE.Box3(),
  4503. _points3 = new Array( 3 ),
  4504. _points4 = new Array( 4 ),
  4505. _viewMatrix = new THREE.Matrix4(),
  4506. _viewProjectionMatrix = new THREE.Matrix4(),
  4507. _modelMatrix,
  4508. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4509. _normalMatrix = new THREE.Matrix3(),
  4510. _frustum = new THREE.Frustum(),
  4511. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4512. _clippedVertex2PositionScreen = new THREE.Vector4();
  4513. this.projectVector = function ( vector, camera ) {
  4514. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4515. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4516. return vector.applyProjection( _viewProjectionMatrix );
  4517. };
  4518. this.unprojectVector = function () {
  4519. var projectionMatrixInverse = new THREE.Matrix4();
  4520. return function ( vector, camera ) {
  4521. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4522. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4523. return vector.applyProjection( _viewProjectionMatrix );
  4524. };
  4525. }();
  4526. this.pickingRay = function ( vector, camera ) {
  4527. // set two vectors with opposing z values
  4528. vector.z = -1.0;
  4529. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4530. this.unprojectVector( vector, camera );
  4531. this.unprojectVector( end, camera );
  4532. // find direction from vector to end
  4533. end.sub( vector ).normalize();
  4534. return new THREE.Raycaster( vector, end );
  4535. };
  4536. var projectObject = function ( object ) {
  4537. if ( object.visible === false ) return;
  4538. if ( object instanceof THREE.Light ) {
  4539. _renderData.lights.push( object );
  4540. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4541. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4542. _object = getNextObjectInPool();
  4543. _object.id = object.id;
  4544. _object.object = object;
  4545. if ( object.renderDepth !== null ) {
  4546. _object.z = object.renderDepth;
  4547. } else {
  4548. _vector3.setFromMatrixPosition( object.matrixWorld );
  4549. _vector3.applyProjection( _viewProjectionMatrix );
  4550. _object.z = _vector3.z;
  4551. }
  4552. _renderData.objects.push( _object );
  4553. }
  4554. }
  4555. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4556. projectObject( object.children[ i ] );
  4557. }
  4558. };
  4559. var projectGraph = function ( root, sortObjects ) {
  4560. _objectCount = 0;
  4561. _renderData.objects.length = 0;
  4562. _renderData.lights.length = 0;
  4563. projectObject( root );
  4564. if ( sortObjects === true ) {
  4565. _renderData.objects.sort( painterSort );
  4566. }
  4567. };
  4568. var RenderList = function () {
  4569. var normals = [];
  4570. var uvs = [];
  4571. var object = null;
  4572. var material = null;
  4573. var normalMatrix = new THREE.Matrix3();
  4574. var setObject = function ( value ) {
  4575. object = value;
  4576. material = object.material;
  4577. normalMatrix.getNormalMatrix( object.matrixWorld );
  4578. normals.length = 0;
  4579. uvs.length = 0;
  4580. };
  4581. var projectVertex = function ( vertex ) {
  4582. var position = vertex.position;
  4583. var positionWorld = vertex.positionWorld;
  4584. var positionScreen = vertex.positionScreen;
  4585. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4586. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4587. var invW = 1 / positionScreen.w;
  4588. positionScreen.x *= invW;
  4589. positionScreen.y *= invW;
  4590. positionScreen.z *= invW;
  4591. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4592. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4593. positionScreen.z >= -1 && positionScreen.z <= 1;
  4594. };
  4595. var pushVertex = function ( x, y, z ) {
  4596. _vertex = getNextVertexInPool();
  4597. _vertex.position.set( x, y, z );
  4598. projectVertex( _vertex );
  4599. };
  4600. var pushNormal = function ( x, y, z ) {
  4601. normals.push( x, y, z );
  4602. };
  4603. var pushUv = function ( x, y ) {
  4604. uvs.push( x, y );
  4605. };
  4606. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4607. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4608. _points3[ 0 ] = v1.positionScreen;
  4609. _points3[ 1 ] = v2.positionScreen;
  4610. _points3[ 2 ] = v3.positionScreen;
  4611. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4612. };
  4613. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4614. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4615. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4616. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4617. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4618. };
  4619. var pushLine = function ( a, b ) {
  4620. var v1 = _vertexPool[ a ];
  4621. var v2 = _vertexPool[ b ];
  4622. _line = getNextLineInPool();
  4623. _line.id = object.id;
  4624. _line.v1.copy( v1 );
  4625. _line.v2.copy( v2 );
  4626. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4627. _line.material = object.material;
  4628. _renderData.elements.push( _line );
  4629. };
  4630. var pushTriangle = function ( a, b, c ) {
  4631. var v1 = _vertexPool[ a ];
  4632. var v2 = _vertexPool[ b ];
  4633. var v3 = _vertexPool[ c ];
  4634. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4635. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4636. _face = getNextFaceInPool();
  4637. _face.id = object.id;
  4638. _face.v1.copy( v1 );
  4639. _face.v2.copy( v2 );
  4640. _face.v3.copy( v3 );
  4641. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4642. for ( var i = 0; i < 3; i ++ ) {
  4643. var offset = arguments[ i ] * 3;
  4644. var normal = _face.vertexNormalsModel[ i ];
  4645. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4646. normal.applyMatrix3( normalMatrix ).normalize();
  4647. var offset2 = arguments[ i ] * 2;
  4648. var uv = _face.uvs[ i ];
  4649. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4650. }
  4651. _face.vertexNormalsLength = 3;
  4652. _face.material = object.material;
  4653. _renderData.elements.push( _face );
  4654. }
  4655. };
  4656. return {
  4657. setObject: setObject,
  4658. projectVertex: projectVertex,
  4659. checkTriangleVisibility: checkTriangleVisibility,
  4660. checkBackfaceCulling: checkBackfaceCulling,
  4661. pushVertex: pushVertex,
  4662. pushNormal: pushNormal,
  4663. pushUv: pushUv,
  4664. pushLine: pushLine,
  4665. pushTriangle: pushTriangle
  4666. }
  4667. };
  4668. var renderList = new RenderList();
  4669. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4670. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4671. isFaceMaterial, objectMaterials;
  4672. _faceCount = 0;
  4673. _lineCount = 0;
  4674. _spriteCount = 0;
  4675. _renderData.elements.length = 0;
  4676. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4677. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4678. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4679. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4680. _frustum.setFromMatrix( _viewProjectionMatrix );
  4681. projectGraph( scene, sortObjects );
  4682. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4683. object = _renderData.objects[ o ].object;
  4684. geometry = object.geometry;
  4685. renderList.setObject( object );
  4686. _modelMatrix = object.matrixWorld;
  4687. _vertexCount = 0;
  4688. if ( object instanceof THREE.Mesh ) {
  4689. if ( geometry instanceof THREE.BufferGeometry ) {
  4690. var attributes = geometry.attributes;
  4691. var offsets = geometry.offsets;
  4692. if ( attributes.position === undefined ) continue;
  4693. var positions = attributes.position.array;
  4694. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4695. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4696. }
  4697. if ( attributes.normal !== undefined ) {
  4698. var normals = attributes.normal.array;
  4699. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4700. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4701. }
  4702. }
  4703. if ( attributes.uv !== undefined ) {
  4704. var uvs = attributes.uv.array;
  4705. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4706. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4707. }
  4708. }
  4709. if ( attributes.index !== undefined ) {
  4710. var indices = attributes.index.array;
  4711. if ( offsets.length > 0 ) {
  4712. for ( var o = 0; o < offsets.length; o ++ ) {
  4713. var offset = offsets[ o ];
  4714. var index = offset.index;
  4715. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4716. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4717. }
  4718. }
  4719. } else {
  4720. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4721. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4722. }
  4723. }
  4724. } else {
  4725. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4726. renderList.pushTriangle( i, i + 1, i + 2 );
  4727. }
  4728. }
  4729. } else if ( geometry instanceof THREE.Geometry ) {
  4730. vertices = geometry.vertices;
  4731. faces = geometry.faces;
  4732. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4733. _normalMatrix.getNormalMatrix( _modelMatrix );
  4734. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4735. objectMaterials = isFaceMaterial === true ? object.material : null;
  4736. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4737. var vertex = vertices[ v ];
  4738. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4739. }
  4740. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4741. face = faces[ f ];
  4742. var material = isFaceMaterial === true
  4743. ? objectMaterials.materials[ face.materialIndex ]
  4744. : object.material;
  4745. if ( material === undefined ) continue;
  4746. var side = material.side;
  4747. var v1 = _vertexPool[ face.a ];
  4748. var v2 = _vertexPool[ face.b ];
  4749. var v3 = _vertexPool[ face.c ];
  4750. if ( material.morphTargets === true ) {
  4751. var morphTargets = geometry.morphTargets;
  4752. var morphInfluences = object.morphTargetInfluences;
  4753. var v1p = v1.position;
  4754. var v2p = v2.position;
  4755. var v3p = v3.position;
  4756. _vA.set( 0, 0, 0 );
  4757. _vB.set( 0, 0, 0 );
  4758. _vC.set( 0, 0, 0 );
  4759. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4760. var influence = morphInfluences[ t ];
  4761. if ( influence === 0 ) continue;
  4762. var targets = morphTargets[ t ].vertices;
  4763. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4764. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4765. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4766. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4767. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4768. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4769. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4770. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4771. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4772. }
  4773. v1.position.add( _vA );
  4774. v2.position.add( _vB );
  4775. v3.position.add( _vC );
  4776. renderList.projectVertex( v1 );
  4777. renderList.projectVertex( v2 );
  4778. renderList.projectVertex( v3 );
  4779. }
  4780. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  4781. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  4782. if ( side !== THREE.DoubleSide ) {
  4783. if ( side === THREE.FrontSide && visible === false ) continue;
  4784. if ( side === THREE.BackSide && visible === true ) continue;
  4785. }
  4786. _face = getNextFaceInPool();
  4787. _face.id = object.id;
  4788. _face.v1.copy( v1 );
  4789. _face.v2.copy( v2 );
  4790. _face.v3.copy( v3 );
  4791. _face.normalModel.copy( face.normal );
  4792. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4793. _face.normalModel.negate();
  4794. }
  4795. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4796. faceVertexNormals = face.vertexNormals;
  4797. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4798. var normalModel = _face.vertexNormalsModel[ n ];
  4799. normalModel.copy( faceVertexNormals[ n ] );
  4800. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4801. normalModel.negate();
  4802. }
  4803. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4804. }
  4805. _face.vertexNormalsLength = faceVertexNormals.length;
  4806. var vertexUvs = faceVertexUvs[ f ];
  4807. if ( vertexUvs !== undefined ) {
  4808. for ( var u = 0; u < 3; u ++ ) {
  4809. _face.uvs[ u ].copy( vertexUvs[ u ] );
  4810. }
  4811. }
  4812. _face.color = face.color;
  4813. _face.material = material;
  4814. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4815. _renderData.elements.push( _face );
  4816. }
  4817. }
  4818. } else if ( object instanceof THREE.Line ) {
  4819. if ( geometry instanceof THREE.BufferGeometry ) {
  4820. var attributes = geometry.attributes;
  4821. if ( attributes.position !== undefined ) {
  4822. var positions = attributes.position.array;
  4823. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4824. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4825. }
  4826. if ( attributes.index !== undefined ) {
  4827. var indices = attributes.index.array;
  4828. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4829. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  4830. }
  4831. } else {
  4832. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  4833. renderList.pushLine( i, i + 1 );
  4834. }
  4835. }
  4836. }
  4837. } else if ( geometry instanceof THREE.Geometry ) {
  4838. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4839. vertices = object.geometry.vertices;
  4840. if ( vertices.length === 0 ) continue;
  4841. v1 = getNextVertexInPool();
  4842. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4843. // Handle LineStrip and LinePieces
  4844. var step = object.type === THREE.LinePieces ? 2 : 1;
  4845. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  4846. v1 = getNextVertexInPool();
  4847. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4848. if ( ( v + 1 ) % step > 0 ) continue;
  4849. v2 = _vertexPool[ _vertexCount - 2 ];
  4850. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4851. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4852. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4853. // Perform the perspective divide
  4854. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4855. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4856. _line = getNextLineInPool();
  4857. _line.id = object.id;
  4858. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4859. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4860. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4861. _line.material = object.material;
  4862. if ( object.material.vertexColors === THREE.VertexColors ) {
  4863. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4864. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4865. }
  4866. _renderData.elements.push( _line );
  4867. }
  4868. }
  4869. }
  4870. } else if ( object instanceof THREE.Sprite ) {
  4871. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4872. _vector4.applyMatrix4( _viewProjectionMatrix );
  4873. var invW = 1 / _vector4.w;
  4874. _vector4.z *= invW;
  4875. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4876. _sprite = getNextSpriteInPool();
  4877. _sprite.id = object.id;
  4878. _sprite.x = _vector4.x * invW;
  4879. _sprite.y = _vector4.y * invW;
  4880. _sprite.z = _vector4.z;
  4881. _sprite.object = object;
  4882. _sprite.rotation = object.rotation;
  4883. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4884. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4885. _sprite.material = object.material;
  4886. _renderData.elements.push( _sprite );
  4887. }
  4888. }
  4889. }
  4890. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4891. return _renderData;
  4892. };
  4893. // Pools
  4894. function getNextObjectInPool() {
  4895. if ( _objectCount === _objectPoolLength ) {
  4896. var object = new THREE.RenderableObject();
  4897. _objectPool.push( object );
  4898. _objectPoolLength ++;
  4899. _objectCount ++;
  4900. return object;
  4901. }
  4902. return _objectPool[ _objectCount ++ ];
  4903. }
  4904. function getNextVertexInPool() {
  4905. if ( _vertexCount === _vertexPoolLength ) {
  4906. var vertex = new THREE.RenderableVertex();
  4907. _vertexPool.push( vertex );
  4908. _vertexPoolLength ++;
  4909. _vertexCount ++;
  4910. return vertex;
  4911. }
  4912. return _vertexPool[ _vertexCount ++ ];
  4913. }
  4914. function getNextFaceInPool() {
  4915. if ( _faceCount === _facePoolLength ) {
  4916. var face = new THREE.RenderableFace();
  4917. _facePool.push( face );
  4918. _facePoolLength ++;
  4919. _faceCount ++;
  4920. return face;
  4921. }
  4922. return _facePool[ _faceCount ++ ];
  4923. }
  4924. function getNextLineInPool() {
  4925. if ( _lineCount === _linePoolLength ) {
  4926. var line = new THREE.RenderableLine();
  4927. _linePool.push( line );
  4928. _linePoolLength ++;
  4929. _lineCount ++
  4930. return line;
  4931. }
  4932. return _linePool[ _lineCount ++ ];
  4933. }
  4934. function getNextSpriteInPool() {
  4935. if ( _spriteCount === _spritePoolLength ) {
  4936. var sprite = new THREE.RenderableSprite();
  4937. _spritePool.push( sprite );
  4938. _spritePoolLength ++;
  4939. _spriteCount ++
  4940. return sprite;
  4941. }
  4942. return _spritePool[ _spriteCount ++ ];
  4943. }
  4944. //
  4945. function painterSort( a, b ) {
  4946. if ( a.z !== b.z ) {
  4947. return b.z - a.z;
  4948. } else if ( a.id !== b.id ) {
  4949. return a.id - b.id;
  4950. } else {
  4951. return 0;
  4952. }
  4953. }
  4954. function clipLine( s1, s2 ) {
  4955. var alpha1 = 0, alpha2 = 1,
  4956. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4957. // Z = -1 and Z = +1, respectively.
  4958. bc1near = s1.z + s1.w,
  4959. bc2near = s2.z + s2.w,
  4960. bc1far = - s1.z + s1.w,
  4961. bc2far = - s2.z + s2.w;
  4962. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4963. // Both vertices lie entirely within all clip planes.
  4964. return true;
  4965. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4966. // Both vertices lie entirely outside one of the clip planes.
  4967. return false;
  4968. } else {
  4969. // The line segment spans at least one clip plane.
  4970. if ( bc1near < 0 ) {
  4971. // v1 lies outside the near plane, v2 inside
  4972. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4973. } else if ( bc2near < 0 ) {
  4974. // v2 lies outside the near plane, v1 inside
  4975. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4976. }
  4977. if ( bc1far < 0 ) {
  4978. // v1 lies outside the far plane, v2 inside
  4979. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4980. } else if ( bc2far < 0 ) {
  4981. // v2 lies outside the far plane, v2 inside
  4982. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4983. }
  4984. if ( alpha2 < alpha1 ) {
  4985. // The line segment spans two boundaries, but is outside both of them.
  4986. // (This can't happen when we're only clipping against just near/far but good
  4987. // to leave the check here for future usage if other clip planes are added.)
  4988. return false;
  4989. } else {
  4990. // Update the s1 and s2 vertices to match the clipped line segment.
  4991. s1.lerp( s2, alpha1 );
  4992. s2.lerp( s1, 1 - alpha2 );
  4993. return true;
  4994. }
  4995. }
  4996. }
  4997. };
  4998. /**
  4999. * @author mrdoob / http://mrdoob.com/
  5000. * @author alteredq / http://alteredqualia.com/
  5001. */
  5002. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5003. this.a = a;
  5004. this.b = b;
  5005. this.c = c;
  5006. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5007. this.vertexNormals = normal instanceof Array ? normal : [];
  5008. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5009. this.vertexColors = color instanceof Array ? color : [];
  5010. this.vertexTangents = [];
  5011. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5012. };
  5013. THREE.Face3.prototype = {
  5014. constructor: THREE.Face3,
  5015. clone: function () {
  5016. var face = new THREE.Face3( this.a, this.b, this.c );
  5017. face.normal.copy( this.normal );
  5018. face.color.copy( this.color );
  5019. face.materialIndex = this.materialIndex;
  5020. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  5021. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5022. }
  5023. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  5024. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5025. }
  5026. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  5027. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5028. }
  5029. return face;
  5030. }
  5031. };
  5032. /**
  5033. * @author mrdoob / http://mrdoob.com/
  5034. */
  5035. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5036. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5037. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5038. };
  5039. /**
  5040. * @author mrdoob / http://mrdoob.com/
  5041. */
  5042. THREE.BufferAttribute = function ( array, itemSize ) {
  5043. this.array = array;
  5044. this.itemSize = itemSize;
  5045. };
  5046. THREE.BufferAttribute.prototype = {
  5047. constructor: THREE.BufferAttribute,
  5048. get length () {
  5049. return this.array.length;
  5050. },
  5051. set: function ( value ) {
  5052. this.array.set( value );
  5053. return this;
  5054. },
  5055. setX: function ( index, x ) {
  5056. this.array[ index * this.itemSize ] = x;
  5057. return this;
  5058. },
  5059. setY: function ( index, y ) {
  5060. this.array[ index * this.itemSize + 1 ] = y;
  5061. return this;
  5062. },
  5063. setZ: function ( index, z ) {
  5064. this.array[ index * this.itemSize + 2 ] = z;
  5065. return this;
  5066. },
  5067. setXY: function ( index, x, y ) {
  5068. index *= this.itemSize;
  5069. this.array[ index ] = x;
  5070. this.array[ index + 1 ] = y;
  5071. return this;
  5072. },
  5073. setXYZ: function ( index, x, y, z ) {
  5074. index *= this.itemSize;
  5075. this.array[ index ] = x;
  5076. this.array[ index + 1 ] = y;
  5077. this.array[ index + 2 ] = z;
  5078. return this;
  5079. },
  5080. setXYZW: function ( index, x, y, z, w ) {
  5081. index *= this.itemSize;
  5082. this.array[ index ] = x;
  5083. this.array[ index + 1 ] = y;
  5084. this.array[ index + 2 ] = z;
  5085. this.array[ index + 3 ] = w;
  5086. return this;
  5087. }
  5088. };
  5089. //
  5090. THREE.Int8Attribute = function ( data, itemSize ) {
  5091. console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5092. return new THREE.BufferAttribute( data, itemSize );
  5093. };
  5094. THREE.Uint8Attribute = function ( data, itemSize ) {
  5095. console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5096. return new THREE.BufferAttribute( data, itemSize );
  5097. };
  5098. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  5099. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5100. return new THREE.BufferAttribute( data, itemSize );
  5101. };
  5102. THREE.Int16Attribute = function ( data, itemSize ) {
  5103. console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5104. return new THREE.BufferAttribute( data, itemSize );
  5105. };
  5106. THREE.Uint16Attribute = function ( data, itemSize ) {
  5107. console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5108. return new THREE.BufferAttribute( data, itemSize );
  5109. };
  5110. THREE.Int32Attribute = function ( data, itemSize ) {
  5111. console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5112. return new THREE.BufferAttribute( data, itemSize );
  5113. };
  5114. THREE.Uint32Attribute = function ( data, itemSize ) {
  5115. console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5116. return new THREE.BufferAttribute( data, itemSize );
  5117. };
  5118. THREE.Float32Attribute = function ( data, itemSize ) {
  5119. console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5120. return new THREE.BufferAttribute( data, itemSize );
  5121. };
  5122. THREE.Float64Attribute = function ( data, itemSize ) {
  5123. console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5124. return new THREE.BufferAttribute( data, itemSize );
  5125. };
  5126. /**
  5127. * @author alteredq / http://alteredqualia.com/
  5128. */
  5129. THREE.BufferGeometry = function () {
  5130. this.id = THREE.GeometryIdCount ++;
  5131. this.uuid = THREE.Math.generateUUID();
  5132. this.name = '';
  5133. this.attributes = {};
  5134. this.drawcalls = [];
  5135. this.offsets = this.drawcalls; // backwards compatibility
  5136. this.boundingBox = null;
  5137. this.boundingSphere = null;
  5138. };
  5139. THREE.BufferGeometry.prototype = {
  5140. constructor: THREE.BufferGeometry,
  5141. addAttribute: function ( name, attribute ) {
  5142. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5143. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5144. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5145. return;
  5146. }
  5147. this.attributes[ name ] = attribute;
  5148. },
  5149. getAttribute: function ( name ) {
  5150. return this.attributes[ name ];
  5151. },
  5152. addDrawCall: function ( start, count, indexOffset ) {
  5153. this.drawcalls.push( {
  5154. start: start,
  5155. count: count,
  5156. index: indexOffset !== undefined ? indexOffset : 0
  5157. } );
  5158. },
  5159. applyMatrix: function ( matrix ) {
  5160. var position = this.attributes.position;
  5161. if ( position !== undefined ) {
  5162. matrix.applyToVector3Array( position.array );
  5163. position.needsUpdate = true;
  5164. }
  5165. var normal = this.attributes.normal;
  5166. if ( normal !== undefined ) {
  5167. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5168. normalMatrix.applyToVector3Array( normal.array );
  5169. normal.needsUpdate = true;
  5170. }
  5171. },
  5172. computeBoundingBox: function () {
  5173. if ( this.boundingBox === null ) {
  5174. this.boundingBox = new THREE.Box3();
  5175. }
  5176. var positions = this.attributes[ "position" ].array;
  5177. if ( positions ) {
  5178. var bb = this.boundingBox;
  5179. if( positions.length >= 3 ) {
  5180. bb.min.x = bb.max.x = positions[ 0 ];
  5181. bb.min.y = bb.max.y = positions[ 1 ];
  5182. bb.min.z = bb.max.z = positions[ 2 ];
  5183. }
  5184. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5185. var x = positions[ i ];
  5186. var y = positions[ i + 1 ];
  5187. var z = positions[ i + 2 ];
  5188. // bounding box
  5189. if ( x < bb.min.x ) {
  5190. bb.min.x = x;
  5191. } else if ( x > bb.max.x ) {
  5192. bb.max.x = x;
  5193. }
  5194. if ( y < bb.min.y ) {
  5195. bb.min.y = y;
  5196. } else if ( y > bb.max.y ) {
  5197. bb.max.y = y;
  5198. }
  5199. if ( z < bb.min.z ) {
  5200. bb.min.z = z;
  5201. } else if ( z > bb.max.z ) {
  5202. bb.max.z = z;
  5203. }
  5204. }
  5205. }
  5206. if ( positions === undefined || positions.length === 0 ) {
  5207. this.boundingBox.min.set( 0, 0, 0 );
  5208. this.boundingBox.max.set( 0, 0, 0 );
  5209. }
  5210. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5211. console.error( 'THREE.BufferGeometry.computeBoundingBox()', 'Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5212. }
  5213. },
  5214. computeBoundingSphere: function () {
  5215. var box = new THREE.Box3();
  5216. var vector = new THREE.Vector3();
  5217. return function () {
  5218. if ( this.boundingSphere === null ) {
  5219. this.boundingSphere = new THREE.Sphere();
  5220. }
  5221. var positions = this.attributes[ "position" ].array;
  5222. if ( positions ) {
  5223. box.makeEmpty();
  5224. var center = this.boundingSphere.center;
  5225. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5226. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5227. box.addPoint( vector );
  5228. }
  5229. box.center( center );
  5230. // hoping to find a boundingSphere with a radius smaller than the
  5231. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5232. var maxRadiusSq = 0;
  5233. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5234. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5235. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5236. }
  5237. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5238. if ( isNaN( this.boundingSphere.radius ) ) {
  5239. console.error( 'THREE.BufferGeometry.computeBoundingSphere()', 'Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5240. }
  5241. }
  5242. }
  5243. }(),
  5244. computeFaceNormals: function () {
  5245. // backwards compatibility
  5246. },
  5247. computeVertexNormals: function () {
  5248. if ( this.attributes[ "position" ] ) {
  5249. var i, il;
  5250. var j, jl;
  5251. var nVertexElements = this.attributes[ "position" ].array.length;
  5252. if ( this.attributes[ "normal" ] === undefined ) {
  5253. this.attributes[ "normal" ] = {
  5254. itemSize: 3,
  5255. array: new Float32Array( nVertexElements )
  5256. };
  5257. } else {
  5258. // reset existing normals to zero
  5259. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5260. this.attributes[ "normal" ].array[ i ] = 0;
  5261. }
  5262. }
  5263. var positions = this.attributes[ "position" ].array;
  5264. var normals = this.attributes[ "normal" ].array;
  5265. var vA, vB, vC, x, y, z,
  5266. pA = new THREE.Vector3(),
  5267. pB = new THREE.Vector3(),
  5268. pC = new THREE.Vector3(),
  5269. cb = new THREE.Vector3(),
  5270. ab = new THREE.Vector3();
  5271. // indexed elements
  5272. if ( this.attributes[ "index" ] ) {
  5273. var indices = this.attributes[ "index" ].array;
  5274. var offsets = (this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ]);
  5275. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5276. var start = offsets[ j ].start;
  5277. var count = offsets[ j ].count;
  5278. var index = offsets[ j ].index;
  5279. for ( i = start, il = start + count; i < il; i += 3 ) {
  5280. vA = index + indices[ i ];
  5281. vB = index + indices[ i + 1 ];
  5282. vC = index + indices[ i + 2 ];
  5283. x = positions[ vA * 3 ];
  5284. y = positions[ vA * 3 + 1 ];
  5285. z = positions[ vA * 3 + 2 ];
  5286. pA.set( x, y, z );
  5287. x = positions[ vB * 3 ];
  5288. y = positions[ vB * 3 + 1 ];
  5289. z = positions[ vB * 3 + 2 ];
  5290. pB.set( x, y, z );
  5291. x = positions[ vC * 3 ];
  5292. y = positions[ vC * 3 + 1 ];
  5293. z = positions[ vC * 3 + 2 ];
  5294. pC.set( x, y, z );
  5295. cb.subVectors( pC, pB );
  5296. ab.subVectors( pA, pB );
  5297. cb.cross( ab );
  5298. normals[ vA * 3 ] += cb.x;
  5299. normals[ vA * 3 + 1 ] += cb.y;
  5300. normals[ vA * 3 + 2 ] += cb.z;
  5301. normals[ vB * 3 ] += cb.x;
  5302. normals[ vB * 3 + 1 ] += cb.y;
  5303. normals[ vB * 3 + 2 ] += cb.z;
  5304. normals[ vC * 3 ] += cb.x;
  5305. normals[ vC * 3 + 1 ] += cb.y;
  5306. normals[ vC * 3 + 2 ] += cb.z;
  5307. }
  5308. }
  5309. // non-indexed elements (unconnected triangle soup)
  5310. } else {
  5311. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5312. x = positions[ i ];
  5313. y = positions[ i + 1 ];
  5314. z = positions[ i + 2 ];
  5315. pA.set( x, y, z );
  5316. x = positions[ i + 3 ];
  5317. y = positions[ i + 4 ];
  5318. z = positions[ i + 5 ];
  5319. pB.set( x, y, z );
  5320. x = positions[ i + 6 ];
  5321. y = positions[ i + 7 ];
  5322. z = positions[ i + 8 ];
  5323. pC.set( x, y, z );
  5324. cb.subVectors( pC, pB );
  5325. ab.subVectors( pA, pB );
  5326. cb.cross( ab );
  5327. normals[ i ] = cb.x;
  5328. normals[ i + 1 ] = cb.y;
  5329. normals[ i + 2 ] = cb.z;
  5330. normals[ i + 3 ] = cb.x;
  5331. normals[ i + 4 ] = cb.y;
  5332. normals[ i + 5 ] = cb.z;
  5333. normals[ i + 6 ] = cb.x;
  5334. normals[ i + 7 ] = cb.y;
  5335. normals[ i + 8 ] = cb.z;
  5336. }
  5337. }
  5338. this.normalizeNormals();
  5339. this.normalsNeedUpdate = true;
  5340. }
  5341. },
  5342. computeTangents: function () {
  5343. // based on http://www.terathon.com/code/tangent.html
  5344. // (per vertex tangents)
  5345. if ( this.attributes[ "index" ] === undefined ||
  5346. this.attributes[ "position" ] === undefined ||
  5347. this.attributes[ "normal" ] === undefined ||
  5348. this.attributes[ "uv" ] === undefined ) {
  5349. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5350. return;
  5351. }
  5352. var indices = this.attributes[ "index" ].array;
  5353. var positions = this.attributes[ "position" ].array;
  5354. var normals = this.attributes[ "normal" ].array;
  5355. var uvs = this.attributes[ "uv" ].array;
  5356. var nVertices = positions.length / 3;
  5357. if ( this.attributes[ "tangent" ] === undefined ) {
  5358. var nTangentElements = 4 * nVertices;
  5359. this.attributes[ "tangent" ] = {
  5360. itemSize: 4,
  5361. array: new Float32Array( nTangentElements )
  5362. };
  5363. }
  5364. var tangents = this.attributes[ "tangent" ].array;
  5365. var tan1 = [], tan2 = [];
  5366. for ( var k = 0; k < nVertices; k ++ ) {
  5367. tan1[ k ] = new THREE.Vector3();
  5368. tan2[ k ] = new THREE.Vector3();
  5369. }
  5370. var xA, yA, zA,
  5371. xB, yB, zB,
  5372. xC, yC, zC,
  5373. uA, vA,
  5374. uB, vB,
  5375. uC, vC,
  5376. x1, x2, y1, y2, z1, z2,
  5377. s1, s2, t1, t2, r;
  5378. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5379. function handleTriangle( a, b, c ) {
  5380. xA = positions[ a * 3 ];
  5381. yA = positions[ a * 3 + 1 ];
  5382. zA = positions[ a * 3 + 2 ];
  5383. xB = positions[ b * 3 ];
  5384. yB = positions[ b * 3 + 1 ];
  5385. zB = positions[ b * 3 + 2 ];
  5386. xC = positions[ c * 3 ];
  5387. yC = positions[ c * 3 + 1 ];
  5388. zC = positions[ c * 3 + 2 ];
  5389. uA = uvs[ a * 2 ];
  5390. vA = uvs[ a * 2 + 1 ];
  5391. uB = uvs[ b * 2 ];
  5392. vB = uvs[ b * 2 + 1 ];
  5393. uC = uvs[ c * 2 ];
  5394. vC = uvs[ c * 2 + 1 ];
  5395. x1 = xB - xA;
  5396. x2 = xC - xA;
  5397. y1 = yB - yA;
  5398. y2 = yC - yA;
  5399. z1 = zB - zA;
  5400. z2 = zC - zA;
  5401. s1 = uB - uA;
  5402. s2 = uC - uA;
  5403. t1 = vB - vA;
  5404. t2 = vC - vA;
  5405. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5406. sdir.set(
  5407. ( t2 * x1 - t1 * x2 ) * r,
  5408. ( t2 * y1 - t1 * y2 ) * r,
  5409. ( t2 * z1 - t1 * z2 ) * r
  5410. );
  5411. tdir.set(
  5412. ( s1 * x2 - s2 * x1 ) * r,
  5413. ( s1 * y2 - s2 * y1 ) * r,
  5414. ( s1 * z2 - s2 * z1 ) * r
  5415. );
  5416. tan1[ a ].add( sdir );
  5417. tan1[ b ].add( sdir );
  5418. tan1[ c ].add( sdir );
  5419. tan2[ a ].add( tdir );
  5420. tan2[ b ].add( tdir );
  5421. tan2[ c ].add( tdir );
  5422. }
  5423. var i, il;
  5424. var j, jl;
  5425. var iA, iB, iC;
  5426. var offsets = this.offsets;
  5427. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5428. var start = offsets[ j ].start;
  5429. var count = offsets[ j ].count;
  5430. var index = offsets[ j ].index;
  5431. for ( i = start, il = start + count; i < il; i += 3 ) {
  5432. iA = index + indices[ i ];
  5433. iB = index + indices[ i + 1 ];
  5434. iC = index + indices[ i + 2 ];
  5435. handleTriangle( iA, iB, iC );
  5436. }
  5437. }
  5438. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5439. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5440. var w, t, test;
  5441. function handleVertex( v ) {
  5442. n.x = normals[ v * 3 ];
  5443. n.y = normals[ v * 3 + 1 ];
  5444. n.z = normals[ v * 3 + 2 ];
  5445. n2.copy( n );
  5446. t = tan1[ v ];
  5447. // Gram-Schmidt orthogonalize
  5448. tmp.copy( t );
  5449. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5450. // Calculate handedness
  5451. tmp2.crossVectors( n2, t );
  5452. test = tmp2.dot( tan2[ v ] );
  5453. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5454. tangents[ v * 4 ] = tmp.x;
  5455. tangents[ v * 4 + 1 ] = tmp.y;
  5456. tangents[ v * 4 + 2 ] = tmp.z;
  5457. tangents[ v * 4 + 3 ] = w;
  5458. }
  5459. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5460. var start = offsets[ j ].start;
  5461. var count = offsets[ j ].count;
  5462. var index = offsets[ j ].index;
  5463. for ( i = start, il = start + count; i < il; i += 3 ) {
  5464. iA = index + indices[ i ];
  5465. iB = index + indices[ i + 1 ];
  5466. iC = index + indices[ i + 2 ];
  5467. handleVertex( iA );
  5468. handleVertex( iB );
  5469. handleVertex( iC );
  5470. }
  5471. }
  5472. },
  5473. /*
  5474. computeOffsets
  5475. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5476. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5477. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5478. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5479. */
  5480. computeOffsets: function(indexBufferSize) {
  5481. var size = indexBufferSize;
  5482. if(indexBufferSize === undefined)
  5483. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5484. var s = Date.now();
  5485. var indices = this.attributes['index'].array;
  5486. var vertices = this.attributes['position'].array;
  5487. var verticesCount = (vertices.length/3);
  5488. var facesCount = (indices.length/3);
  5489. /*
  5490. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5491. console.log("Faces to process: "+(indices.length/3));
  5492. console.log("Reordering "+verticesCount+" vertices.");
  5493. */
  5494. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5495. var indexPtr = 0;
  5496. var vertexPtr = 0;
  5497. var offsets = [ { start:0, count:0, index:0 } ];
  5498. var offset = offsets[0];
  5499. var duplicatedVertices = 0;
  5500. var newVerticeMaps = 0;
  5501. var faceVertices = new Int32Array(6);
  5502. var vertexMap = new Int32Array( vertices.length );
  5503. var revVertexMap = new Int32Array( vertices.length );
  5504. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5505. /*
  5506. Traverse every face and reorder vertices in the proper offsets of 65k.
  5507. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5508. */
  5509. for(var findex = 0; findex < facesCount; findex++) {
  5510. newVerticeMaps = 0;
  5511. for(var vo = 0; vo < 3; vo++) {
  5512. var vid = indices[ findex*3 + vo ];
  5513. if(vertexMap[vid] == -1) {
  5514. //Unmapped vertice
  5515. faceVertices[vo*2] = vid;
  5516. faceVertices[vo*2+1] = -1;
  5517. newVerticeMaps++;
  5518. } else if(vertexMap[vid] < offset.index) {
  5519. //Reused vertices from previous block (duplicate)
  5520. faceVertices[vo*2] = vid;
  5521. faceVertices[vo*2+1] = -1;
  5522. duplicatedVertices++;
  5523. } else {
  5524. //Reused vertice in the current block
  5525. faceVertices[vo*2] = vid;
  5526. faceVertices[vo*2+1] = vertexMap[vid];
  5527. }
  5528. }
  5529. var faceMax = vertexPtr + newVerticeMaps;
  5530. if(faceMax > (offset.index + size)) {
  5531. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5532. offsets.push(new_offset);
  5533. offset = new_offset;
  5534. //Re-evaluate reused vertices in light of new offset.
  5535. for(var v = 0; v < 6; v+=2) {
  5536. var new_vid = faceVertices[v+1];
  5537. if(new_vid > -1 && new_vid < offset.index)
  5538. faceVertices[v+1] = -1;
  5539. }
  5540. }
  5541. //Reindex the face.
  5542. for(var v = 0; v < 6; v+=2) {
  5543. var vid = faceVertices[v];
  5544. var new_vid = faceVertices[v+1];
  5545. if(new_vid === -1)
  5546. new_vid = vertexPtr++;
  5547. vertexMap[vid] = new_vid;
  5548. revVertexMap[new_vid] = vid;
  5549. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5550. offset.count++;
  5551. }
  5552. }
  5553. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5554. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5555. this.offsets = offsets;
  5556. /*
  5557. var orderTime = Date.now();
  5558. console.log("Reorder time: "+(orderTime-s)+"ms");
  5559. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5560. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5561. console.log("Draw offsets: "+offsets.length);
  5562. */
  5563. return offsets;
  5564. },
  5565. merge: function () {
  5566. console.log( 'BufferGeometry.merge(): TODO' );
  5567. },
  5568. normalizeNormals: function () {
  5569. var normals = this.attributes[ "normal" ].array;
  5570. var x, y, z, n;
  5571. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5572. x = normals[ i ];
  5573. y = normals[ i + 1 ];
  5574. z = normals[ i + 2 ];
  5575. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5576. normals[ i ] *= n;
  5577. normals[ i + 1 ] *= n;
  5578. normals[ i + 2 ] *= n;
  5579. }
  5580. },
  5581. /*
  5582. reoderBuffers:
  5583. Reorder attributes based on a new indexBuffer and indexMap.
  5584. indexBuffer - Uint16Array of the new ordered indices.
  5585. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5586. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5587. */
  5588. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5589. /* Create a copy of all attributes for reordering. */
  5590. var sortedAttributes = {};
  5591. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5592. for( var attr in this.attributes ) {
  5593. if(attr == 'index')
  5594. continue;
  5595. var sourceArray = this.attributes[attr].array;
  5596. for ( var i = 0, il = types.length; i < il; i++ ) {
  5597. var type = types[i];
  5598. if (sourceArray instanceof type) {
  5599. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5600. break;
  5601. }
  5602. }
  5603. }
  5604. /* Move attribute positions based on the new index map */
  5605. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5606. var vid = indexMap[new_vid];
  5607. for ( var attr in this.attributes ) {
  5608. if(attr == 'index')
  5609. continue;
  5610. var attrArray = this.attributes[attr].array;
  5611. var attrSize = this.attributes[attr].itemSize;
  5612. var sortedAttr = sortedAttributes[attr];
  5613. for(var k = 0; k < attrSize; k++)
  5614. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5615. }
  5616. }
  5617. /* Carry the new sorted buffers locally */
  5618. this.attributes['index'].array = indexBuffer;
  5619. for ( var attr in this.attributes ) {
  5620. if(attr == 'index')
  5621. continue;
  5622. this.attributes[attr].array = sortedAttributes[attr];
  5623. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5624. }
  5625. },
  5626. clone: function () {
  5627. var geometry = new THREE.BufferGeometry();
  5628. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5629. for ( var attr in this.attributes ) {
  5630. var sourceAttr = this.attributes[ attr ];
  5631. var sourceArray = sourceAttr.array;
  5632. var attribute = {
  5633. itemSize: sourceAttr.itemSize,
  5634. array: null
  5635. };
  5636. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5637. var type = types[ i ];
  5638. if ( sourceArray instanceof type ) {
  5639. attribute.array = new type( sourceArray );
  5640. break;
  5641. }
  5642. }
  5643. geometry.attributes[ attr ] = attribute;
  5644. }
  5645. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5646. var offset = this.offsets[ i ];
  5647. geometry.offsets.push( {
  5648. start: offset.start,
  5649. index: offset.index,
  5650. count: offset.count
  5651. } );
  5652. }
  5653. return geometry;
  5654. },
  5655. dispose: function () {
  5656. this.dispatchEvent( { type: 'dispose' } );
  5657. }
  5658. };
  5659. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5660. /**
  5661. * @author mrdoob / http://mrdoob.com/
  5662. * @author kile / http://kile.stravaganza.org/
  5663. * @author alteredq / http://alteredqualia.com/
  5664. * @author mikael emtinger / http://gomo.se/
  5665. * @author zz85 / http://www.lab4games.net/zz85/blog
  5666. * @author bhouston / http://exocortex.com
  5667. */
  5668. THREE.Geometry = function () {
  5669. this.id = THREE.GeometryIdCount ++;
  5670. this.uuid = THREE.Math.generateUUID();
  5671. this.name = '';
  5672. this.vertices = [];
  5673. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5674. this.faces = [];
  5675. this.faceVertexUvs = [[]];
  5676. this.morphTargets = [];
  5677. this.morphColors = [];
  5678. this.morphNormals = [];
  5679. this.skinWeights = [];
  5680. this.skinIndices = [];
  5681. this.lineDistances = [];
  5682. this.boundingBox = null;
  5683. this.boundingSphere = null;
  5684. this.hasTangents = false;
  5685. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5686. // update flags
  5687. this.verticesNeedUpdate = false;
  5688. this.elementsNeedUpdate = false;
  5689. this.uvsNeedUpdate = false;
  5690. this.normalsNeedUpdate = false;
  5691. this.tangentsNeedUpdate = false;
  5692. this.colorsNeedUpdate = false;
  5693. this.lineDistancesNeedUpdate = false;
  5694. this.buffersNeedUpdate = false;
  5695. };
  5696. THREE.Geometry.prototype = {
  5697. constructor: THREE.Geometry,
  5698. applyMatrix: function ( matrix ) {
  5699. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5700. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5701. var vertex = this.vertices[ i ];
  5702. vertex.applyMatrix4( matrix );
  5703. }
  5704. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5705. var face = this.faces[ i ];
  5706. face.normal.applyMatrix3( normalMatrix ).normalize();
  5707. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5708. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5709. }
  5710. }
  5711. if ( this.boundingBox instanceof THREE.Box3 ) {
  5712. this.computeBoundingBox();
  5713. }
  5714. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5715. this.computeBoundingSphere();
  5716. }
  5717. },
  5718. computeFaceNormals: function () {
  5719. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5720. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5721. var face = this.faces[ f ];
  5722. var vA = this.vertices[ face.a ];
  5723. var vB = this.vertices[ face.b ];
  5724. var vC = this.vertices[ face.c ];
  5725. cb.subVectors( vC, vB );
  5726. ab.subVectors( vA, vB );
  5727. cb.cross( ab );
  5728. cb.normalize();
  5729. face.normal.copy( cb );
  5730. }
  5731. },
  5732. computeVertexNormals: function ( areaWeighted ) {
  5733. var v, vl, f, fl, face, vertices;
  5734. vertices = new Array( this.vertices.length );
  5735. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5736. vertices[ v ] = new THREE.Vector3();
  5737. }
  5738. if ( areaWeighted ) {
  5739. // vertex normals weighted by triangle areas
  5740. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5741. var vA, vB, vC, vD;
  5742. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5743. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5744. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5745. face = this.faces[ f ];
  5746. vA = this.vertices[ face.a ];
  5747. vB = this.vertices[ face.b ];
  5748. vC = this.vertices[ face.c ];
  5749. cb.subVectors( vC, vB );
  5750. ab.subVectors( vA, vB );
  5751. cb.cross( ab );
  5752. vertices[ face.a ].add( cb );
  5753. vertices[ face.b ].add( cb );
  5754. vertices[ face.c ].add( cb );
  5755. }
  5756. } else {
  5757. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5758. face = this.faces[ f ];
  5759. vertices[ face.a ].add( face.normal );
  5760. vertices[ face.b ].add( face.normal );
  5761. vertices[ face.c ].add( face.normal );
  5762. }
  5763. }
  5764. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5765. vertices[ v ].normalize();
  5766. }
  5767. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5768. face = this.faces[ f ];
  5769. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5770. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5771. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5772. }
  5773. },
  5774. computeMorphNormals: function () {
  5775. var i, il, f, fl, face;
  5776. // save original normals
  5777. // - create temp variables on first access
  5778. // otherwise just copy (for faster repeated calls)
  5779. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5780. face = this.faces[ f ];
  5781. if ( ! face.__originalFaceNormal ) {
  5782. face.__originalFaceNormal = face.normal.clone();
  5783. } else {
  5784. face.__originalFaceNormal.copy( face.normal );
  5785. }
  5786. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5787. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5788. if ( ! face.__originalVertexNormals[ i ] ) {
  5789. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5790. } else {
  5791. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5792. }
  5793. }
  5794. }
  5795. // use temp geometry to compute face and vertex normals for each morph
  5796. var tmpGeo = new THREE.Geometry();
  5797. tmpGeo.faces = this.faces;
  5798. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5799. // create on first access
  5800. if ( ! this.morphNormals[ i ] ) {
  5801. this.morphNormals[ i ] = {};
  5802. this.morphNormals[ i ].faceNormals = [];
  5803. this.morphNormals[ i ].vertexNormals = [];
  5804. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5805. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5806. var faceNormal, vertexNormals;
  5807. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5808. faceNormal = new THREE.Vector3();
  5809. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5810. dstNormalsFace.push( faceNormal );
  5811. dstNormalsVertex.push( vertexNormals );
  5812. }
  5813. }
  5814. var morphNormals = this.morphNormals[ i ];
  5815. // set vertices to morph target
  5816. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5817. // compute morph normals
  5818. tmpGeo.computeFaceNormals();
  5819. tmpGeo.computeVertexNormals();
  5820. // store morph normals
  5821. var faceNormal, vertexNormals;
  5822. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5823. face = this.faces[ f ];
  5824. faceNormal = morphNormals.faceNormals[ f ];
  5825. vertexNormals = morphNormals.vertexNormals[ f ];
  5826. faceNormal.copy( face.normal );
  5827. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5828. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5829. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5830. }
  5831. }
  5832. // restore original normals
  5833. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5834. face = this.faces[ f ];
  5835. face.normal = face.__originalFaceNormal;
  5836. face.vertexNormals = face.__originalVertexNormals;
  5837. }
  5838. },
  5839. computeTangents: function () {
  5840. // based on http://www.terathon.com/code/tangent.html
  5841. // tangents go to vertices
  5842. var f, fl, v, vl, i, il, vertexIndex,
  5843. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5844. x1, x2, y1, y2, z1, z2,
  5845. s1, s2, t1, t2, r, t, test,
  5846. tan1 = [], tan2 = [],
  5847. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5848. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5849. n = new THREE.Vector3(), w;
  5850. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5851. tan1[ v ] = new THREE.Vector3();
  5852. tan2[ v ] = new THREE.Vector3();
  5853. }
  5854. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5855. vA = context.vertices[ a ];
  5856. vB = context.vertices[ b ];
  5857. vC = context.vertices[ c ];
  5858. uvA = uv[ ua ];
  5859. uvB = uv[ ub ];
  5860. uvC = uv[ uc ];
  5861. x1 = vB.x - vA.x;
  5862. x2 = vC.x - vA.x;
  5863. y1 = vB.y - vA.y;
  5864. y2 = vC.y - vA.y;
  5865. z1 = vB.z - vA.z;
  5866. z2 = vC.z - vA.z;
  5867. s1 = uvB.x - uvA.x;
  5868. s2 = uvC.x - uvA.x;
  5869. t1 = uvB.y - uvA.y;
  5870. t2 = uvC.y - uvA.y;
  5871. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5872. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5873. ( t2 * y1 - t1 * y2 ) * r,
  5874. ( t2 * z1 - t1 * z2 ) * r );
  5875. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5876. ( s1 * y2 - s2 * y1 ) * r,
  5877. ( s1 * z2 - s2 * z1 ) * r );
  5878. tan1[ a ].add( sdir );
  5879. tan1[ b ].add( sdir );
  5880. tan1[ c ].add( sdir );
  5881. tan2[ a ].add( tdir );
  5882. tan2[ b ].add( tdir );
  5883. tan2[ c ].add( tdir );
  5884. }
  5885. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5886. face = this.faces[ f ];
  5887. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5888. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5889. }
  5890. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5891. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5892. face = this.faces[ f ];
  5893. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5894. n.copy( face.vertexNormals[ i ] );
  5895. vertexIndex = face[ faceIndex[ i ] ];
  5896. t = tan1[ vertexIndex ];
  5897. // Gram-Schmidt orthogonalize
  5898. tmp.copy( t );
  5899. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5900. // Calculate handedness
  5901. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5902. test = tmp2.dot( tan2[ vertexIndex ] );
  5903. w = (test < 0.0) ? -1.0 : 1.0;
  5904. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5905. }
  5906. }
  5907. this.hasTangents = true;
  5908. },
  5909. computeLineDistances: function ( ) {
  5910. var d = 0;
  5911. var vertices = this.vertices;
  5912. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5913. if ( i > 0 ) {
  5914. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5915. }
  5916. this.lineDistances[ i ] = d;
  5917. }
  5918. },
  5919. computeBoundingBox: function () {
  5920. if ( this.boundingBox === null ) {
  5921. this.boundingBox = new THREE.Box3();
  5922. }
  5923. this.boundingBox.setFromPoints( this.vertices );
  5924. },
  5925. computeBoundingSphere: function () {
  5926. if ( this.boundingSphere === null ) {
  5927. this.boundingSphere = new THREE.Sphere();
  5928. }
  5929. this.boundingSphere.setFromPoints( this.vertices );
  5930. },
  5931. merge: function ( geometry, matrix, materialIndexOffset ) {
  5932. if ( geometry instanceof THREE.Geometry === false ) {
  5933. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5934. return;
  5935. }
  5936. var normalMatrix,
  5937. vertexOffset = this.vertices.length,
  5938. uvPosition = this.faceVertexUvs[ 0 ].length,
  5939. vertices1 = this.vertices,
  5940. vertices2 = geometry.vertices,
  5941. faces1 = this.faces,
  5942. faces2 = geometry.faces,
  5943. uvs1 = this.faceVertexUvs[ 0 ],
  5944. uvs2 = geometry.faceVertexUvs[ 0 ];
  5945. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5946. if ( matrix !== undefined ) {
  5947. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5948. }
  5949. // vertices
  5950. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5951. var vertex = vertices2[ i ];
  5952. var vertexCopy = vertex.clone();
  5953. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5954. vertices1.push( vertexCopy );
  5955. }
  5956. // faces
  5957. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5958. var face = faces2[ i ], faceCopy, normal, color,
  5959. faceVertexNormals = face.vertexNormals,
  5960. faceVertexColors = face.vertexColors;
  5961. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5962. faceCopy.normal.copy( face.normal );
  5963. if ( normalMatrix !== undefined ) {
  5964. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5965. }
  5966. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5967. normal = faceVertexNormals[ j ].clone();
  5968. if ( normalMatrix !== undefined ) {
  5969. normal.applyMatrix3( normalMatrix ).normalize();
  5970. }
  5971. faceCopy.vertexNormals.push( normal );
  5972. }
  5973. faceCopy.color.copy( face.color );
  5974. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5975. color = faceVertexColors[ j ];
  5976. faceCopy.vertexColors.push( color.clone() );
  5977. }
  5978. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5979. faces1.push( faceCopy );
  5980. }
  5981. // uvs
  5982. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5983. var uv = uvs2[ i ], uvCopy = [];
  5984. if ( uv === undefined ) {
  5985. continue;
  5986. }
  5987. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5988. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5989. }
  5990. uvs1.push( uvCopy );
  5991. }
  5992. },
  5993. /*
  5994. * Checks for duplicate vertices with hashmap.
  5995. * Duplicated vertices are removed
  5996. * and faces' vertices are updated.
  5997. */
  5998. mergeVertices: function () {
  5999. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6000. var unique = [], changes = [];
  6001. var v, key;
  6002. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6003. var precision = Math.pow( 10, precisionPoints );
  6004. var i,il, face;
  6005. var indices, k, j, jl, u;
  6006. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6007. v = this.vertices[ i ];
  6008. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6009. if ( verticesMap[ key ] === undefined ) {
  6010. verticesMap[ key ] = i;
  6011. unique.push( this.vertices[ i ] );
  6012. changes[ i ] = unique.length - 1;
  6013. } else {
  6014. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6015. changes[ i ] = changes[ verticesMap[ key ] ];
  6016. }
  6017. };
  6018. // if faces are completely degenerate after merging vertices, we
  6019. // have to remove them from the geometry.
  6020. var faceIndicesToRemove = [];
  6021. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6022. face = this.faces[ i ];
  6023. face.a = changes[ face.a ];
  6024. face.b = changes[ face.b ];
  6025. face.c = changes[ face.c ];
  6026. indices = [ face.a, face.b, face.c ];
  6027. var dupIndex = -1;
  6028. // if any duplicate vertices are found in a Face3
  6029. // we have to remove the face as nothing can be saved
  6030. for ( var n = 0; n < 3; n ++ ) {
  6031. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6032. dupIndex = n;
  6033. faceIndicesToRemove.push( i );
  6034. break;
  6035. }
  6036. }
  6037. }
  6038. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6039. var idx = faceIndicesToRemove[ i ];
  6040. this.faces.splice( idx, 1 );
  6041. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6042. this.faceVertexUvs[ j ].splice( idx, 1 );
  6043. }
  6044. }
  6045. // Use unique set of vertices
  6046. var diff = this.vertices.length - unique.length;
  6047. this.vertices = unique;
  6048. return diff;
  6049. },
  6050. // Geometry splitting
  6051. makeGroups: ( function () {
  6052. var geometryGroupCounter = 0;
  6053. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6054. var f, fl, face, materialIndex,
  6055. groupHash, hash_map = {};
  6056. var numMorphTargets = this.morphTargets.length;
  6057. var numMorphNormals = this.morphNormals.length;
  6058. this.geometryGroups = {};
  6059. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6060. face = this.faces[ f ];
  6061. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6062. if ( ! ( materialIndex in hash_map ) ) {
  6063. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6064. }
  6065. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6066. if ( ! ( groupHash in this.geometryGroups ) ) {
  6067. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6068. }
  6069. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6070. hash_map[ materialIndex ].counter += 1;
  6071. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6072. if ( ! ( groupHash in this.geometryGroups ) ) {
  6073. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6074. }
  6075. }
  6076. this.geometryGroups[ groupHash ].faces3.push( f );
  6077. this.geometryGroups[ groupHash ].vertices += 3;
  6078. }
  6079. this.geometryGroupsList = [];
  6080. for ( var g in this.geometryGroups ) {
  6081. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6082. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6083. }
  6084. };
  6085. } )(),
  6086. clone: function () {
  6087. var geometry = new THREE.Geometry();
  6088. var vertices = this.vertices;
  6089. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6090. geometry.vertices.push( vertices[ i ].clone() );
  6091. }
  6092. var faces = this.faces;
  6093. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6094. geometry.faces.push( faces[ i ].clone() );
  6095. }
  6096. var uvs = this.faceVertexUvs[ 0 ];
  6097. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6098. var uv = uvs[ i ], uvCopy = [];
  6099. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6100. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6101. }
  6102. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6103. }
  6104. return geometry;
  6105. },
  6106. dispose: function () {
  6107. this.dispatchEvent( { type: 'dispose' } );
  6108. }
  6109. };
  6110. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6111. THREE.GeometryIdCount = 0;
  6112. /**
  6113. * @author mrdoob / http://mrdoob.com/
  6114. * @author mikael emtinger / http://gomo.se/
  6115. * @author WestLangley / http://github.com/WestLangley
  6116. */
  6117. THREE.Camera = function () {
  6118. THREE.Object3D.call( this );
  6119. this.matrixWorldInverse = new THREE.Matrix4();
  6120. this.projectionMatrix = new THREE.Matrix4();
  6121. };
  6122. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6123. THREE.Camera.prototype.lookAt = function () {
  6124. // This routine does not support cameras with rotated and/or translated parent(s)
  6125. var m1 = new THREE.Matrix4();
  6126. return function ( vector ) {
  6127. m1.lookAt( this.position, vector, this.up );
  6128. this.quaternion.setFromRotationMatrix( m1 );
  6129. };
  6130. }();
  6131. THREE.Camera.prototype.clone = function (camera) {
  6132. if ( camera === undefined ) camera = new THREE.Camera();
  6133. THREE.Object3D.prototype.clone.call( this, camera );
  6134. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6135. camera.projectionMatrix.copy( this.projectionMatrix );
  6136. return camera;
  6137. };
  6138. /**
  6139. * Camera for rendering cube maps
  6140. * - renders scene into axis-aligned cube
  6141. *
  6142. * @author alteredq / http://alteredqualia.com/
  6143. */
  6144. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6145. THREE.Object3D.call( this );
  6146. var fov = 90, aspect = 1;
  6147. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6148. cameraPX.up.set( 0, -1, 0 );
  6149. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6150. this.add( cameraPX );
  6151. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6152. cameraNX.up.set( 0, -1, 0 );
  6153. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  6154. this.add( cameraNX );
  6155. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6156. cameraPY.up.set( 0, 0, 1 );
  6157. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6158. this.add( cameraPY );
  6159. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6160. cameraNY.up.set( 0, 0, -1 );
  6161. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  6162. this.add( cameraNY );
  6163. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6164. cameraPZ.up.set( 0, -1, 0 );
  6165. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6166. this.add( cameraPZ );
  6167. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6168. cameraNZ.up.set( 0, -1, 0 );
  6169. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  6170. this.add( cameraNZ );
  6171. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6172. this.updateCubeMap = function ( renderer, scene ) {
  6173. var renderTarget = this.renderTarget;
  6174. var generateMipmaps = renderTarget.generateMipmaps;
  6175. renderTarget.generateMipmaps = false;
  6176. renderTarget.activeCubeFace = 0;
  6177. renderer.render( scene, cameraPX, renderTarget );
  6178. renderTarget.activeCubeFace = 1;
  6179. renderer.render( scene, cameraNX, renderTarget );
  6180. renderTarget.activeCubeFace = 2;
  6181. renderer.render( scene, cameraPY, renderTarget );
  6182. renderTarget.activeCubeFace = 3;
  6183. renderer.render( scene, cameraNY, renderTarget );
  6184. renderTarget.activeCubeFace = 4;
  6185. renderer.render( scene, cameraPZ, renderTarget );
  6186. renderTarget.generateMipmaps = generateMipmaps;
  6187. renderTarget.activeCubeFace = 5;
  6188. renderer.render( scene, cameraNZ, renderTarget );
  6189. };
  6190. };
  6191. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6192. /**
  6193. * @author alteredq / http://alteredqualia.com/
  6194. */
  6195. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6196. THREE.Camera.call( this );
  6197. this.left = left;
  6198. this.right = right;
  6199. this.top = top;
  6200. this.bottom = bottom;
  6201. this.near = ( near !== undefined ) ? near : 0.1;
  6202. this.far = ( far !== undefined ) ? far : 2000;
  6203. this.updateProjectionMatrix();
  6204. };
  6205. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6206. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6207. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6208. };
  6209. THREE.OrthographicCamera.prototype.clone = function () {
  6210. var camera = new THREE.OrthographicCamera();
  6211. THREE.Camera.prototype.clone.call( this, camera );
  6212. camera.left = this.left;
  6213. camera.right = this.right;
  6214. camera.top = this.top;
  6215. camera.bottom = this.bottom;
  6216. camera.near = this.near;
  6217. camera.far = this.far;
  6218. return camera;
  6219. };
  6220. /**
  6221. * @author mrdoob / http://mrdoob.com/
  6222. * @author greggman / http://games.greggman.com/
  6223. * @author zz85 / http://www.lab4games.net/zz85/blog
  6224. */
  6225. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6226. THREE.Camera.call( this );
  6227. this.fov = fov !== undefined ? fov : 50;
  6228. this.aspect = aspect !== undefined ? aspect : 1;
  6229. this.near = near !== undefined ? near : 0.1;
  6230. this.far = far !== undefined ? far : 2000;
  6231. this.updateProjectionMatrix();
  6232. };
  6233. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6234. /**
  6235. * Uses Focal Length (in mm) to estimate and set FOV
  6236. * 35mm (fullframe) camera is used if frame size is not specified;
  6237. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6238. */
  6239. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6240. if ( frameHeight === undefined ) frameHeight = 24;
  6241. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6242. this.updateProjectionMatrix();
  6243. }
  6244. /**
  6245. * Sets an offset in a larger frustum. This is useful for multi-window or
  6246. * multi-monitor/multi-machine setups.
  6247. *
  6248. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6249. * the monitors are in grid like this
  6250. *
  6251. * +---+---+---+
  6252. * | A | B | C |
  6253. * +---+---+---+
  6254. * | D | E | F |
  6255. * +---+---+---+
  6256. *
  6257. * then for each monitor you would call it like this
  6258. *
  6259. * var w = 1920;
  6260. * var h = 1080;
  6261. * var fullWidth = w * 3;
  6262. * var fullHeight = h * 2;
  6263. *
  6264. * --A--
  6265. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6266. * --B--
  6267. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6268. * --C--
  6269. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6270. * --D--
  6271. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6272. * --E--
  6273. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6274. * --F--
  6275. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6276. *
  6277. * Note there is no reason monitors have to be the same size or in a grid.
  6278. */
  6279. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6280. this.fullWidth = fullWidth;
  6281. this.fullHeight = fullHeight;
  6282. this.x = x;
  6283. this.y = y;
  6284. this.width = width;
  6285. this.height = height;
  6286. this.updateProjectionMatrix();
  6287. };
  6288. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6289. if ( this.fullWidth ) {
  6290. var aspect = this.fullWidth / this.fullHeight;
  6291. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6292. var bottom = -top;
  6293. var left = aspect * bottom;
  6294. var right = aspect * top;
  6295. var width = Math.abs( right - left );
  6296. var height = Math.abs( top - bottom );
  6297. this.projectionMatrix.makeFrustum(
  6298. left + this.x * width / this.fullWidth,
  6299. left + ( this.x + this.width ) * width / this.fullWidth,
  6300. top - ( this.y + this.height ) * height / this.fullHeight,
  6301. top - this.y * height / this.fullHeight,
  6302. this.near,
  6303. this.far
  6304. );
  6305. } else {
  6306. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6307. }
  6308. };
  6309. THREE.PerspectiveCamera.prototype.clone = function () {
  6310. var camera = new THREE.PerspectiveCamera();
  6311. THREE.Camera.prototype.clone.call( this, camera );
  6312. camera.fov = this.fov;
  6313. camera.aspect = this.aspect;
  6314. camera.near = this.near;
  6315. camera.far = this.far;
  6316. return camera;
  6317. };
  6318. /**
  6319. * @author mrdoob / http://mrdoob.com/
  6320. * @author alteredq / http://alteredqualia.com/
  6321. */
  6322. THREE.Light = function ( color ) {
  6323. THREE.Object3D.call( this );
  6324. this.color = new THREE.Color( color );
  6325. };
  6326. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6327. THREE.Light.prototype.clone = function ( light ) {
  6328. if ( light === undefined ) light = new THREE.Light();
  6329. THREE.Object3D.prototype.clone.call( this, light );
  6330. light.color.copy( this.color );
  6331. return light;
  6332. };
  6333. /**
  6334. * @author mrdoob / http://mrdoob.com/
  6335. */
  6336. THREE.AmbientLight = function ( color ) {
  6337. THREE.Light.call( this, color );
  6338. };
  6339. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6340. THREE.AmbientLight.prototype.clone = function () {
  6341. var light = new THREE.AmbientLight();
  6342. THREE.Light.prototype.clone.call( this, light );
  6343. return light;
  6344. };
  6345. /**
  6346. * @author MPanknin / http://www.redplant.de/
  6347. * @author alteredq / http://alteredqualia.com/
  6348. */
  6349. THREE.AreaLight = function ( color, intensity ) {
  6350. THREE.Light.call( this, color );
  6351. this.normal = new THREE.Vector3( 0, -1, 0 );
  6352. this.right = new THREE.Vector3( 1, 0, 0 );
  6353. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6354. this.width = 1.0;
  6355. this.height = 1.0;
  6356. this.constantAttenuation = 1.5;
  6357. this.linearAttenuation = 0.5;
  6358. this.quadraticAttenuation = 0.1;
  6359. };
  6360. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6361. /**
  6362. * @author mrdoob / http://mrdoob.com/
  6363. * @author alteredq / http://alteredqualia.com/
  6364. */
  6365. THREE.DirectionalLight = function ( color, intensity ) {
  6366. THREE.Light.call( this, color );
  6367. this.position.set( 0, 1, 0 );
  6368. this.target = new THREE.Object3D();
  6369. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6370. this.castShadow = false;
  6371. this.onlyShadow = false;
  6372. //
  6373. this.shadowCameraNear = 50;
  6374. this.shadowCameraFar = 5000;
  6375. this.shadowCameraLeft = -500;
  6376. this.shadowCameraRight = 500;
  6377. this.shadowCameraTop = 500;
  6378. this.shadowCameraBottom = -500;
  6379. this.shadowCameraVisible = false;
  6380. this.shadowBias = 0;
  6381. this.shadowDarkness = 0.5;
  6382. this.shadowMapWidth = 512;
  6383. this.shadowMapHeight = 512;
  6384. //
  6385. this.shadowCascade = false;
  6386. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6387. this.shadowCascadeCount = 2;
  6388. this.shadowCascadeBias = [ 0, 0, 0 ];
  6389. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6390. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6391. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6392. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6393. this.shadowCascadeArray = [];
  6394. //
  6395. this.shadowMap = null;
  6396. this.shadowMapSize = null;
  6397. this.shadowCamera = null;
  6398. this.shadowMatrix = null;
  6399. };
  6400. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6401. THREE.DirectionalLight.prototype.clone = function () {
  6402. var light = new THREE.DirectionalLight();
  6403. THREE.Light.prototype.clone.call( this, light );
  6404. light.target = this.target.clone();
  6405. light.intensity = this.intensity;
  6406. light.castShadow = this.castShadow;
  6407. light.onlyShadow = this.onlyShadow;
  6408. //
  6409. light.shadowCameraNear = this.shadowCameraNear;
  6410. light.shadowCameraFar = this.shadowCameraFar;
  6411. light.shadowCameraLeft = this.shadowCameraLeft;
  6412. light.shadowCameraRight = this.shadowCameraRight;
  6413. light.shadowCameraTop = this.shadowCameraTop;
  6414. light.shadowCameraBottom = this.shadowCameraBottom;
  6415. light.shadowCameraVisible = this.shadowCameraVisible;
  6416. light.shadowBias = this.shadowBias;
  6417. light.shadowDarkness = this.shadowDarkness;
  6418. light.shadowMapWidth = this.shadowMapWidth;
  6419. light.shadowMapHeight = this.shadowMapHeight;
  6420. //
  6421. light.shadowCascade = this.shadowCascade;
  6422. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6423. light.shadowCascadeCount = this.shadowCascadeCount;
  6424. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6425. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6426. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6427. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6428. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6429. return light;
  6430. };
  6431. /**
  6432. * @author alteredq / http://alteredqualia.com/
  6433. */
  6434. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6435. THREE.Light.call( this, skyColor );
  6436. this.position.set( 0, 100, 0 );
  6437. this.groundColor = new THREE.Color( groundColor );
  6438. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6439. };
  6440. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6441. THREE.HemisphereLight.prototype.clone = function () {
  6442. var light = new THREE.HemisphereLight();
  6443. THREE.Light.prototype.clone.call( this, light );
  6444. light.groundColor.copy( this.groundColor );
  6445. light.intensity = this.intensity;
  6446. return light;
  6447. };
  6448. /**
  6449. * @author mrdoob / http://mrdoob.com/
  6450. */
  6451. THREE.PointLight = function ( color, intensity, distance ) {
  6452. THREE.Light.call( this, color );
  6453. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6454. this.distance = ( distance !== undefined ) ? distance : 0;
  6455. };
  6456. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6457. THREE.PointLight.prototype.clone = function () {
  6458. var light = new THREE.PointLight();
  6459. THREE.Light.prototype.clone.call( this, light );
  6460. light.intensity = this.intensity;
  6461. light.distance = this.distance;
  6462. return light;
  6463. };
  6464. /**
  6465. * @author alteredq / http://alteredqualia.com/
  6466. */
  6467. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6468. THREE.Light.call( this, color );
  6469. this.position.set( 0, 1, 0 );
  6470. this.target = new THREE.Object3D();
  6471. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6472. this.distance = ( distance !== undefined ) ? distance : 0;
  6473. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6474. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6475. this.castShadow = false;
  6476. this.onlyShadow = false;
  6477. //
  6478. this.shadowCameraNear = 50;
  6479. this.shadowCameraFar = 5000;
  6480. this.shadowCameraFov = 50;
  6481. this.shadowCameraVisible = false;
  6482. this.shadowBias = 0;
  6483. this.shadowDarkness = 0.5;
  6484. this.shadowMapWidth = 512;
  6485. this.shadowMapHeight = 512;
  6486. //
  6487. this.shadowMap = null;
  6488. this.shadowMapSize = null;
  6489. this.shadowCamera = null;
  6490. this.shadowMatrix = null;
  6491. };
  6492. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6493. THREE.SpotLight.prototype.clone = function () {
  6494. var light = new THREE.SpotLight();
  6495. THREE.Light.prototype.clone.call( this, light );
  6496. light.target = this.target.clone();
  6497. light.intensity = this.intensity;
  6498. light.distance = this.distance;
  6499. light.angle = this.angle;
  6500. light.exponent = this.exponent;
  6501. light.castShadow = this.castShadow;
  6502. light.onlyShadow = this.onlyShadow;
  6503. //
  6504. light.shadowCameraNear = this.shadowCameraNear;
  6505. light.shadowCameraFar = this.shadowCameraFar;
  6506. light.shadowCameraFov = this.shadowCameraFov;
  6507. light.shadowCameraVisible = this.shadowCameraVisible;
  6508. light.shadowBias = this.shadowBias;
  6509. light.shadowDarkness = this.shadowDarkness;
  6510. light.shadowMapWidth = this.shadowMapWidth;
  6511. light.shadowMapHeight = this.shadowMapHeight;
  6512. return light;
  6513. };
  6514. /**
  6515. * @author mrdoob / http://mrdoob.com/
  6516. */
  6517. THREE.Cache = function () {
  6518. this.files = {};
  6519. };
  6520. THREE.Cache.prototype = {
  6521. constructor: THREE.Cache,
  6522. add: function ( key, file ) {
  6523. // console.log( 'THREE.Cache', 'Adding key:', key );
  6524. this.files[ key ] = file;
  6525. },
  6526. get: function ( key ) {
  6527. // console.log( 'THREE.Cache', 'Checking key:', key );
  6528. return this.files[ key ];
  6529. },
  6530. remove: function ( key ) {
  6531. delete this.files[ key ];
  6532. },
  6533. clear: function () {
  6534. this.files = {}
  6535. }
  6536. };
  6537. /**
  6538. * @author alteredq / http://alteredqualia.com/
  6539. */
  6540. THREE.Loader = function ( showStatus ) {
  6541. this.showStatus = showStatus;
  6542. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6543. this.imageLoader = new THREE.ImageLoader();
  6544. this.onLoadStart = function () {};
  6545. this.onLoadProgress = function () {};
  6546. this.onLoadComplete = function () {};
  6547. };
  6548. THREE.Loader.prototype = {
  6549. constructor: THREE.Loader,
  6550. crossOrigin: undefined,
  6551. addStatusElement: function () {
  6552. var e = document.createElement( "div" );
  6553. e.style.position = "absolute";
  6554. e.style.right = "0px";
  6555. e.style.top = "0px";
  6556. e.style.fontSize = "0.8em";
  6557. e.style.textAlign = "left";
  6558. e.style.background = "rgba(0,0,0,0.25)";
  6559. e.style.color = "#fff";
  6560. e.style.width = "120px";
  6561. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6562. e.style.zIndex = 1000;
  6563. e.innerHTML = "Loading ...";
  6564. return e;
  6565. },
  6566. updateProgress: function ( progress ) {
  6567. var message = "Loaded ";
  6568. if ( progress.total ) {
  6569. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6570. } else {
  6571. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6572. }
  6573. this.statusDomElement.innerHTML = message;
  6574. },
  6575. extractUrlBase: function ( url ) {
  6576. var parts = url.split( '/' );
  6577. if ( parts.length === 1 ) return './';
  6578. parts.pop();
  6579. return parts.join( '/' ) + '/';
  6580. },
  6581. initMaterials: function ( materials, texturePath ) {
  6582. var array = [];
  6583. for ( var i = 0; i < materials.length; ++ i ) {
  6584. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6585. }
  6586. return array;
  6587. },
  6588. needsTangents: function ( materials ) {
  6589. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6590. var m = materials[ i ];
  6591. if ( m instanceof THREE.ShaderMaterial ) return true;
  6592. }
  6593. return false;
  6594. },
  6595. createMaterial: function ( m, texturePath ) {
  6596. var scope = this;
  6597. function nearest_pow2( n ) {
  6598. var l = Math.log( n ) / Math.LN2;
  6599. return Math.pow( 2, Math.round( l ) );
  6600. }
  6601. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6602. var fullPath = texturePath + sourceFile;
  6603. var texture;
  6604. var loader = THREE.Loader.Handlers.get( fullPath );
  6605. if ( loader !== null ) {
  6606. texture = loader.load( fullPath );
  6607. } else {
  6608. texture = new THREE.Texture( document.createElement( 'canvas' ) );
  6609. loader = scope.imageLoader;
  6610. loader.crossOrigin = scope.crossOrigin;
  6611. loader.load( fullPath, function ( image ) {
  6612. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6613. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6614. var width = nearest_pow2( image.width );
  6615. var height = nearest_pow2( image.height );
  6616. texture.image.width = width;
  6617. texture.image.height = height;
  6618. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  6619. } else {
  6620. texture.image = image;
  6621. }
  6622. texture.needsUpdate = true;
  6623. } );
  6624. }
  6625. texture.sourceFile = sourceFile;
  6626. if ( repeat ) {
  6627. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6628. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6629. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6630. }
  6631. if ( offset ) {
  6632. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6633. }
  6634. if ( wrap ) {
  6635. var wrapMap = {
  6636. "repeat": THREE.RepeatWrapping,
  6637. "mirror": THREE.MirroredRepeatWrapping
  6638. }
  6639. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6640. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6641. }
  6642. if ( anisotropy ) {
  6643. texture.anisotropy = anisotropy;
  6644. }
  6645. where[ name ] = texture;
  6646. }
  6647. function rgb2hex( rgb ) {
  6648. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6649. }
  6650. // defaults
  6651. var mtype = "MeshLambertMaterial";
  6652. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6653. // parameters from model file
  6654. if ( m.shading ) {
  6655. var shading = m.shading.toLowerCase();
  6656. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6657. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6658. }
  6659. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6660. mpars.blending = THREE[ m.blending ];
  6661. }
  6662. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6663. mpars.transparent = m.transparent;
  6664. }
  6665. if ( m.depthTest !== undefined ) {
  6666. mpars.depthTest = m.depthTest;
  6667. }
  6668. if ( m.depthWrite !== undefined ) {
  6669. mpars.depthWrite = m.depthWrite;
  6670. }
  6671. if ( m.visible !== undefined ) {
  6672. mpars.visible = m.visible;
  6673. }
  6674. if ( m.flipSided !== undefined ) {
  6675. mpars.side = THREE.BackSide;
  6676. }
  6677. if ( m.doubleSided !== undefined ) {
  6678. mpars.side = THREE.DoubleSide;
  6679. }
  6680. if ( m.wireframe !== undefined ) {
  6681. mpars.wireframe = m.wireframe;
  6682. }
  6683. if ( m.vertexColors !== undefined ) {
  6684. if ( m.vertexColors === "face" ) {
  6685. mpars.vertexColors = THREE.FaceColors;
  6686. } else if ( m.vertexColors ) {
  6687. mpars.vertexColors = THREE.VertexColors;
  6688. }
  6689. }
  6690. // colors
  6691. if ( m.colorDiffuse ) {
  6692. mpars.color = rgb2hex( m.colorDiffuse );
  6693. } else if ( m.DbgColor ) {
  6694. mpars.color = m.DbgColor;
  6695. }
  6696. if ( m.colorSpecular ) {
  6697. mpars.specular = rgb2hex( m.colorSpecular );
  6698. }
  6699. if ( m.colorAmbient ) {
  6700. mpars.ambient = rgb2hex( m.colorAmbient );
  6701. }
  6702. if ( m.colorEmissive ) {
  6703. mpars.emissive = rgb2hex( m.colorEmissive );
  6704. }
  6705. // modifiers
  6706. if ( m.transparency ) {
  6707. mpars.opacity = m.transparency;
  6708. }
  6709. if ( m.specularCoef ) {
  6710. mpars.shininess = m.specularCoef;
  6711. }
  6712. // textures
  6713. if ( m.mapDiffuse && texturePath ) {
  6714. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6715. }
  6716. if ( m.mapLight && texturePath ) {
  6717. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6718. }
  6719. if ( m.mapBump && texturePath ) {
  6720. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6721. }
  6722. if ( m.mapNormal && texturePath ) {
  6723. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6724. }
  6725. if ( m.mapSpecular && texturePath ) {
  6726. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6727. }
  6728. //
  6729. if ( m.mapBumpScale ) {
  6730. mpars.bumpScale = m.mapBumpScale;
  6731. }
  6732. // special case for normal mapped material
  6733. if ( m.mapNormal ) {
  6734. var shader = THREE.ShaderLib[ "normalmap" ];
  6735. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6736. uniforms[ "tNormal" ].value = mpars.normalMap;
  6737. if ( m.mapNormalFactor ) {
  6738. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6739. }
  6740. if ( mpars.map ) {
  6741. uniforms[ "tDiffuse" ].value = mpars.map;
  6742. uniforms[ "enableDiffuse" ].value = true;
  6743. }
  6744. if ( mpars.specularMap ) {
  6745. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6746. uniforms[ "enableSpecular" ].value = true;
  6747. }
  6748. if ( mpars.lightMap ) {
  6749. uniforms[ "tAO" ].value = mpars.lightMap;
  6750. uniforms[ "enableAO" ].value = true;
  6751. }
  6752. // for the moment don't handle displacement texture
  6753. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6754. uniforms[ "specular" ].value.setHex( mpars.specular );
  6755. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6756. uniforms[ "shininess" ].value = mpars.shininess;
  6757. if ( mpars.opacity !== undefined ) {
  6758. uniforms[ "opacity" ].value = mpars.opacity;
  6759. }
  6760. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6761. var material = new THREE.ShaderMaterial( parameters );
  6762. if ( mpars.transparent ) {
  6763. material.transparent = true;
  6764. }
  6765. } else {
  6766. var material = new THREE[ mtype ]( mpars );
  6767. }
  6768. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6769. return material;
  6770. }
  6771. };
  6772. THREE.Loader.Handlers = {
  6773. handlers: [],
  6774. add: function ( regex, loader ) {
  6775. this.handlers.push( regex, loader );
  6776. },
  6777. get: function ( file ) {
  6778. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6779. var regex = this.handlers[ i ];
  6780. var loader = this.handlers[ i + 1 ];
  6781. if ( regex.test( file ) ) {
  6782. return loader;
  6783. }
  6784. }
  6785. return null;
  6786. }
  6787. };
  6788. /**
  6789. * @author mrdoob / http://mrdoob.com/
  6790. */
  6791. THREE.XHRLoader = function ( manager ) {
  6792. this.cache = new THREE.Cache();
  6793. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6794. };
  6795. THREE.XHRLoader.prototype = {
  6796. constructor: THREE.XHRLoader,
  6797. load: function ( url, onLoad, onProgress, onError ) {
  6798. var scope = this;
  6799. var cached = scope.cache.get( url );
  6800. if ( cached !== undefined ) {
  6801. onLoad( cached );
  6802. return;
  6803. }
  6804. var request = new XMLHttpRequest();
  6805. request.open( 'GET', url, true );
  6806. if ( onLoad !== undefined ) {
  6807. request.addEventListener( 'load', function ( event ) {
  6808. scope.cache.add( url, this.response );
  6809. onLoad( this.response );
  6810. scope.manager.itemEnd( url );
  6811. }, false );
  6812. }
  6813. if ( onProgress !== undefined ) {
  6814. request.addEventListener( 'progress', function ( event ) {
  6815. onProgress( event );
  6816. }, false );
  6817. }
  6818. if ( onError !== undefined ) {
  6819. request.addEventListener( 'error', function ( event ) {
  6820. onError( event );
  6821. }, false );
  6822. }
  6823. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6824. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6825. request.send( null );
  6826. scope.manager.itemStart( url );
  6827. },
  6828. setResponseType: function ( value ) {
  6829. this.responseType = value;
  6830. },
  6831. setCrossOrigin: function ( value ) {
  6832. this.crossOrigin = value;
  6833. }
  6834. };
  6835. /**
  6836. * @author mrdoob / http://mrdoob.com/
  6837. */
  6838. THREE.ImageLoader = function ( manager ) {
  6839. this.cache = new THREE.Cache();
  6840. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6841. };
  6842. THREE.ImageLoader.prototype = {
  6843. constructor: THREE.ImageLoader,
  6844. load: function ( url, onLoad, onProgress, onError ) {
  6845. var scope = this;
  6846. var cached = scope.cache.get( url );
  6847. if ( cached !== undefined ) {
  6848. onLoad( cached );
  6849. return;
  6850. }
  6851. var image = document.createElement( 'img' );
  6852. if ( onLoad !== undefined ) {
  6853. image.addEventListener( 'load', function ( event ) {
  6854. scope.cache.add( url, this );
  6855. onLoad( this );
  6856. scope.manager.itemEnd( url );
  6857. }, false );
  6858. }
  6859. if ( onProgress !== undefined ) {
  6860. image.addEventListener( 'progress', function ( event ) {
  6861. onProgress( event );
  6862. }, false );
  6863. }
  6864. if ( onError !== undefined ) {
  6865. image.addEventListener( 'error', function ( event ) {
  6866. onError( event );
  6867. }, false );
  6868. }
  6869. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6870. image.src = url;
  6871. scope.manager.itemStart( url );
  6872. return image;
  6873. },
  6874. setCrossOrigin: function ( value ) {
  6875. this.crossOrigin = value;
  6876. }
  6877. }
  6878. /**
  6879. * @author mrdoob / http://mrdoob.com/
  6880. * @author alteredq / http://alteredqualia.com/
  6881. */
  6882. THREE.JSONLoader = function ( showStatus ) {
  6883. THREE.Loader.call( this, showStatus );
  6884. this.withCredentials = false;
  6885. };
  6886. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6887. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6888. var scope = this;
  6889. // todo: unify load API to for easier SceneLoader use
  6890. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6891. this.onLoadStart();
  6892. this.loadAjaxJSON( this, url, callback, texturePath );
  6893. };
  6894. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6895. var xhr = new XMLHttpRequest();
  6896. var length = 0;
  6897. xhr.onreadystatechange = function () {
  6898. if ( xhr.readyState === xhr.DONE ) {
  6899. if ( xhr.status === 200 || xhr.status === 0 ) {
  6900. if ( xhr.responseText ) {
  6901. var json = JSON.parse( xhr.responseText );
  6902. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  6903. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  6904. return;
  6905. }
  6906. var result = context.parse( json, texturePath );
  6907. callback( result.geometry, result.materials );
  6908. } else {
  6909. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  6910. }
  6911. // in context of more complex asset initialization
  6912. // do not block on single failed file
  6913. // maybe should go even one more level up
  6914. context.onLoadComplete();
  6915. } else {
  6916. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  6917. }
  6918. } else if ( xhr.readyState === xhr.LOADING ) {
  6919. if ( callbackProgress ) {
  6920. if ( length === 0 ) {
  6921. length = xhr.getResponseHeader( 'Content-Length' );
  6922. }
  6923. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6924. }
  6925. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6926. if ( callbackProgress !== undefined ) {
  6927. length = xhr.getResponseHeader( "Content-Length" );
  6928. }
  6929. }
  6930. };
  6931. xhr.open( "GET", url, true );
  6932. xhr.withCredentials = this.withCredentials;
  6933. xhr.send( null );
  6934. };
  6935. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6936. var scope = this,
  6937. geometry = new THREE.Geometry(),
  6938. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6939. parseModel( scale );
  6940. parseSkin();
  6941. parseMorphing( scale );
  6942. geometry.computeFaceNormals();
  6943. geometry.computeBoundingSphere();
  6944. function parseModel( scale ) {
  6945. function isBitSet( value, position ) {
  6946. return value & ( 1 << position );
  6947. }
  6948. var i, j, fi,
  6949. offset, zLength,
  6950. colorIndex, normalIndex, uvIndex, materialIndex,
  6951. type,
  6952. isQuad,
  6953. hasMaterial,
  6954. hasFaceVertexUv,
  6955. hasFaceNormal, hasFaceVertexNormal,
  6956. hasFaceColor, hasFaceVertexColor,
  6957. vertex, face, faceA, faceB, color, hex, normal,
  6958. uvLayer, uv, u, v,
  6959. faces = json.faces,
  6960. vertices = json.vertices,
  6961. normals = json.normals,
  6962. colors = json.colors,
  6963. nUvLayers = 0;
  6964. if ( json.uvs !== undefined ) {
  6965. // disregard empty arrays
  6966. for ( i = 0; i < json.uvs.length; i++ ) {
  6967. if ( json.uvs[ i ].length ) nUvLayers ++;
  6968. }
  6969. for ( i = 0; i < nUvLayers; i++ ) {
  6970. geometry.faceVertexUvs[ i ] = [];
  6971. }
  6972. }
  6973. offset = 0;
  6974. zLength = vertices.length;
  6975. while ( offset < zLength ) {
  6976. vertex = new THREE.Vector3();
  6977. vertex.x = vertices[ offset ++ ] * scale;
  6978. vertex.y = vertices[ offset ++ ] * scale;
  6979. vertex.z = vertices[ offset ++ ] * scale;
  6980. geometry.vertices.push( vertex );
  6981. }
  6982. offset = 0;
  6983. zLength = faces.length;
  6984. while ( offset < zLength ) {
  6985. type = faces[ offset ++ ];
  6986. isQuad = isBitSet( type, 0 );
  6987. hasMaterial = isBitSet( type, 1 );
  6988. hasFaceVertexUv = isBitSet( type, 3 );
  6989. hasFaceNormal = isBitSet( type, 4 );
  6990. hasFaceVertexNormal = isBitSet( type, 5 );
  6991. hasFaceColor = isBitSet( type, 6 );
  6992. hasFaceVertexColor = isBitSet( type, 7 );
  6993. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6994. if ( isQuad ) {
  6995. faceA = new THREE.Face3();
  6996. faceA.a = faces[ offset ];
  6997. faceA.b = faces[ offset + 1 ];
  6998. faceA.c = faces[ offset + 3 ];
  6999. faceB = new THREE.Face3();
  7000. faceB.a = faces[ offset + 1 ];
  7001. faceB.b = faces[ offset + 2 ];
  7002. faceB.c = faces[ offset + 3 ];
  7003. offset += 4;
  7004. if ( hasMaterial ) {
  7005. materialIndex = faces[ offset ++ ];
  7006. faceA.materialIndex = materialIndex;
  7007. faceB.materialIndex = materialIndex;
  7008. }
  7009. // to get face <=> uv index correspondence
  7010. fi = geometry.faces.length;
  7011. if ( hasFaceVertexUv ) {
  7012. for ( i = 0; i < nUvLayers; i++ ) {
  7013. uvLayer = json.uvs[ i ];
  7014. geometry.faceVertexUvs[ i ][ fi ] = [];
  7015. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7016. for ( j = 0; j < 4; j ++ ) {
  7017. uvIndex = faces[ offset ++ ];
  7018. u = uvLayer[ uvIndex * 2 ];
  7019. v = uvLayer[ uvIndex * 2 + 1 ];
  7020. uv = new THREE.Vector2( u, v );
  7021. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7022. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7023. }
  7024. }
  7025. }
  7026. if ( hasFaceNormal ) {
  7027. normalIndex = faces[ offset ++ ] * 3;
  7028. faceA.normal.set(
  7029. normals[ normalIndex ++ ],
  7030. normals[ normalIndex ++ ],
  7031. normals[ normalIndex ]
  7032. );
  7033. faceB.normal.copy( faceA.normal );
  7034. }
  7035. if ( hasFaceVertexNormal ) {
  7036. for ( i = 0; i < 4; i++ ) {
  7037. normalIndex = faces[ offset ++ ] * 3;
  7038. normal = new THREE.Vector3(
  7039. normals[ normalIndex ++ ],
  7040. normals[ normalIndex ++ ],
  7041. normals[ normalIndex ]
  7042. );
  7043. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7044. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7045. }
  7046. }
  7047. if ( hasFaceColor ) {
  7048. colorIndex = faces[ offset ++ ];
  7049. hex = colors[ colorIndex ];
  7050. faceA.color.setHex( hex );
  7051. faceB.color.setHex( hex );
  7052. }
  7053. if ( hasFaceVertexColor ) {
  7054. for ( i = 0; i < 4; i++ ) {
  7055. colorIndex = faces[ offset ++ ];
  7056. hex = colors[ colorIndex ];
  7057. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7058. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7059. }
  7060. }
  7061. geometry.faces.push( faceA );
  7062. geometry.faces.push( faceB );
  7063. } else {
  7064. face = new THREE.Face3();
  7065. face.a = faces[ offset ++ ];
  7066. face.b = faces[ offset ++ ];
  7067. face.c = faces[ offset ++ ];
  7068. if ( hasMaterial ) {
  7069. materialIndex = faces[ offset ++ ];
  7070. face.materialIndex = materialIndex;
  7071. }
  7072. // to get face <=> uv index correspondence
  7073. fi = geometry.faces.length;
  7074. if ( hasFaceVertexUv ) {
  7075. for ( i = 0; i < nUvLayers; i++ ) {
  7076. uvLayer = json.uvs[ i ];
  7077. geometry.faceVertexUvs[ i ][ fi ] = [];
  7078. for ( j = 0; j < 3; j ++ ) {
  7079. uvIndex = faces[ offset ++ ];
  7080. u = uvLayer[ uvIndex * 2 ];
  7081. v = uvLayer[ uvIndex * 2 + 1 ];
  7082. uv = new THREE.Vector2( u, v );
  7083. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7084. }
  7085. }
  7086. }
  7087. if ( hasFaceNormal ) {
  7088. normalIndex = faces[ offset ++ ] * 3;
  7089. face.normal.set(
  7090. normals[ normalIndex ++ ],
  7091. normals[ normalIndex ++ ],
  7092. normals[ normalIndex ]
  7093. );
  7094. }
  7095. if ( hasFaceVertexNormal ) {
  7096. for ( i = 0; i < 3; i++ ) {
  7097. normalIndex = faces[ offset ++ ] * 3;
  7098. normal = new THREE.Vector3(
  7099. normals[ normalIndex ++ ],
  7100. normals[ normalIndex ++ ],
  7101. normals[ normalIndex ]
  7102. );
  7103. face.vertexNormals.push( normal );
  7104. }
  7105. }
  7106. if ( hasFaceColor ) {
  7107. colorIndex = faces[ offset ++ ];
  7108. face.color.setHex( colors[ colorIndex ] );
  7109. }
  7110. if ( hasFaceVertexColor ) {
  7111. for ( i = 0; i < 3; i++ ) {
  7112. colorIndex = faces[ offset ++ ];
  7113. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7114. }
  7115. }
  7116. geometry.faces.push( face );
  7117. }
  7118. }
  7119. };
  7120. function parseSkin() {
  7121. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7122. if ( json.skinWeights ) {
  7123. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7124. var x = json.skinWeights[ i ];
  7125. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7126. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7127. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7128. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7129. }
  7130. }
  7131. if ( json.skinIndices ) {
  7132. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7133. var a = json.skinIndices[ i ];
  7134. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7135. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7136. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7137. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7138. }
  7139. }
  7140. geometry.bones = json.bones;
  7141. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7142. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7143. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7144. }
  7145. // could change this to json.animations[0] or remove completely
  7146. geometry.animation = json.animation;
  7147. geometry.animations = json.animations;
  7148. };
  7149. function parseMorphing( scale ) {
  7150. if ( json.morphTargets !== undefined ) {
  7151. var i, l, v, vl, dstVertices, srcVertices;
  7152. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7153. geometry.morphTargets[ i ] = {};
  7154. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7155. geometry.morphTargets[ i ].vertices = [];
  7156. dstVertices = geometry.morphTargets[ i ].vertices;
  7157. srcVertices = json.morphTargets [ i ].vertices;
  7158. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7159. var vertex = new THREE.Vector3();
  7160. vertex.x = srcVertices[ v ] * scale;
  7161. vertex.y = srcVertices[ v + 1 ] * scale;
  7162. vertex.z = srcVertices[ v + 2 ] * scale;
  7163. dstVertices.push( vertex );
  7164. }
  7165. }
  7166. }
  7167. if ( json.morphColors !== undefined ) {
  7168. var i, l, c, cl, dstColors, srcColors, color;
  7169. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7170. geometry.morphColors[ i ] = {};
  7171. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7172. geometry.morphColors[ i ].colors = [];
  7173. dstColors = geometry.morphColors[ i ].colors;
  7174. srcColors = json.morphColors [ i ].colors;
  7175. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7176. color = new THREE.Color( 0xffaa00 );
  7177. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7178. dstColors.push( color );
  7179. }
  7180. }
  7181. }
  7182. };
  7183. if ( json.materials === undefined || json.materials.length === 0 ) {
  7184. return { geometry: geometry };
  7185. } else {
  7186. var materials = this.initMaterials( json.materials, texturePath );
  7187. if ( this.needsTangents( materials ) ) {
  7188. geometry.computeTangents();
  7189. }
  7190. return { geometry: geometry, materials: materials };
  7191. }
  7192. };
  7193. /**
  7194. * @author mrdoob / http://mrdoob.com/
  7195. */
  7196. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7197. var scope = this;
  7198. var loaded = 0, total = 0;
  7199. this.onLoad = onLoad;
  7200. this.onProgress = onProgress;
  7201. this.onError = onError;
  7202. this.itemStart = function ( url ) {
  7203. total ++;
  7204. };
  7205. this.itemEnd = function ( url ) {
  7206. loaded ++;
  7207. if ( scope.onProgress !== undefined ) {
  7208. scope.onProgress( url, loaded, total );
  7209. }
  7210. if ( loaded === total && scope.onLoad !== undefined ) {
  7211. scope.onLoad();
  7212. }
  7213. };
  7214. };
  7215. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7216. /**
  7217. * @author mrdoob / http://mrdoob.com/
  7218. */
  7219. THREE.BufferGeometryLoader = function ( manager ) {
  7220. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7221. };
  7222. THREE.BufferGeometryLoader.prototype = {
  7223. constructor: THREE.BufferGeometryLoader,
  7224. load: function ( url, onLoad, onProgress, onError ) {
  7225. var scope = this;
  7226. var loader = new THREE.XHRLoader();
  7227. loader.setCrossOrigin( this.crossOrigin );
  7228. loader.load( url, function ( text ) {
  7229. onLoad( scope.parse( JSON.parse( text ) ) );
  7230. } );
  7231. },
  7232. setCrossOrigin: function ( value ) {
  7233. this.crossOrigin = value;
  7234. },
  7235. parse: function ( json ) {
  7236. var geometry = new THREE.BufferGeometry();
  7237. var attributes = json.attributes;
  7238. var offsets = json.offsets;
  7239. var boundingSphere = json.boundingSphere;
  7240. for ( var key in attributes ) {
  7241. var attribute = attributes[ key ];
  7242. geometry.attributes[ key ] = {
  7243. itemSize: attribute.itemSize,
  7244. array: new self[ attribute.type ]( attribute.array )
  7245. }
  7246. }
  7247. if ( offsets !== undefined ) {
  7248. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7249. }
  7250. if ( boundingSphere !== undefined ) {
  7251. geometry.boundingSphere = new THREE.Sphere(
  7252. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7253. boundingSphere.radius
  7254. );
  7255. }
  7256. return geometry;
  7257. }
  7258. };
  7259. /**
  7260. * @author mrdoob / http://mrdoob.com/
  7261. */
  7262. THREE.MaterialLoader = function ( manager ) {
  7263. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7264. };
  7265. THREE.MaterialLoader.prototype = {
  7266. constructor: THREE.MaterialLoader,
  7267. load: function ( url, onLoad, onProgress, onError ) {
  7268. var scope = this;
  7269. var loader = new THREE.XHRLoader();
  7270. loader.setCrossOrigin( this.crossOrigin );
  7271. loader.load( url, function ( text ) {
  7272. onLoad( scope.parse( JSON.parse( text ) ) );
  7273. } );
  7274. },
  7275. setCrossOrigin: function ( value ) {
  7276. this.crossOrigin = value;
  7277. },
  7278. parse: function ( json ) {
  7279. var material = new THREE[ json.type ];
  7280. if ( json.color !== undefined ) material.color.setHex( json.color );
  7281. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7282. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7283. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7284. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7285. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7286. if ( json.blending !== undefined ) material.blending = json.blending;
  7287. if ( json.side !== undefined ) material.side = json.side;
  7288. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7289. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7290. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7291. if ( json.materials !== undefined ) {
  7292. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7293. material.materials.push( this.parse( json.materials[ i ] ) );
  7294. }
  7295. }
  7296. return material;
  7297. }
  7298. };
  7299. /**
  7300. * @author mrdoob / http://mrdoob.com/
  7301. */
  7302. THREE.ObjectLoader = function ( manager ) {
  7303. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7304. };
  7305. THREE.ObjectLoader.prototype = {
  7306. constructor: THREE.ObjectLoader,
  7307. load: function ( url, onLoad, onProgress, onError ) {
  7308. var scope = this;
  7309. var loader = new THREE.XHRLoader( scope.manager );
  7310. loader.setCrossOrigin( this.crossOrigin );
  7311. loader.load( url, function ( text ) {
  7312. onLoad( scope.parse( JSON.parse( text ) ) );
  7313. } );
  7314. },
  7315. setCrossOrigin: function ( value ) {
  7316. this.crossOrigin = value;
  7317. },
  7318. parse: function ( json ) {
  7319. var geometries = this.parseGeometries( json.geometries );
  7320. var materials = this.parseMaterials( json.materials );
  7321. var object = this.parseObject( json.object, geometries, materials );
  7322. return object;
  7323. },
  7324. parseGeometries: function ( json ) {
  7325. var geometries = {};
  7326. if ( json !== undefined ) {
  7327. var geometryLoader = new THREE.JSONLoader();
  7328. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7329. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7330. var geometry;
  7331. var data = json[ i ];
  7332. switch ( data.type ) {
  7333. case 'PlaneGeometry':
  7334. geometry = new THREE.PlaneGeometry(
  7335. data.width,
  7336. data.height,
  7337. data.widthSegments,
  7338. data.heightSegments
  7339. );
  7340. break;
  7341. case 'BoxGeometry':
  7342. case 'CubeGeometry': // backwards compatible
  7343. geometry = new THREE.BoxGeometry(
  7344. data.width,
  7345. data.height,
  7346. data.depth,
  7347. data.widthSegments,
  7348. data.heightSegments,
  7349. data.depthSegments
  7350. );
  7351. break;
  7352. case 'CircleGeometry':
  7353. geometry = new THREE.CircleGeometry(
  7354. data.radius,
  7355. data.segments
  7356. );
  7357. break;
  7358. case 'CylinderGeometry':
  7359. geometry = new THREE.CylinderGeometry(
  7360. data.radiusTop,
  7361. data.radiusBottom,
  7362. data.height,
  7363. data.radialSegments,
  7364. data.heightSegments,
  7365. data.openEnded
  7366. );
  7367. break;
  7368. case 'SphereGeometry':
  7369. geometry = new THREE.SphereGeometry(
  7370. data.radius,
  7371. data.widthSegments,
  7372. data.heightSegments,
  7373. data.phiStart,
  7374. data.phiLength,
  7375. data.thetaStart,
  7376. data.thetaLength
  7377. );
  7378. break;
  7379. case 'IcosahedronGeometry':
  7380. geometry = new THREE.IcosahedronGeometry(
  7381. data.radius,
  7382. data.detail
  7383. );
  7384. break;
  7385. case 'TorusGeometry':
  7386. geometry = new THREE.TorusGeometry(
  7387. data.radius,
  7388. data.tube,
  7389. data.radialSegments,
  7390. data.tubularSegments,
  7391. data.arc
  7392. );
  7393. break;
  7394. case 'TorusKnotGeometry':
  7395. geometry = new THREE.TorusKnotGeometry(
  7396. data.radius,
  7397. data.tube,
  7398. data.radialSegments,
  7399. data.tubularSegments,
  7400. data.p,
  7401. data.q,
  7402. data.heightScale
  7403. );
  7404. break;
  7405. case 'BufferGeometry':
  7406. geometry = bufferGeometryLoader.parse( data.data );
  7407. break;
  7408. case 'Geometry':
  7409. geometry = geometryLoader.parse( data.data ).geometry;
  7410. break;
  7411. }
  7412. geometry.uuid = data.uuid;
  7413. if ( data.name !== undefined ) geometry.name = data.name;
  7414. geometries[ data.uuid ] = geometry;
  7415. }
  7416. }
  7417. return geometries;
  7418. },
  7419. parseMaterials: function ( json ) {
  7420. var materials = {};
  7421. if ( json !== undefined ) {
  7422. var loader = new THREE.MaterialLoader();
  7423. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7424. var data = json[ i ];
  7425. var material = loader.parse( data );
  7426. material.uuid = data.uuid;
  7427. if ( data.name !== undefined ) material.name = data.name;
  7428. materials[ data.uuid ] = material;
  7429. }
  7430. }
  7431. return materials;
  7432. },
  7433. parseObject: function () {
  7434. var matrix = new THREE.Matrix4();
  7435. return function ( data, geometries, materials ) {
  7436. var object;
  7437. switch ( data.type ) {
  7438. case 'Scene':
  7439. object = new THREE.Scene();
  7440. break;
  7441. case 'PerspectiveCamera':
  7442. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7443. break;
  7444. case 'OrthographicCamera':
  7445. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7446. break;
  7447. case 'AmbientLight':
  7448. object = new THREE.AmbientLight( data.color );
  7449. break;
  7450. case 'DirectionalLight':
  7451. object = new THREE.DirectionalLight( data.color, data.intensity );
  7452. break;
  7453. case 'PointLight':
  7454. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7455. break;
  7456. case 'SpotLight':
  7457. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7458. break;
  7459. case 'HemisphereLight':
  7460. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7461. break;
  7462. case 'Mesh':
  7463. var geometry = geometries[ data.geometry ];
  7464. var material = materials[ data.material ];
  7465. if ( geometry === undefined ) {
  7466. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7467. }
  7468. if ( material === undefined ) {
  7469. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7470. }
  7471. object = new THREE.Mesh( geometry, material );
  7472. break;
  7473. case 'Sprite':
  7474. var material = materials[ data.material ];
  7475. if ( material === undefined ) {
  7476. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7477. }
  7478. object = new THREE.Sprite( material );
  7479. break;
  7480. default:
  7481. object = new THREE.Object3D();
  7482. }
  7483. object.uuid = data.uuid;
  7484. if ( data.name !== undefined ) object.name = data.name;
  7485. if ( data.matrix !== undefined ) {
  7486. matrix.fromArray( data.matrix );
  7487. matrix.decompose( object.position, object.quaternion, object.scale );
  7488. } else {
  7489. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7490. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7491. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7492. }
  7493. if ( data.visible !== undefined ) object.visible = data.visible;
  7494. if ( data.userData !== undefined ) object.userData = data.userData;
  7495. if ( data.children !== undefined ) {
  7496. for ( var child in data.children ) {
  7497. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7498. }
  7499. }
  7500. return object;
  7501. }
  7502. }()
  7503. };
  7504. /**
  7505. * @author mrdoob / http://mrdoob.com/
  7506. */
  7507. THREE.TextureLoader = function ( manager ) {
  7508. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7509. };
  7510. THREE.TextureLoader.prototype = {
  7511. constructor: THREE.TextureLoader,
  7512. load: function ( url, onLoad, onProgress, onError ) {
  7513. var scope = this;
  7514. var loader = new THREE.ImageLoader( scope.manager );
  7515. loader.setCrossOrigin( this.crossOrigin );
  7516. loader.load( url, function ( image ) {
  7517. var texture = new THREE.Texture( image );
  7518. texture.needsUpdate = true;
  7519. if ( onLoad !== undefined ) {
  7520. onLoad( texture );
  7521. }
  7522. } );
  7523. },
  7524. setCrossOrigin: function ( value ) {
  7525. this.crossOrigin = value;
  7526. }
  7527. };
  7528. /**
  7529. * @author mrdoob / http://mrdoob.com/
  7530. * @author alteredq / http://alteredqualia.com/
  7531. */
  7532. THREE.Material = function () {
  7533. this.id = THREE.MaterialIdCount ++;
  7534. this.uuid = THREE.Math.generateUUID();
  7535. this.name = '';
  7536. this.side = THREE.FrontSide;
  7537. this.opacity = 1;
  7538. this.transparent = false;
  7539. this.blending = THREE.NormalBlending;
  7540. this.blendSrc = THREE.SrcAlphaFactor;
  7541. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7542. this.blendEquation = THREE.AddEquation;
  7543. this.depthTest = true;
  7544. this.depthWrite = true;
  7545. this.polygonOffset = false;
  7546. this.polygonOffsetFactor = 0;
  7547. this.polygonOffsetUnits = 0;
  7548. this.alphaTest = 0;
  7549. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7550. this.visible = true;
  7551. this.needsUpdate = true;
  7552. };
  7553. THREE.Material.prototype = {
  7554. constructor: THREE.Material,
  7555. setValues: function ( values ) {
  7556. if ( values === undefined ) return;
  7557. for ( var key in values ) {
  7558. var newValue = values[ key ];
  7559. if ( newValue === undefined ) {
  7560. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7561. continue;
  7562. }
  7563. if ( key in this ) {
  7564. var currentValue = this[ key ];
  7565. if ( currentValue instanceof THREE.Color ) {
  7566. currentValue.set( newValue );
  7567. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7568. currentValue.copy( newValue );
  7569. } else if ( key == 'overdraw') {
  7570. // ensure overdraw is backwards-compatable with legacy boolean type
  7571. this[ key ] = Number(newValue);
  7572. } else {
  7573. this[ key ] = newValue;
  7574. }
  7575. }
  7576. }
  7577. },
  7578. clone: function ( material ) {
  7579. if ( material === undefined ) material = new THREE.Material();
  7580. material.name = this.name;
  7581. material.side = this.side;
  7582. material.opacity = this.opacity;
  7583. material.transparent = this.transparent;
  7584. material.blending = this.blending;
  7585. material.blendSrc = this.blendSrc;
  7586. material.blendDst = this.blendDst;
  7587. material.blendEquation = this.blendEquation;
  7588. material.depthTest = this.depthTest;
  7589. material.depthWrite = this.depthWrite;
  7590. material.polygonOffset = this.polygonOffset;
  7591. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7592. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7593. material.alphaTest = this.alphaTest;
  7594. material.overdraw = this.overdraw;
  7595. material.visible = this.visible;
  7596. return material;
  7597. },
  7598. dispose: function () {
  7599. this.dispatchEvent( { type: 'dispose' } );
  7600. }
  7601. };
  7602. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7603. THREE.MaterialIdCount = 0;
  7604. /**
  7605. * @author mrdoob / http://mrdoob.com/
  7606. * @author alteredq / http://alteredqualia.com/
  7607. *
  7608. * parameters = {
  7609. * color: <hex>,
  7610. * opacity: <float>,
  7611. *
  7612. * blending: THREE.NormalBlending,
  7613. * depthTest: <bool>,
  7614. * depthWrite: <bool>,
  7615. *
  7616. * linewidth: <float>,
  7617. * linecap: "round",
  7618. * linejoin: "round",
  7619. *
  7620. * vertexColors: <bool>
  7621. *
  7622. * fog: <bool>
  7623. * }
  7624. */
  7625. THREE.LineBasicMaterial = function ( parameters ) {
  7626. THREE.Material.call( this );
  7627. this.color = new THREE.Color( 0xffffff );
  7628. this.linewidth = 1;
  7629. this.linecap = 'round';
  7630. this.linejoin = 'round';
  7631. this.vertexColors = THREE.NoColors;
  7632. this.fog = true;
  7633. this.setValues( parameters );
  7634. };
  7635. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7636. THREE.LineBasicMaterial.prototype.clone = function () {
  7637. var material = new THREE.LineBasicMaterial();
  7638. THREE.Material.prototype.clone.call( this, material );
  7639. material.color.copy( this.color );
  7640. material.linewidth = this.linewidth;
  7641. material.linecap = this.linecap;
  7642. material.linejoin = this.linejoin;
  7643. material.vertexColors = this.vertexColors;
  7644. material.fog = this.fog;
  7645. return material;
  7646. };
  7647. /**
  7648. * @author alteredq / http://alteredqualia.com/
  7649. *
  7650. * parameters = {
  7651. * color: <hex>,
  7652. * opacity: <float>,
  7653. *
  7654. * blending: THREE.NormalBlending,
  7655. * depthTest: <bool>,
  7656. * depthWrite: <bool>,
  7657. *
  7658. * linewidth: <float>,
  7659. *
  7660. * scale: <float>,
  7661. * dashSize: <float>,
  7662. * gapSize: <float>,
  7663. *
  7664. * vertexColors: <bool>
  7665. *
  7666. * fog: <bool>
  7667. * }
  7668. */
  7669. THREE.LineDashedMaterial = function ( parameters ) {
  7670. THREE.Material.call( this );
  7671. this.color = new THREE.Color( 0xffffff );
  7672. this.linewidth = 1;
  7673. this.scale = 1;
  7674. this.dashSize = 3;
  7675. this.gapSize = 1;
  7676. this.vertexColors = false;
  7677. this.fog = true;
  7678. this.setValues( parameters );
  7679. };
  7680. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7681. THREE.LineDashedMaterial.prototype.clone = function () {
  7682. var material = new THREE.LineDashedMaterial();
  7683. THREE.Material.prototype.clone.call( this, material );
  7684. material.color.copy( this.color );
  7685. material.linewidth = this.linewidth;
  7686. material.scale = this.scale;
  7687. material.dashSize = this.dashSize;
  7688. material.gapSize = this.gapSize;
  7689. material.vertexColors = this.vertexColors;
  7690. material.fog = this.fog;
  7691. return material;
  7692. };
  7693. /**
  7694. * @author mrdoob / http://mrdoob.com/
  7695. * @author alteredq / http://alteredqualia.com/
  7696. *
  7697. * parameters = {
  7698. * color: <hex>,
  7699. * opacity: <float>,
  7700. * map: new THREE.Texture( <Image> ),
  7701. *
  7702. * lightMap: new THREE.Texture( <Image> ),
  7703. *
  7704. * specularMap: new THREE.Texture( <Image> ),
  7705. *
  7706. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7707. * combine: THREE.Multiply,
  7708. * reflectivity: <float>,
  7709. * refractionRatio: <float>,
  7710. *
  7711. * shading: THREE.SmoothShading,
  7712. * blending: THREE.NormalBlending,
  7713. * depthTest: <bool>,
  7714. * depthWrite: <bool>,
  7715. *
  7716. * wireframe: <boolean>,
  7717. * wireframeLinewidth: <float>,
  7718. *
  7719. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7720. *
  7721. * skinning: <bool>,
  7722. * morphTargets: <bool>,
  7723. *
  7724. * fog: <bool>
  7725. * }
  7726. */
  7727. THREE.MeshBasicMaterial = function ( parameters ) {
  7728. THREE.Material.call( this );
  7729. this.color = new THREE.Color( 0xffffff ); // emissive
  7730. this.map = null;
  7731. this.lightMap = null;
  7732. this.specularMap = null;
  7733. this.envMap = null;
  7734. this.combine = THREE.MultiplyOperation;
  7735. this.reflectivity = 1;
  7736. this.refractionRatio = 0.98;
  7737. this.fog = true;
  7738. this.shading = THREE.SmoothShading;
  7739. this.wireframe = false;
  7740. this.wireframeLinewidth = 1;
  7741. this.wireframeLinecap = 'round';
  7742. this.wireframeLinejoin = 'round';
  7743. this.vertexColors = THREE.NoColors;
  7744. this.skinning = false;
  7745. this.morphTargets = false;
  7746. this.setValues( parameters );
  7747. };
  7748. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7749. THREE.MeshBasicMaterial.prototype.clone = function () {
  7750. var material = new THREE.MeshBasicMaterial();
  7751. THREE.Material.prototype.clone.call( this, material );
  7752. material.color.copy( this.color );
  7753. material.map = this.map;
  7754. material.lightMap = this.lightMap;
  7755. material.specularMap = this.specularMap;
  7756. material.envMap = this.envMap;
  7757. material.combine = this.combine;
  7758. material.reflectivity = this.reflectivity;
  7759. material.refractionRatio = this.refractionRatio;
  7760. material.fog = this.fog;
  7761. material.shading = this.shading;
  7762. material.wireframe = this.wireframe;
  7763. material.wireframeLinewidth = this.wireframeLinewidth;
  7764. material.wireframeLinecap = this.wireframeLinecap;
  7765. material.wireframeLinejoin = this.wireframeLinejoin;
  7766. material.vertexColors = this.vertexColors;
  7767. material.skinning = this.skinning;
  7768. material.morphTargets = this.morphTargets;
  7769. return material;
  7770. };
  7771. /**
  7772. * @author mrdoob / http://mrdoob.com/
  7773. * @author alteredq / http://alteredqualia.com/
  7774. *
  7775. * parameters = {
  7776. * color: <hex>,
  7777. * ambient: <hex>,
  7778. * emissive: <hex>,
  7779. * opacity: <float>,
  7780. *
  7781. * map: new THREE.Texture( <Image> ),
  7782. *
  7783. * lightMap: new THREE.Texture( <Image> ),
  7784. *
  7785. * specularMap: new THREE.Texture( <Image> ),
  7786. *
  7787. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7788. * combine: THREE.Multiply,
  7789. * reflectivity: <float>,
  7790. * refractionRatio: <float>,
  7791. *
  7792. * shading: THREE.SmoothShading,
  7793. * blending: THREE.NormalBlending,
  7794. * depthTest: <bool>,
  7795. * depthWrite: <bool>,
  7796. *
  7797. * wireframe: <boolean>,
  7798. * wireframeLinewidth: <float>,
  7799. *
  7800. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7801. *
  7802. * skinning: <bool>,
  7803. * morphTargets: <bool>,
  7804. * morphNormals: <bool>,
  7805. *
  7806. * fog: <bool>
  7807. * }
  7808. */
  7809. THREE.MeshLambertMaterial = function ( parameters ) {
  7810. THREE.Material.call( this );
  7811. this.color = new THREE.Color( 0xffffff ); // diffuse
  7812. this.ambient = new THREE.Color( 0xffffff );
  7813. this.emissive = new THREE.Color( 0x000000 );
  7814. this.wrapAround = false;
  7815. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7816. this.map = null;
  7817. this.lightMap = null;
  7818. this.specularMap = null;
  7819. this.envMap = null;
  7820. this.combine = THREE.MultiplyOperation;
  7821. this.reflectivity = 1;
  7822. this.refractionRatio = 0.98;
  7823. this.fog = true;
  7824. this.shading = THREE.SmoothShading;
  7825. this.wireframe = false;
  7826. this.wireframeLinewidth = 1;
  7827. this.wireframeLinecap = 'round';
  7828. this.wireframeLinejoin = 'round';
  7829. this.vertexColors = THREE.NoColors;
  7830. this.skinning = false;
  7831. this.morphTargets = false;
  7832. this.morphNormals = false;
  7833. this.setValues( parameters );
  7834. };
  7835. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7836. THREE.MeshLambertMaterial.prototype.clone = function () {
  7837. var material = new THREE.MeshLambertMaterial();
  7838. THREE.Material.prototype.clone.call( this, material );
  7839. material.color.copy( this.color );
  7840. material.ambient.copy( this.ambient );
  7841. material.emissive.copy( this.emissive );
  7842. material.wrapAround = this.wrapAround;
  7843. material.wrapRGB.copy( this.wrapRGB );
  7844. material.map = this.map;
  7845. material.lightMap = this.lightMap;
  7846. material.specularMap = this.specularMap;
  7847. material.envMap = this.envMap;
  7848. material.combine = this.combine;
  7849. material.reflectivity = this.reflectivity;
  7850. material.refractionRatio = this.refractionRatio;
  7851. material.fog = this.fog;
  7852. material.shading = this.shading;
  7853. material.wireframe = this.wireframe;
  7854. material.wireframeLinewidth = this.wireframeLinewidth;
  7855. material.wireframeLinecap = this.wireframeLinecap;
  7856. material.wireframeLinejoin = this.wireframeLinejoin;
  7857. material.vertexColors = this.vertexColors;
  7858. material.skinning = this.skinning;
  7859. material.morphTargets = this.morphTargets;
  7860. material.morphNormals = this.morphNormals;
  7861. return material;
  7862. };
  7863. /**
  7864. * @author mrdoob / http://mrdoob.com/
  7865. * @author alteredq / http://alteredqualia.com/
  7866. *
  7867. * parameters = {
  7868. * color: <hex>,
  7869. * ambient: <hex>,
  7870. * emissive: <hex>,
  7871. * specular: <hex>,
  7872. * shininess: <float>,
  7873. * opacity: <float>,
  7874. *
  7875. * map: new THREE.Texture( <Image> ),
  7876. *
  7877. * lightMap: new THREE.Texture( <Image> ),
  7878. *
  7879. * bumpMap: new THREE.Texture( <Image> ),
  7880. * bumpScale: <float>,
  7881. *
  7882. * normalMap: new THREE.Texture( <Image> ),
  7883. * normalScale: <Vector2>,
  7884. *
  7885. * specularMap: new THREE.Texture( <Image> ),
  7886. *
  7887. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7888. * combine: THREE.Multiply,
  7889. * reflectivity: <float>,
  7890. * refractionRatio: <float>,
  7891. *
  7892. * shading: THREE.SmoothShading,
  7893. * blending: THREE.NormalBlending,
  7894. * depthTest: <bool>,
  7895. * depthWrite: <bool>,
  7896. *
  7897. * wireframe: <boolean>,
  7898. * wireframeLinewidth: <float>,
  7899. *
  7900. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7901. *
  7902. * skinning: <bool>,
  7903. * morphTargets: <bool>,
  7904. * morphNormals: <bool>,
  7905. *
  7906. * fog: <bool>
  7907. * }
  7908. */
  7909. THREE.MeshPhongMaterial = function ( parameters ) {
  7910. THREE.Material.call( this );
  7911. this.color = new THREE.Color( 0xffffff ); // diffuse
  7912. this.ambient = new THREE.Color( 0xffffff );
  7913. this.emissive = new THREE.Color( 0x000000 );
  7914. this.specular = new THREE.Color( 0x111111 );
  7915. this.shininess = 30;
  7916. this.metal = false;
  7917. this.wrapAround = false;
  7918. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7919. this.map = null;
  7920. this.lightMap = null;
  7921. this.bumpMap = null;
  7922. this.bumpScale = 1;
  7923. this.normalMap = null;
  7924. this.normalScale = new THREE.Vector2( 1, 1 );
  7925. this.specularMap = null;
  7926. this.envMap = null;
  7927. this.combine = THREE.MultiplyOperation;
  7928. this.reflectivity = 1;
  7929. this.refractionRatio = 0.98;
  7930. this.fog = true;
  7931. this.shading = THREE.SmoothShading;
  7932. this.wireframe = false;
  7933. this.wireframeLinewidth = 1;
  7934. this.wireframeLinecap = 'round';
  7935. this.wireframeLinejoin = 'round';
  7936. this.vertexColors = THREE.NoColors;
  7937. this.skinning = false;
  7938. this.morphTargets = false;
  7939. this.morphNormals = false;
  7940. this.setValues( parameters );
  7941. };
  7942. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7943. THREE.MeshPhongMaterial.prototype.clone = function () {
  7944. var material = new THREE.MeshPhongMaterial();
  7945. THREE.Material.prototype.clone.call( this, material );
  7946. material.color.copy( this.color );
  7947. material.ambient.copy( this.ambient );
  7948. material.emissive.copy( this.emissive );
  7949. material.specular.copy( this.specular );
  7950. material.shininess = this.shininess;
  7951. material.metal = this.metal;
  7952. material.wrapAround = this.wrapAround;
  7953. material.wrapRGB.copy( this.wrapRGB );
  7954. material.map = this.map;
  7955. material.lightMap = this.lightMap;
  7956. material.bumpMap = this.bumpMap;
  7957. material.bumpScale = this.bumpScale;
  7958. material.normalMap = this.normalMap;
  7959. material.normalScale.copy( this.normalScale );
  7960. material.specularMap = this.specularMap;
  7961. material.envMap = this.envMap;
  7962. material.combine = this.combine;
  7963. material.reflectivity = this.reflectivity;
  7964. material.refractionRatio = this.refractionRatio;
  7965. material.fog = this.fog;
  7966. material.shading = this.shading;
  7967. material.wireframe = this.wireframe;
  7968. material.wireframeLinewidth = this.wireframeLinewidth;
  7969. material.wireframeLinecap = this.wireframeLinecap;
  7970. material.wireframeLinejoin = this.wireframeLinejoin;
  7971. material.vertexColors = this.vertexColors;
  7972. material.skinning = this.skinning;
  7973. material.morphTargets = this.morphTargets;
  7974. material.morphNormals = this.morphNormals;
  7975. return material;
  7976. };
  7977. /**
  7978. * @author mrdoob / http://mrdoob.com/
  7979. * @author alteredq / http://alteredqualia.com/
  7980. *
  7981. * parameters = {
  7982. * opacity: <float>,
  7983. *
  7984. * blending: THREE.NormalBlending,
  7985. * depthTest: <bool>,
  7986. * depthWrite: <bool>,
  7987. *
  7988. * wireframe: <boolean>,
  7989. * wireframeLinewidth: <float>
  7990. * }
  7991. */
  7992. THREE.MeshDepthMaterial = function ( parameters ) {
  7993. THREE.Material.call( this );
  7994. this.morphTargets = false;
  7995. this.wireframe = false;
  7996. this.wireframeLinewidth = 1;
  7997. this.setValues( parameters );
  7998. };
  7999. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8000. THREE.MeshDepthMaterial.prototype.clone = function () {
  8001. var material = new THREE.MeshDepthMaterial();
  8002. THREE.Material.prototype.clone.call( this, material );
  8003. material.wireframe = this.wireframe;
  8004. material.wireframeLinewidth = this.wireframeLinewidth;
  8005. return material;
  8006. };
  8007. /**
  8008. * @author mrdoob / http://mrdoob.com/
  8009. *
  8010. * parameters = {
  8011. * opacity: <float>,
  8012. *
  8013. * shading: THREE.FlatShading,
  8014. * blending: THREE.NormalBlending,
  8015. * depthTest: <bool>,
  8016. * depthWrite: <bool>,
  8017. *
  8018. * wireframe: <boolean>,
  8019. * wireframeLinewidth: <float>
  8020. * }
  8021. */
  8022. THREE.MeshNormalMaterial = function ( parameters ) {
  8023. THREE.Material.call( this, parameters );
  8024. this.shading = THREE.FlatShading;
  8025. this.wireframe = false;
  8026. this.wireframeLinewidth = 1;
  8027. this.morphTargets = false;
  8028. this.setValues( parameters );
  8029. };
  8030. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8031. THREE.MeshNormalMaterial.prototype.clone = function () {
  8032. var material = new THREE.MeshNormalMaterial();
  8033. THREE.Material.prototype.clone.call( this, material );
  8034. material.shading = this.shading;
  8035. material.wireframe = this.wireframe;
  8036. material.wireframeLinewidth = this.wireframeLinewidth;
  8037. return material;
  8038. };
  8039. /**
  8040. * @author mrdoob / http://mrdoob.com/
  8041. */
  8042. THREE.MeshFaceMaterial = function ( materials ) {
  8043. this.materials = materials instanceof Array ? materials : [];
  8044. };
  8045. THREE.MeshFaceMaterial.prototype.clone = function () {
  8046. var material = new THREE.MeshFaceMaterial();
  8047. for ( var i = 0; i < this.materials.length; i ++ ) {
  8048. material.materials.push( this.materials[ i ].clone() );
  8049. }
  8050. return material;
  8051. };
  8052. /**
  8053. * @author mrdoob / http://mrdoob.com/
  8054. * @author alteredq / http://alteredqualia.com/
  8055. *
  8056. * parameters = {
  8057. * color: <hex>,
  8058. * opacity: <float>,
  8059. * map: new THREE.Texture( <Image> ),
  8060. *
  8061. * size: <float>,
  8062. *
  8063. * blending: THREE.NormalBlending,
  8064. * depthTest: <bool>,
  8065. * depthWrite: <bool>,
  8066. *
  8067. * vertexColors: <bool>,
  8068. *
  8069. * fog: <bool>
  8070. * }
  8071. */
  8072. THREE.PointCloudMaterial = function ( parameters ) {
  8073. THREE.Material.call( this );
  8074. this.color = new THREE.Color( 0xffffff );
  8075. this.map = null;
  8076. this.size = 1;
  8077. this.sizeAttenuation = true;
  8078. this.vertexColors = THREE.NoColors;
  8079. this.fog = true;
  8080. this.setValues( parameters );
  8081. };
  8082. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8083. THREE.PointCloudMaterial.prototype.clone = function () {
  8084. var material = new THREE.PointCloudMaterial();
  8085. THREE.Material.prototype.clone.call( this, material );
  8086. material.color.copy( this.color );
  8087. material.map = this.map;
  8088. material.size = this.size;
  8089. material.sizeAttenuation = this.sizeAttenuation;
  8090. material.vertexColors = this.vertexColors;
  8091. material.fog = this.fog;
  8092. return material;
  8093. };
  8094. // backwards compatibility
  8095. THREE.ParticleSystemMaterial = function ( parameters ) {
  8096. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8097. return new THREE.PointCloudMaterial( parameters );
  8098. }
  8099. /**
  8100. * @author alteredq / http://alteredqualia.com/
  8101. *
  8102. * parameters = {
  8103. * fragmentShader: <string>,
  8104. * vertexShader: <string>,
  8105. *
  8106. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8107. *
  8108. * defines: { "label" : "value" },
  8109. *
  8110. * shading: THREE.SmoothShading,
  8111. * blending: THREE.NormalBlending,
  8112. * depthTest: <bool>,
  8113. * depthWrite: <bool>,
  8114. *
  8115. * wireframe: <boolean>,
  8116. * wireframeLinewidth: <float>,
  8117. *
  8118. * lights: <bool>,
  8119. *
  8120. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8121. *
  8122. * skinning: <bool>,
  8123. * morphTargets: <bool>,
  8124. * morphNormals: <bool>,
  8125. *
  8126. * fog: <bool>
  8127. * }
  8128. */
  8129. THREE.ShaderMaterial = function ( parameters ) {
  8130. THREE.Material.call( this );
  8131. this.fragmentShader = "void main() {}";
  8132. this.vertexShader = "void main() {}";
  8133. this.uniforms = {};
  8134. this.defines = {};
  8135. this.attributes = null;
  8136. this.shading = THREE.SmoothShading;
  8137. this.linewidth = 1;
  8138. this.wireframe = false;
  8139. this.wireframeLinewidth = 1;
  8140. this.fog = false; // set to use scene fog
  8141. this.lights = false; // set to use scene lights
  8142. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8143. this.skinning = false; // set to use skinning attribute streams
  8144. this.morphTargets = false; // set to use morph targets
  8145. this.morphNormals = false; // set to use morph normals
  8146. // When rendered geometry doesn't include these attributes but the material does,
  8147. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8148. this.defaultAttributeValues = {
  8149. "color" : [ 1, 1, 1 ],
  8150. "uv" : [ 0, 0 ],
  8151. "uv2" : [ 0, 0 ]
  8152. };
  8153. this.index0AttributeName = undefined;
  8154. this.setValues( parameters );
  8155. };
  8156. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8157. THREE.ShaderMaterial.prototype.clone = function () {
  8158. var material = new THREE.ShaderMaterial();
  8159. THREE.Material.prototype.clone.call( this, material );
  8160. material.fragmentShader = this.fragmentShader;
  8161. material.vertexShader = this.vertexShader;
  8162. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8163. material.attributes = this.attributes;
  8164. material.defines = this.defines;
  8165. material.shading = this.shading;
  8166. material.wireframe = this.wireframe;
  8167. material.wireframeLinewidth = this.wireframeLinewidth;
  8168. material.fog = this.fog;
  8169. material.lights = this.lights;
  8170. material.vertexColors = this.vertexColors;
  8171. material.skinning = this.skinning;
  8172. material.morphTargets = this.morphTargets;
  8173. material.morphNormals = this.morphNormals;
  8174. return material;
  8175. };
  8176. /**
  8177. * @author mrdoob / http://mrdoob.com/
  8178. */
  8179. THREE.RawShaderMaterial = function ( parameters ) {
  8180. THREE.ShaderMaterial.call( this, parameters );
  8181. };
  8182. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8183. THREE.RawShaderMaterial.prototype.clone = function () {
  8184. var material = new THREE.RawShaderMaterial();
  8185. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8186. return material;
  8187. };
  8188. /**
  8189. * @author alteredq / http://alteredqualia.com/
  8190. *
  8191. * parameters = {
  8192. * color: <hex>,
  8193. * opacity: <float>,
  8194. * map: new THREE.Texture( <Image> ),
  8195. *
  8196. * blending: THREE.NormalBlending,
  8197. * depthTest: <bool>,
  8198. * depthWrite: <bool>,
  8199. *
  8200. * uvOffset: new THREE.Vector2(),
  8201. * uvScale: new THREE.Vector2(),
  8202. *
  8203. * fog: <bool>
  8204. * }
  8205. */
  8206. THREE.SpriteMaterial = function ( parameters ) {
  8207. THREE.Material.call( this );
  8208. // defaults
  8209. this.color = new THREE.Color( 0xffffff );
  8210. this.map = null;
  8211. this.rotation = 0;
  8212. this.fog = false;
  8213. // set parameters
  8214. this.setValues( parameters );
  8215. };
  8216. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8217. THREE.SpriteMaterial.prototype.clone = function () {
  8218. var material = new THREE.SpriteMaterial();
  8219. THREE.Material.prototype.clone.call( this, material );
  8220. material.color.copy( this.color );
  8221. material.map = this.map;
  8222. material.rotation = this.rotation;
  8223. material.fog = this.fog;
  8224. return material;
  8225. };
  8226. /**
  8227. * @author mrdoob / http://mrdoob.com/
  8228. *
  8229. * parameters = {
  8230. * color: <hex>,
  8231. * program: <function>,
  8232. * opacity: <float>,
  8233. * blending: THREE.NormalBlending
  8234. * }
  8235. */
  8236. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8237. THREE.Material.call( this );
  8238. this.color = new THREE.Color( 0xffffff );
  8239. this.program = function ( context, color ) {};
  8240. this.setValues( parameters );
  8241. };
  8242. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8243. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8244. var material = new THREE.SpriteCanvasMaterial();
  8245. THREE.Material.prototype.clone.call( this, material );
  8246. material.color.copy( this.color );
  8247. material.program = this.program;
  8248. return material;
  8249. };
  8250. // backwards compatibility
  8251. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8252. /**
  8253. * @author mrdoob / http://mrdoob.com/
  8254. * @author alteredq / http://alteredqualia.com/
  8255. * @author szimek / https://github.com/szimek/
  8256. */
  8257. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8258. this.id = THREE.TextureIdCount ++;
  8259. this.uuid = THREE.Math.generateUUID();
  8260. this.name = '';
  8261. this.image = image;
  8262. this.mipmaps = [];
  8263. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8264. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8265. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8266. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8267. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8268. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8269. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8270. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8271. this.offset = new THREE.Vector2( 0, 0 );
  8272. this.repeat = new THREE.Vector2( 1, 1 );
  8273. this.generateMipmaps = true;
  8274. this.premultiplyAlpha = false;
  8275. this.flipY = true;
  8276. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8277. this._needsUpdate = false;
  8278. this.onUpdate = null;
  8279. };
  8280. THREE.Texture.prototype = {
  8281. constructor: THREE.Texture,
  8282. get needsUpdate () {
  8283. return this._needsUpdate;
  8284. },
  8285. set needsUpdate ( value ) {
  8286. if ( value === true ) this.update();
  8287. this._needsUpdate = value;
  8288. },
  8289. clone: function ( texture ) {
  8290. if ( texture === undefined ) texture = new THREE.Texture();
  8291. texture.image = this.image;
  8292. texture.mipmaps = this.mipmaps.slice(0);
  8293. texture.mapping = this.mapping;
  8294. texture.wrapS = this.wrapS;
  8295. texture.wrapT = this.wrapT;
  8296. texture.magFilter = this.magFilter;
  8297. texture.minFilter = this.minFilter;
  8298. texture.anisotropy = this.anisotropy;
  8299. texture.format = this.format;
  8300. texture.type = this.type;
  8301. texture.offset.copy( this.offset );
  8302. texture.repeat.copy( this.repeat );
  8303. texture.generateMipmaps = this.generateMipmaps;
  8304. texture.premultiplyAlpha = this.premultiplyAlpha;
  8305. texture.flipY = this.flipY;
  8306. texture.unpackAlignment = this.unpackAlignment;
  8307. return texture;
  8308. },
  8309. update: function () {
  8310. this.dispatchEvent( { type: 'update' } );
  8311. },
  8312. dispose: function () {
  8313. this.dispatchEvent( { type: 'dispose' } );
  8314. }
  8315. };
  8316. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8317. THREE.TextureIdCount = 0;
  8318. /**
  8319. * @author alteredq / http://alteredqualia.com/
  8320. */
  8321. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8322. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8323. this.image = { width: width, height: height };
  8324. this.mipmaps = mipmaps;
  8325. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8326. };
  8327. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8328. THREE.CompressedTexture.prototype.clone = function () {
  8329. var texture = new THREE.CompressedTexture();
  8330. THREE.Texture.prototype.clone.call( this, texture );
  8331. return texture;
  8332. };
  8333. /**
  8334. * @author alteredq / http://alteredqualia.com/
  8335. */
  8336. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8337. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8338. this.image = { data: data, width: width, height: height };
  8339. };
  8340. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8341. THREE.DataTexture.prototype.clone = function () {
  8342. var texture = new THREE.DataTexture();
  8343. THREE.Texture.prototype.clone.call( this, texture );
  8344. return texture;
  8345. };
  8346. /**
  8347. * @author alteredq / http://alteredqualia.com/
  8348. */
  8349. THREE.PointCloud = function ( geometry, material ) {
  8350. THREE.Object3D.call( this );
  8351. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8352. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8353. this.sortParticles = false;
  8354. };
  8355. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8356. THREE.PointCloud.prototype.raycast = ( function () {
  8357. var inverseMatrix = new THREE.Matrix4();
  8358. var ray = new THREE.Ray();
  8359. return function ( raycaster, intersects ) {
  8360. var object = this;
  8361. var geometry = object.geometry;
  8362. var threshold = raycaster.params.PointCloud.threshold;
  8363. inverseMatrix.getInverse( this.matrixWorld );
  8364. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8365. if ( geometry.boundingBox !== null ) {
  8366. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8367. return;
  8368. }
  8369. }
  8370. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8371. var position = new THREE.Vector3();
  8372. var testPoint = function ( point, index ) {
  8373. var rayPointDistance = ray.distanceToPoint( point );
  8374. if ( rayPointDistance < localThreshold ) {
  8375. var intersectPoint = ray.closestPointToPoint( point );
  8376. intersectPoint.applyMatrix4( object.matrixWorld );
  8377. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8378. intersects.push( {
  8379. distance: distance,
  8380. distanceToRay: rayPointDistance,
  8381. point: intersectPoint.clone(),
  8382. index: index,
  8383. face: null,
  8384. object: object
  8385. } );
  8386. }
  8387. };
  8388. if ( geometry instanceof THREE.BufferGeometry ) {
  8389. var attributes = geometry.attributes;
  8390. var positions = attributes.position.array;
  8391. if ( attributes.index !== undefined ) {
  8392. var indices = attributes.index.array;
  8393. var offsets = geometry.offsets;
  8394. if ( offsets.length === 0 ) {
  8395. var offset = {
  8396. start: 0,
  8397. count: indices.length,
  8398. index: 0
  8399. };
  8400. offsets = [ offset ];
  8401. }
  8402. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8403. var start = offsets[ oi ].start;
  8404. var count = offsets[ oi ].count;
  8405. var index = offsets[ oi ].index;
  8406. for ( var i = start, il = start + count; i < il; i++ ) {
  8407. var a = index + indices[ i ];
  8408. position.set(
  8409. positions[ a * 3 ],
  8410. positions[ a * 3 + 1 ],
  8411. positions[ a * 3 + 2 ]
  8412. );
  8413. testPoint( position, a );
  8414. }
  8415. }
  8416. } else {
  8417. var pointCount = positions.length / 3;
  8418. for ( var i = 0; i < pointCount; i ++ ) {
  8419. position.set(
  8420. positions[ 3 * i ],
  8421. positions[ 3 * i + 1 ],
  8422. positions[ 3 * i + 2 ]
  8423. );
  8424. testPoint( position, i );
  8425. }
  8426. }
  8427. } else {
  8428. var vertices = this.geometry.vertices;
  8429. for ( var i = 0; i < vertices.length; i ++ ) {
  8430. testPoint( vertices[ i ], i );
  8431. }
  8432. }
  8433. };
  8434. }() );
  8435. THREE.PointCloud.prototype.clone = function ( object ) {
  8436. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8437. object.sortParticles = this.sortParticles;
  8438. THREE.Object3D.prototype.clone.call( this, object );
  8439. return object;
  8440. };
  8441. // Backwards compatibility
  8442. THREE.ParticleSystem = function ( geometry, material ) {
  8443. console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  8444. return new THREE.PointCloud( geometry, material );
  8445. };
  8446. /**
  8447. * @author mrdoob / http://mrdoob.com/
  8448. */
  8449. THREE.Line = function ( geometry, material, type ) {
  8450. THREE.Object3D.call( this );
  8451. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8452. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8453. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8454. };
  8455. THREE.LineStrip = 0;
  8456. THREE.LinePieces = 1;
  8457. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8458. THREE.Line.prototype.raycast = ( function () {
  8459. var inverseMatrix = new THREE.Matrix4();
  8460. var ray = new THREE.Ray();
  8461. var sphere = new THREE.Sphere();
  8462. return function ( raycaster, intersects ) {
  8463. var precision = raycaster.linePrecision;
  8464. var precisionSq = precision * precision;
  8465. var geometry = this.geometry;
  8466. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8467. // Checking boundingSphere distance to ray
  8468. sphere.copy( geometry.boundingSphere );
  8469. sphere.applyMatrix4( this.matrixWorld );
  8470. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8471. return;
  8472. }
  8473. inverseMatrix.getInverse( this.matrixWorld );
  8474. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8475. /* if ( geometry instanceof THREE.BufferGeometry ) {
  8476. } else */ if ( geometry instanceof THREE.Geometry ) {
  8477. var vertices = geometry.vertices;
  8478. var nbVertices = vertices.length;
  8479. var interSegment = new THREE.Vector3();
  8480. var interRay = new THREE.Vector3();
  8481. var step = this.type === THREE.LineStrip ? 1 : 2;
  8482. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  8483. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  8484. if ( distSq > precisionSq ) continue;
  8485. var distance = ray.origin.distanceTo( interRay );
  8486. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  8487. intersects.push( {
  8488. distance: distance,
  8489. // What do we want? intersection point on the ray or on the segment??
  8490. // point: raycaster.ray.at( distance ),
  8491. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  8492. face: null,
  8493. faceIndex: null,
  8494. object: this
  8495. } );
  8496. }
  8497. }
  8498. };
  8499. }() );
  8500. THREE.Line.prototype.clone = function ( object ) {
  8501. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8502. THREE.Object3D.prototype.clone.call( this, object );
  8503. return object;
  8504. };
  8505. /**
  8506. * @author mrdoob / http://mrdoob.com/
  8507. * @author alteredq / http://alteredqualia.com/
  8508. * @author mikael emtinger / http://gomo.se/
  8509. * @author jonobr1 / http://jonobr1.com/
  8510. */
  8511. THREE.Mesh = function ( geometry, material ) {
  8512. THREE.Object3D.call( this );
  8513. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8514. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8515. this.updateMorphTargets();
  8516. };
  8517. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8518. THREE.Mesh.prototype.updateMorphTargets = function () {
  8519. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8520. this.morphTargetBase = -1;
  8521. this.morphTargetForcedOrder = [];
  8522. this.morphTargetInfluences = [];
  8523. this.morphTargetDictionary = {};
  8524. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8525. this.morphTargetInfluences.push( 0 );
  8526. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8527. }
  8528. }
  8529. };
  8530. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8531. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8532. return this.morphTargetDictionary[ name ];
  8533. }
  8534. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8535. return 0;
  8536. };
  8537. THREE.Mesh.prototype.raycast = ( function () {
  8538. var inverseMatrix = new THREE.Matrix4();
  8539. var ray = new THREE.Ray();
  8540. var sphere = new THREE.Sphere();
  8541. var vA = new THREE.Vector3();
  8542. var vB = new THREE.Vector3();
  8543. var vC = new THREE.Vector3();
  8544. return function ( raycaster, intersects ) {
  8545. var geometry = this.geometry;
  8546. // Checking boundingSphere distance to ray
  8547. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8548. sphere.copy( geometry.boundingSphere );
  8549. sphere.applyMatrix4( this.matrixWorld );
  8550. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8551. return;
  8552. }
  8553. // Check boundingBox before continuing
  8554. inverseMatrix.getInverse( this.matrixWorld );
  8555. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8556. if ( geometry.boundingBox !== null ) {
  8557. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8558. return;
  8559. }
  8560. }
  8561. if ( geometry instanceof THREE.BufferGeometry ) {
  8562. var material = this.material;
  8563. if ( material === undefined ) return;
  8564. var attributes = geometry.attributes;
  8565. var a, b, c;
  8566. var precision = raycaster.precision;
  8567. if ( attributes.index !== undefined ) {
  8568. var indices = attributes.index.array;
  8569. var positions = attributes.position.array;
  8570. var offsets = geometry.offsets;
  8571. if ( offsets.length === 0 ) {
  8572. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  8573. }
  8574. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8575. var start = offsets[ oi ].start;
  8576. var count = offsets[ oi ].count;
  8577. var index = offsets[ oi ].index;
  8578. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8579. a = index + indices[ i ];
  8580. b = index + indices[ i + 1 ];
  8581. c = index + indices[ i + 2 ];
  8582. vA.set(
  8583. positions[ a * 3 ],
  8584. positions[ a * 3 + 1 ],
  8585. positions[ a * 3 + 2 ]
  8586. );
  8587. vB.set(
  8588. positions[ b * 3 ],
  8589. positions[ b * 3 + 1 ],
  8590. positions[ b * 3 + 2 ]
  8591. );
  8592. vC.set(
  8593. positions[ c * 3 ],
  8594. positions[ c * 3 + 1 ],
  8595. positions[ c * 3 + 2 ]
  8596. );
  8597. if ( material.side === THREE.BackSide ) {
  8598. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8599. } else {
  8600. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8601. }
  8602. if ( intersectionPoint === null ) continue;
  8603. intersectionPoint.applyMatrix4( this.matrixWorld );
  8604. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8605. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8606. intersects.push( {
  8607. distance: distance,
  8608. point: intersectionPoint,
  8609. indices: [a, b, c],
  8610. face: null,
  8611. faceIndex: null,
  8612. object: this
  8613. } );
  8614. }
  8615. }
  8616. } else {
  8617. var positions = attributes.position.array;
  8618. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  8619. a = i;
  8620. b = i + 1;
  8621. c = i + 2;
  8622. vA.set(
  8623. positions[ j ],
  8624. positions[ j + 1 ],
  8625. positions[ j + 2 ]
  8626. );
  8627. vB.set(
  8628. positions[ j + 3 ],
  8629. positions[ j + 4 ],
  8630. positions[ j + 5 ]
  8631. );
  8632. vC.set(
  8633. positions[ j + 6 ],
  8634. positions[ j + 7 ],
  8635. positions[ j + 8 ]
  8636. );
  8637. if ( material.side === THREE.BackSide ) {
  8638. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8639. } else {
  8640. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8641. }
  8642. if ( intersectionPoint === null ) continue;
  8643. intersectionPoint.applyMatrix4( this.matrixWorld );
  8644. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8645. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8646. intersects.push( {
  8647. distance: distance,
  8648. point: intersectionPoint,
  8649. indices: [ a, b, c ],
  8650. face: null,
  8651. faceIndex: null,
  8652. object: this
  8653. } );
  8654. }
  8655. }
  8656. } else if ( geometry instanceof THREE.Geometry ) {
  8657. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  8658. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  8659. var a, b, c, d;
  8660. var precision = raycaster.precision;
  8661. var vertices = geometry.vertices;
  8662. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8663. var face = geometry.faces[ f ];
  8664. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  8665. if ( material === undefined ) continue;
  8666. a = vertices[ face.a ];
  8667. b = vertices[ face.b ];
  8668. c = vertices[ face.c ];
  8669. if ( material.morphTargets === true ) {
  8670. var morphTargets = geometry.morphTargets;
  8671. var morphInfluences = this.morphTargetInfluences;
  8672. vA.set( 0, 0, 0 );
  8673. vB.set( 0, 0, 0 );
  8674. vC.set( 0, 0, 0 );
  8675. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8676. var influence = morphInfluences[ t ];
  8677. if ( influence === 0 ) continue;
  8678. var targets = morphTargets[ t ].vertices;
  8679. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  8680. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  8681. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  8682. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  8683. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  8684. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  8685. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  8686. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  8687. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  8688. }
  8689. vA.add( a );
  8690. vB.add( b );
  8691. vC.add( c );
  8692. a = vA;
  8693. b = vB;
  8694. c = vC;
  8695. }
  8696. if ( material.side === THREE.BackSide ) {
  8697. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  8698. } else {
  8699. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  8700. }
  8701. if ( intersectionPoint === null ) continue;
  8702. intersectionPoint.applyMatrix4( this.matrixWorld );
  8703. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8704. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8705. intersects.push( {
  8706. distance: distance,
  8707. point: intersectionPoint,
  8708. face: face,
  8709. faceIndex: f,
  8710. object: this
  8711. } );
  8712. }
  8713. }
  8714. };
  8715. }() );
  8716. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  8717. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8718. THREE.Object3D.prototype.clone.call( this, object, recursive );
  8719. return object;
  8720. };
  8721. /**
  8722. * @author mikael emtinger / http://gomo.se/
  8723. * @author alteredq / http://alteredqualia.com/
  8724. */
  8725. THREE.Bone = function( belongsToSkin ) {
  8726. THREE.Object3D.call( this );
  8727. this.skin = belongsToSkin;
  8728. this.skinMatrix = new THREE.Matrix4();
  8729. this.accumulatedRotWeight = 0;
  8730. this.accumulatedPosWeight = 0;
  8731. this.accumulatedSclWeight = 0;
  8732. };
  8733. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8734. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8735. // update local
  8736. if ( this.matrixAutoUpdate ) {
  8737. forceUpdate |= this.updateMatrix();
  8738. }
  8739. // update skin matrix
  8740. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8741. if ( parentSkinMatrix ) {
  8742. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8743. } else {
  8744. this.skinMatrix.copy( this.matrix );
  8745. }
  8746. this.matrixWorldNeedsUpdate = false;
  8747. forceUpdate = true;
  8748. // Reset weights to be re-accumulated in the next frame
  8749. this.accumulatedRotWeight = 0;
  8750. this.accumulatedPosWeight = 0;
  8751. this.accumulatedSclWeight = 0;
  8752. }
  8753. // update children
  8754. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8755. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8756. }
  8757. };
  8758. /**
  8759. * @author mikael emtinger / http://gomo.se/
  8760. * @author alteredq / http://alteredqualia.com/
  8761. * @author michael guerrero / http://realitymeltdown.com
  8762. */
  8763. THREE.Skeleton = function ( boneList, useVertexTexture ) {
  8764. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8765. // init bones
  8766. this.bones = [];
  8767. this.boneMatrices = [];
  8768. var bone, gbone, p, q, s;
  8769. if ( boneList !== undefined ) {
  8770. for ( var b = 0; b < boneList.length; ++b ) {
  8771. gbone = boneList[ b ];
  8772. p = gbone.pos;
  8773. q = gbone.rotq;
  8774. s = gbone.scl;
  8775. bone = this.addBone();
  8776. bone.name = gbone.name;
  8777. bone.position.set( p[0], p[1], p[2] );
  8778. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8779. if ( s !== undefined ) {
  8780. bone.scale.set( s[0], s[1], s[2] );
  8781. } else {
  8782. bone.scale.set( 1, 1, 1 );
  8783. }
  8784. }
  8785. for ( var b = 0; b < boneList.length; ++b ) {
  8786. gbone = boneList[ b ];
  8787. if ( gbone.parent !== -1 ) {
  8788. this.bones[ gbone.parent ].add( this.bones[ b ] );
  8789. }
  8790. }
  8791. //
  8792. var nBones = this.bones.length;
  8793. if ( this.useVertexTexture ) {
  8794. // layout (1 matrix = 4 pixels)
  8795. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8796. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8797. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8798. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8799. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8800. var size;
  8801. if ( nBones > 256 )
  8802. size = 64;
  8803. else if ( nBones > 64 )
  8804. size = 32;
  8805. else if ( nBones > 16 )
  8806. size = 16;
  8807. else
  8808. size = 8;
  8809. this.boneTextureWidth = size;
  8810. this.boneTextureHeight = size;
  8811. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8812. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8813. this.boneTexture.minFilter = THREE.NearestFilter;
  8814. this.boneTexture.magFilter = THREE.NearestFilter;
  8815. this.boneTexture.generateMipmaps = false;
  8816. this.boneTexture.flipY = false;
  8817. } else {
  8818. this.boneMatrices = new Float32Array( 16 * nBones );
  8819. }
  8820. }
  8821. };
  8822. THREE.Skeleton.prototype = Object.create( THREE.Mesh.prototype );
  8823. THREE.Skeleton.prototype.addBone = function( bone ) {
  8824. if ( bone === undefined ) {
  8825. bone = new THREE.Bone( this );
  8826. }
  8827. this.bones.push( bone );
  8828. return bone;
  8829. };
  8830. THREE.Skeleton.prototype.calculateInverses = function( bone ) {
  8831. this.boneInverses = [];
  8832. for ( var b = 0, bl = this.bones.length; b < bl; ++b ) {
  8833. var inverse = new THREE.Matrix4();
  8834. inverse.getInverse( this.bones[ b ].skinMatrix );
  8835. this.boneInverses.push( inverse );
  8836. }
  8837. };
  8838. /**
  8839. * @author mikael emtinger / http://gomo.se/
  8840. * @author alteredq / http://alteredqualia.com/
  8841. */
  8842. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8843. THREE.Mesh.call( this, geometry, material );
  8844. this.skeleton = new THREE.Skeleton( this.geometry && this.geometry.bones, useVertexTexture );
  8845. // Add root level bones as children of the mesh
  8846. for ( var b = 0; b < this.skeleton.bones.length; ++b ) {
  8847. var bone = this.skeleton.bones[ b ];
  8848. if ( bone.parent === undefined ) {
  8849. this.add( bone );
  8850. }
  8851. }
  8852. this.identityMatrix = new THREE.Matrix4();
  8853. this.pose();
  8854. };
  8855. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8856. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8857. var offsetMatrix = new THREE.Matrix4();
  8858. return function ( force ) {
  8859. this.matrixAutoUpdate && this.updateMatrix();
  8860. // update matrixWorld
  8861. if ( this.matrixWorldNeedsUpdate || force ) {
  8862. if ( this.parent ) {
  8863. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8864. } else {
  8865. this.matrixWorld.copy( this.matrix );
  8866. }
  8867. this.matrixWorldNeedsUpdate = false;
  8868. force = true;
  8869. }
  8870. // update children
  8871. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8872. var child = this.children[ i ];
  8873. if ( child instanceof THREE.Bone ) {
  8874. child.update( this.identityMatrix, false );
  8875. } else {
  8876. child.updateMatrixWorld( true );
  8877. }
  8878. }
  8879. // make a snapshot of the bones' rest position
  8880. if ( this.skeleton.boneInverses === undefined ) {
  8881. this.skeleton.calculateInverses();
  8882. }
  8883. // flatten bone matrices to array
  8884. for ( var b = 0, bl = this.skeleton.bones.length; b < bl; b ++ ) {
  8885. // compute the offset between the current and the original transform;
  8886. // TODO: we could get rid of this multiplication step if the skinMatrix
  8887. // was already representing the offset; however, this requires some
  8888. // major changes to the animation system
  8889. offsetMatrix.multiplyMatrices( this.skeleton.bones[ b ].skinMatrix, this.skeleton.boneInverses[ b ] );
  8890. offsetMatrix.flattenToArrayOffset( this.skeleton.boneMatrices, b * 16 );
  8891. }
  8892. if ( this.skeleton.useVertexTexture ) {
  8893. this.skeleton.boneTexture.needsUpdate = true;
  8894. }
  8895. };
  8896. }();
  8897. THREE.SkinnedMesh.prototype.pose = function () {
  8898. this.updateMatrixWorld( true );
  8899. this.normalizeSkinWeights();
  8900. };
  8901. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8902. if ( this.geometry instanceof THREE.Geometry ) {
  8903. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8904. var sw = this.geometry.skinWeights[ i ];
  8905. var scale = 1.0 / sw.lengthManhattan();
  8906. if ( scale !== Infinity ) {
  8907. sw.multiplyScalar( scale );
  8908. } else {
  8909. sw.set( 1 ); // this will be normalized by the shader anyway
  8910. }
  8911. }
  8912. } else {
  8913. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8914. }
  8915. };
  8916. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8917. if ( object === undefined ) {
  8918. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8919. }
  8920. THREE.Mesh.prototype.clone.call( this, object );
  8921. return object;
  8922. };
  8923. /**
  8924. * @author alteredq / http://alteredqualia.com/
  8925. */
  8926. THREE.MorphAnimMesh = function ( geometry, material ) {
  8927. THREE.Mesh.call( this, geometry, material );
  8928. // API
  8929. this.duration = 1000; // milliseconds
  8930. this.mirroredLoop = false;
  8931. this.time = 0;
  8932. // internals
  8933. this.lastKeyframe = 0;
  8934. this.currentKeyframe = 0;
  8935. this.direction = 1;
  8936. this.directionBackwards = false;
  8937. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8938. };
  8939. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8940. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8941. this.startKeyframe = start;
  8942. this.endKeyframe = end;
  8943. this.length = this.endKeyframe - this.startKeyframe + 1;
  8944. };
  8945. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8946. this.direction = 1;
  8947. this.directionBackwards = false;
  8948. };
  8949. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8950. this.direction = -1;
  8951. this.directionBackwards = true;
  8952. };
  8953. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8954. var geometry = this.geometry;
  8955. if ( ! geometry.animations ) geometry.animations = {};
  8956. var firstAnimation, animations = geometry.animations;
  8957. var pattern = /([a-z]+)_?(\d+)/;
  8958. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8959. var morph = geometry.morphTargets[ i ];
  8960. var parts = morph.name.match( pattern );
  8961. if ( parts && parts.length > 1 ) {
  8962. var label = parts[ 1 ];
  8963. var num = parts[ 2 ];
  8964. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8965. var animation = animations[ label ];
  8966. if ( i < animation.start ) animation.start = i;
  8967. if ( i > animation.end ) animation.end = i;
  8968. if ( ! firstAnimation ) firstAnimation = label;
  8969. }
  8970. }
  8971. geometry.firstAnimation = firstAnimation;
  8972. };
  8973. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8974. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8975. this.geometry.animations[ label ] = { start: start, end: end };
  8976. };
  8977. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8978. var animation = this.geometry.animations[ label ];
  8979. if ( animation ) {
  8980. this.setFrameRange( animation.start, animation.end );
  8981. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8982. this.time = 0;
  8983. } else {
  8984. console.warn( "animation[" + label + "] undefined" );
  8985. }
  8986. };
  8987. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8988. var frameTime = this.duration / this.length;
  8989. this.time += this.direction * delta;
  8990. if ( this.mirroredLoop ) {
  8991. if ( this.time > this.duration || this.time < 0 ) {
  8992. this.direction *= -1;
  8993. if ( this.time > this.duration ) {
  8994. this.time = this.duration;
  8995. this.directionBackwards = true;
  8996. }
  8997. if ( this.time < 0 ) {
  8998. this.time = 0;
  8999. this.directionBackwards = false;
  9000. }
  9001. }
  9002. } else {
  9003. this.time = this.time % this.duration;
  9004. if ( this.time < 0 ) this.time += this.duration;
  9005. }
  9006. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9007. if ( keyframe !== this.currentKeyframe ) {
  9008. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9009. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9010. this.morphTargetInfluences[ keyframe ] = 0;
  9011. this.lastKeyframe = this.currentKeyframe;
  9012. this.currentKeyframe = keyframe;
  9013. }
  9014. var mix = ( this.time % frameTime ) / frameTime;
  9015. if ( this.directionBackwards ) {
  9016. mix = 1 - mix;
  9017. }
  9018. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9019. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9020. };
  9021. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9022. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9023. object.duration = this.duration;
  9024. object.mirroredLoop = this.mirroredLoop;
  9025. object.time = this.time;
  9026. object.lastKeyframe = this.lastKeyframe;
  9027. object.currentKeyframe = this.currentKeyframe;
  9028. object.direction = this.direction;
  9029. object.directionBackwards = this.directionBackwards;
  9030. THREE.Mesh.prototype.clone.call( this, object );
  9031. return object;
  9032. };
  9033. /**
  9034. * @author mikael emtinger / http://gomo.se/
  9035. * @author alteredq / http://alteredqualia.com/
  9036. * @author mrdoob / http://mrdoob.com/
  9037. */
  9038. THREE.LOD = function () {
  9039. THREE.Object3D.call( this );
  9040. this.objects = [];
  9041. };
  9042. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9043. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9044. if ( distance === undefined ) distance = 0;
  9045. distance = Math.abs( distance );
  9046. for ( var l = 0; l < this.objects.length; l ++ ) {
  9047. if ( distance < this.objects[ l ].distance ) {
  9048. break;
  9049. }
  9050. }
  9051. this.objects.splice( l, 0, { distance: distance, object: object } );
  9052. this.add( object );
  9053. };
  9054. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9055. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9056. if ( distance < this.objects[ i ].distance ) {
  9057. break;
  9058. }
  9059. }
  9060. return this.objects[ i - 1 ].object;
  9061. };
  9062. THREE.LOD.prototype.raycast = ( function () {
  9063. var matrixPosition = new THREE.Vector3();
  9064. return function ( raycaster, intersects ) {
  9065. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9066. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9067. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9068. };
  9069. }() );
  9070. THREE.LOD.prototype.update = function () {
  9071. var v1 = new THREE.Vector3();
  9072. var v2 = new THREE.Vector3();
  9073. return function ( camera ) {
  9074. if ( this.objects.length > 1 ) {
  9075. v1.setFromMatrixPosition( camera.matrixWorld );
  9076. v2.setFromMatrixPosition( this.matrixWorld );
  9077. var distance = v1.distanceTo( v2 );
  9078. this.objects[ 0 ].object.visible = true;
  9079. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9080. if ( distance >= this.objects[ i ].distance ) {
  9081. this.objects[ i - 1 ].object.visible = false;
  9082. this.objects[ i ].object.visible = true;
  9083. } else {
  9084. break;
  9085. }
  9086. }
  9087. for( ; i < l; i ++ ) {
  9088. this.objects[ i ].object.visible = false;
  9089. }
  9090. }
  9091. };
  9092. }();
  9093. THREE.LOD.prototype.clone = function ( object ) {
  9094. if ( object === undefined ) object = new THREE.LOD();
  9095. THREE.Object3D.prototype.clone.call( this, object );
  9096. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9097. var x = this.objects[i].object.clone();
  9098. x.visible = i === 0;
  9099. object.addLevel( x, this.objects[i].distance );
  9100. }
  9101. return object;
  9102. };
  9103. /**
  9104. * @author mikael emtinger / http://gomo.se/
  9105. * @author alteredq / http://alteredqualia.com/
  9106. */
  9107. THREE.Sprite = ( function () {
  9108. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9109. var geometry = new THREE.BufferGeometry();
  9110. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9111. return function ( material ) {
  9112. THREE.Object3D.call( this );
  9113. this.geometry = geometry;
  9114. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9115. };
  9116. } )();
  9117. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9118. THREE.Sprite.prototype.raycast = ( function () {
  9119. var matrixPosition = new THREE.Vector3();
  9120. return function ( raycaster, intersects ) {
  9121. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9122. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9123. if ( distance > this.scale.x ) {
  9124. return;
  9125. }
  9126. intersects.push( {
  9127. distance: distance,
  9128. point: this.position,
  9129. face: null,
  9130. object: this
  9131. } );
  9132. };
  9133. }() );
  9134. THREE.Sprite.prototype.updateMatrix = function () {
  9135. this.matrix.compose( this.position, this.quaternion, this.scale );
  9136. this.matrixWorldNeedsUpdate = true;
  9137. };
  9138. THREE.Sprite.prototype.clone = function ( object ) {
  9139. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9140. THREE.Object3D.prototype.clone.call( this, object );
  9141. return object;
  9142. };
  9143. // Backwards compatibility
  9144. THREE.Particle = THREE.Sprite;
  9145. /**
  9146. * @author mrdoob / http://mrdoob.com/
  9147. */
  9148. THREE.Scene = function () {
  9149. THREE.Object3D.call( this );
  9150. this.fog = null;
  9151. this.overrideMaterial = null;
  9152. this.autoUpdate = true; // checked by the renderer
  9153. this.matrixAutoUpdate = false;
  9154. this.__lights = [];
  9155. this.__objectsAdded = [];
  9156. this.__objectsRemoved = [];
  9157. };
  9158. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9159. THREE.Scene.prototype.__addObject = function ( object ) {
  9160. if ( object instanceof THREE.Light ) {
  9161. if ( this.__lights.indexOf( object ) === - 1 ) {
  9162. this.__lights.push( object );
  9163. }
  9164. if ( object.target && object.target.parent === undefined ) {
  9165. this.add( object.target );
  9166. }
  9167. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9168. this.__objectsAdded.push( object );
  9169. // check if previously removed
  9170. var i = this.__objectsRemoved.indexOf( object );
  9171. if ( i !== -1 ) {
  9172. this.__objectsRemoved.splice( i, 1 );
  9173. }
  9174. }
  9175. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9176. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9177. for ( var c = 0; c < object.children.length; c ++ ) {
  9178. this.__addObject( object.children[ c ] );
  9179. }
  9180. };
  9181. THREE.Scene.prototype.__removeObject = function ( object ) {
  9182. if ( object instanceof THREE.Light ) {
  9183. var i = this.__lights.indexOf( object );
  9184. if ( i !== -1 ) {
  9185. this.__lights.splice( i, 1 );
  9186. }
  9187. if ( object.shadowCascadeArray ) {
  9188. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9189. this.__removeObject( object.shadowCascadeArray[ x ] );
  9190. }
  9191. }
  9192. } else if ( !( object instanceof THREE.Camera ) ) {
  9193. this.__objectsRemoved.push( object );
  9194. // check if previously added
  9195. var i = this.__objectsAdded.indexOf( object );
  9196. if ( i !== -1 ) {
  9197. this.__objectsAdded.splice( i, 1 );
  9198. }
  9199. }
  9200. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9201. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9202. for ( var c = 0; c < object.children.length; c ++ ) {
  9203. this.__removeObject( object.children[ c ] );
  9204. }
  9205. };
  9206. THREE.Scene.prototype.clone = function ( object ) {
  9207. if ( object === undefined ) object = new THREE.Scene();
  9208. THREE.Object3D.prototype.clone.call(this, object);
  9209. if ( this.fog !== null ) object.fog = this.fog.clone();
  9210. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9211. object.autoUpdate = this.autoUpdate;
  9212. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9213. return object;
  9214. };
  9215. /**
  9216. * @author mrdoob / http://mrdoob.com/
  9217. * @author alteredq / http://alteredqualia.com/
  9218. */
  9219. THREE.Fog = function ( color, near, far ) {
  9220. this.name = '';
  9221. this.color = new THREE.Color( color );
  9222. this.near = ( near !== undefined ) ? near : 1;
  9223. this.far = ( far !== undefined ) ? far : 1000;
  9224. };
  9225. THREE.Fog.prototype.clone = function () {
  9226. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9227. };
  9228. /**
  9229. * @author mrdoob / http://mrdoob.com/
  9230. * @author alteredq / http://alteredqualia.com/
  9231. */
  9232. THREE.FogExp2 = function ( color, density ) {
  9233. this.name = '';
  9234. this.color = new THREE.Color( color );
  9235. this.density = ( density !== undefined ) ? density : 0.00025;
  9236. };
  9237. THREE.FogExp2.prototype.clone = function () {
  9238. return new THREE.FogExp2( this.color.getHex(), this.density );
  9239. };
  9240. /**
  9241. * @author mrdoob / http://mrdoob.com/
  9242. */
  9243. THREE.CanvasRenderer = function ( parameters ) {
  9244. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9245. var smoothstep = THREE.Math.smoothstep;
  9246. parameters = parameters || {};
  9247. var _this = this,
  9248. _renderData, _elements, _lights,
  9249. _projector = new THREE.Projector(),
  9250. _canvas = parameters.canvas !== undefined
  9251. ? parameters.canvas
  9252. : document.createElement( 'canvas' ),
  9253. _canvasWidth = _canvas.width,
  9254. _canvasHeight = _canvas.height,
  9255. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9256. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9257. _context = _canvas.getContext( '2d', {
  9258. alpha: parameters.alpha === true
  9259. } ),
  9260. _clearColor = new THREE.Color( 0x000000 ),
  9261. _clearAlpha = 0,
  9262. _contextGlobalAlpha = 1,
  9263. _contextGlobalCompositeOperation = 0,
  9264. _contextStrokeStyle = null,
  9265. _contextFillStyle = null,
  9266. _contextLineWidth = null,
  9267. _contextLineCap = null,
  9268. _contextLineJoin = null,
  9269. _contextDashSize = null,
  9270. _contextGapSize = 0,
  9271. _camera,
  9272. _v1, _v2, _v3, _v4,
  9273. _v5 = new THREE.RenderableVertex(),
  9274. _v6 = new THREE.RenderableVertex(),
  9275. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9276. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9277. _color = new THREE.Color(),
  9278. _color1 = new THREE.Color(),
  9279. _color2 = new THREE.Color(),
  9280. _color3 = new THREE.Color(),
  9281. _color4 = new THREE.Color(),
  9282. _diffuseColor = new THREE.Color(),
  9283. _emissiveColor = new THREE.Color(),
  9284. _lightColor = new THREE.Color(),
  9285. _patterns = {},
  9286. _image, _uvs,
  9287. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9288. _clipBox = new THREE.Box2(),
  9289. _clearBox = new THREE.Box2(),
  9290. _elemBox = new THREE.Box2(),
  9291. _ambientLight = new THREE.Color(),
  9292. _directionalLights = new THREE.Color(),
  9293. _pointLights = new THREE.Color(),
  9294. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9295. _centroid = new THREE.Vector3(),
  9296. _normal = new THREE.Vector3(),
  9297. _normalViewMatrix = new THREE.Matrix3();
  9298. // dash+gap fallbacks for Firefox and everything else
  9299. if ( _context.setLineDash === undefined ) {
  9300. _context.setLineDash = function () {}
  9301. }
  9302. this.domElement = _canvas;
  9303. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9304. ? parameters.devicePixelRatio
  9305. : self.devicePixelRatio !== undefined
  9306. ? self.devicePixelRatio
  9307. : 1;
  9308. this.autoClear = true;
  9309. this.sortObjects = true;
  9310. this.sortElements = true;
  9311. this.info = {
  9312. render: {
  9313. vertices: 0,
  9314. faces: 0
  9315. }
  9316. }
  9317. // WebGLRenderer compatibility
  9318. this.supportsVertexTextures = function () {};
  9319. this.setFaceCulling = function () {};
  9320. this.setSize = function ( width, height, updateStyle ) {
  9321. _canvasWidth = width * this.devicePixelRatio;
  9322. _canvasHeight = height * this.devicePixelRatio;
  9323. _canvas.width = _canvasWidth;
  9324. _canvas.height = _canvasHeight;
  9325. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9326. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9327. if ( updateStyle !== false ) {
  9328. _canvas.style.width = width + 'px';
  9329. _canvas.style.height = height + 'px';
  9330. }
  9331. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9332. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9333. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9334. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9335. _contextGlobalAlpha = 1;
  9336. _contextGlobalCompositeOperation = 0;
  9337. _contextStrokeStyle = null;
  9338. _contextFillStyle = null;
  9339. _contextLineWidth = null;
  9340. _contextLineCap = null;
  9341. _contextLineJoin = null;
  9342. this.setViewport( 0, 0, width, height );
  9343. };
  9344. this.setViewport = function ( x, y, width, height ) {
  9345. var viewportX = x * this.devicePixelRatio;
  9346. var viewportY = y * this.devicePixelRatio;
  9347. var viewportWidth = width * this.devicePixelRatio;
  9348. var viewportHeight = height * this.devicePixelRatio;
  9349. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  9350. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9351. };
  9352. this.setScissor = function () {};
  9353. this.enableScissorTest = function () {};
  9354. this.setClearColor = function ( color, alpha ) {
  9355. _clearColor.set( color );
  9356. _clearAlpha = alpha !== undefined ? alpha : 1;
  9357. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9358. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9359. };
  9360. this.setClearColorHex = function ( hex, alpha ) {
  9361. console.warn( 'THREE.CanvasRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9362. this.setClearColor( hex, alpha );
  9363. };
  9364. this.getMaxAnisotropy = function () {
  9365. return 0;
  9366. };
  9367. this.clear = function () {
  9368. if ( _clearBox.empty() === false ) {
  9369. _clearBox.intersect( _clipBox );
  9370. _clearBox.expandByScalar( 2 );
  9371. if ( _clearAlpha < 1 ) {
  9372. _context.clearRect(
  9373. _clearBox.min.x | 0,
  9374. _clearBox.min.y | 0,
  9375. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9376. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9377. );
  9378. }
  9379. if ( _clearAlpha > 0 ) {
  9380. setBlending( THREE.NormalBlending );
  9381. setOpacity( 1 );
  9382. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9383. _context.fillRect(
  9384. _clearBox.min.x | 0,
  9385. _clearBox.min.y | 0,
  9386. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9387. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9388. );
  9389. }
  9390. _clearBox.makeEmpty();
  9391. }
  9392. };
  9393. // compatibility
  9394. this.clearColor = function () {};
  9395. this.clearDepth = function () {};
  9396. this.clearStencil = function () {};
  9397. this.render = function ( scene, camera ) {
  9398. if ( camera instanceof THREE.Camera === false ) {
  9399. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9400. return;
  9401. }
  9402. if ( this.autoClear === true ) this.clear();
  9403. _this.info.render.vertices = 0;
  9404. _this.info.render.faces = 0;
  9405. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9406. _elements = _renderData.elements;
  9407. _lights = _renderData.lights;
  9408. _camera = camera;
  9409. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9410. /* DEBUG
  9411. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9412. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9413. */
  9414. calculateLights();
  9415. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9416. var element = _elements[ e ];
  9417. var material = element.material;
  9418. if ( material === undefined || material.opacity === 0 ) continue;
  9419. _elemBox.makeEmpty();
  9420. if ( element instanceof THREE.RenderableSprite ) {
  9421. _v1 = element;
  9422. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9423. renderSprite( _v1, element, material );
  9424. } else if ( element instanceof THREE.RenderableLine ) {
  9425. _v1 = element.v1; _v2 = element.v2;
  9426. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9427. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9428. _elemBox.setFromPoints( [
  9429. _v1.positionScreen,
  9430. _v2.positionScreen
  9431. ] );
  9432. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9433. renderLine( _v1, _v2, element, material );
  9434. }
  9435. } else if ( element instanceof THREE.RenderableFace ) {
  9436. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9437. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9438. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9439. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9440. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9441. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9442. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9443. if ( material.overdraw > 0 ) {
  9444. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9445. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9446. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9447. }
  9448. _elemBox.setFromPoints( [
  9449. _v1.positionScreen,
  9450. _v2.positionScreen,
  9451. _v3.positionScreen
  9452. ] );
  9453. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9454. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9455. }
  9456. }
  9457. /* DEBUG
  9458. setLineWidth( 1 );
  9459. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9460. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9461. */
  9462. _clearBox.union( _elemBox );
  9463. }
  9464. /* DEBUG
  9465. setLineWidth( 1 );
  9466. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9467. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9468. */
  9469. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9470. };
  9471. //
  9472. function calculateLights() {
  9473. _ambientLight.setRGB( 0, 0, 0 );
  9474. _directionalLights.setRGB( 0, 0, 0 );
  9475. _pointLights.setRGB( 0, 0, 0 );
  9476. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9477. var light = _lights[ l ];
  9478. var lightColor = light.color;
  9479. if ( light instanceof THREE.AmbientLight ) {
  9480. _ambientLight.add( lightColor );
  9481. } else if ( light instanceof THREE.DirectionalLight ) {
  9482. // for sprites
  9483. _directionalLights.add( lightColor );
  9484. } else if ( light instanceof THREE.PointLight ) {
  9485. // for sprites
  9486. _pointLights.add( lightColor );
  9487. }
  9488. }
  9489. }
  9490. function calculateLight( position, normal, color ) {
  9491. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9492. var light = _lights[ l ];
  9493. _lightColor.copy( light.color );
  9494. if ( light instanceof THREE.DirectionalLight ) {
  9495. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9496. var amount = normal.dot( lightPosition );
  9497. if ( amount <= 0 ) continue;
  9498. amount *= light.intensity;
  9499. color.add( _lightColor.multiplyScalar( amount ) );
  9500. } else if ( light instanceof THREE.PointLight ) {
  9501. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9502. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9503. if ( amount <= 0 ) continue;
  9504. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9505. if ( amount == 0 ) continue;
  9506. amount *= light.intensity;
  9507. color.add( _lightColor.multiplyScalar( amount ) );
  9508. }
  9509. }
  9510. }
  9511. function renderSprite( v1, element, material ) {
  9512. setOpacity( material.opacity );
  9513. setBlending( material.blending );
  9514. var scaleX = element.scale.x * _canvasWidthHalf;
  9515. var scaleY = element.scale.y * _canvasHeightHalf;
  9516. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9517. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9518. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9519. if ( material instanceof THREE.SpriteMaterial ) {
  9520. var texture = material.map;
  9521. if ( texture !== null ) {
  9522. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9523. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9524. textureToPattern( texture );
  9525. }
  9526. texture.addEventListener( 'update', onTextureUpdate );
  9527. }
  9528. var pattern = _patterns[ texture.id ];
  9529. if ( pattern !== undefined ) {
  9530. setFillStyle( pattern );
  9531. } else {
  9532. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9533. }
  9534. //
  9535. var bitmap = texture.image;
  9536. var ox = bitmap.width * texture.offset.x;
  9537. var oy = bitmap.height * texture.offset.y;
  9538. var sx = bitmap.width * texture.repeat.x;
  9539. var sy = bitmap.height * texture.repeat.y;
  9540. var cx = scaleX / sx;
  9541. var cy = scaleY / sy;
  9542. _context.save();
  9543. _context.translate( v1.x, v1.y );
  9544. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9545. _context.translate( - scaleX / 2, - scaleY / 2 );
  9546. _context.scale( cx, cy );
  9547. _context.translate( - ox, - oy );
  9548. _context.fillRect( ox, oy, sx, sy );
  9549. _context.restore();
  9550. } else {
  9551. // no texture
  9552. setFillStyle( material.color.getStyle() );
  9553. _context.save();
  9554. _context.translate( v1.x, v1.y );
  9555. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9556. _context.scale( scaleX, - scaleY );
  9557. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9558. _context.restore();
  9559. }
  9560. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9561. setStrokeStyle( material.color.getStyle() );
  9562. setFillStyle( material.color.getStyle() );
  9563. _context.save();
  9564. _context.translate( v1.x, v1.y );
  9565. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9566. _context.scale( scaleX, scaleY );
  9567. material.program( _context );
  9568. _context.restore();
  9569. }
  9570. /* DEBUG
  9571. setStrokeStyle( 'rgb(255,255,0)' );
  9572. _context.beginPath();
  9573. _context.moveTo( v1.x - 10, v1.y );
  9574. _context.lineTo( v1.x + 10, v1.y );
  9575. _context.moveTo( v1.x, v1.y - 10 );
  9576. _context.lineTo( v1.x, v1.y + 10 );
  9577. _context.stroke();
  9578. */
  9579. }
  9580. function renderLine( v1, v2, element, material ) {
  9581. setOpacity( material.opacity );
  9582. setBlending( material.blending );
  9583. _context.beginPath();
  9584. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9585. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9586. if ( material instanceof THREE.LineBasicMaterial ) {
  9587. setLineWidth( material.linewidth );
  9588. setLineCap( material.linecap );
  9589. setLineJoin( material.linejoin );
  9590. if ( material.vertexColors !== THREE.VertexColors ) {
  9591. setStrokeStyle( material.color.getStyle() );
  9592. } else {
  9593. var colorStyle1 = element.vertexColors[0].getStyle();
  9594. var colorStyle2 = element.vertexColors[1].getStyle();
  9595. if ( colorStyle1 === colorStyle2 ) {
  9596. setStrokeStyle( colorStyle1 );
  9597. } else {
  9598. try {
  9599. var grad = _context.createLinearGradient(
  9600. v1.positionScreen.x,
  9601. v1.positionScreen.y,
  9602. v2.positionScreen.x,
  9603. v2.positionScreen.y
  9604. );
  9605. grad.addColorStop( 0, colorStyle1 );
  9606. grad.addColorStop( 1, colorStyle2 );
  9607. } catch ( exception ) {
  9608. grad = colorStyle1;
  9609. }
  9610. setStrokeStyle( grad );
  9611. }
  9612. }
  9613. _context.stroke();
  9614. _elemBox.expandByScalar( material.linewidth * 2 );
  9615. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9616. setLineWidth( material.linewidth );
  9617. setLineCap( material.linecap );
  9618. setLineJoin( material.linejoin );
  9619. setStrokeStyle( material.color.getStyle() );
  9620. setDashAndGap( material.dashSize, material.gapSize );
  9621. _context.stroke();
  9622. _elemBox.expandByScalar( material.linewidth * 2 );
  9623. setDashAndGap( null, null );
  9624. }
  9625. }
  9626. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9627. _this.info.render.vertices += 3;
  9628. _this.info.render.faces ++;
  9629. setOpacity( material.opacity );
  9630. setBlending( material.blending );
  9631. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9632. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9633. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9634. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9635. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9636. _diffuseColor.copy( material.color );
  9637. _emissiveColor.copy( material.emissive );
  9638. if ( material.vertexColors === THREE.FaceColors ) {
  9639. _diffuseColor.multiply( element.color );
  9640. }
  9641. _color.copy( _ambientLight );
  9642. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  9643. calculateLight( _centroid, element.normalModel, _color );
  9644. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9645. material.wireframe === true
  9646. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9647. : fillPath( _color );
  9648. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9649. if ( material.map !== null ) {
  9650. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9651. _uvs = element.uvs;
  9652. 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 );
  9653. }
  9654. } else if ( material.envMap !== null ) {
  9655. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9656. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9657. _uv1x = 0.5 * _normal.x + 0.5;
  9658. _uv1y = 0.5 * _normal.y + 0.5;
  9659. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9660. _uv2x = 0.5 * _normal.x + 0.5;
  9661. _uv2y = 0.5 * _normal.y + 0.5;
  9662. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9663. _uv3x = 0.5 * _normal.x + 0.5;
  9664. _uv3y = 0.5 * _normal.y + 0.5;
  9665. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9666. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  9667. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9668. _uv1x = - 0.5 * _normal.x + 0.5;
  9669. _uv1y = - 0.5 * _normal.y + 0.5;
  9670. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9671. _uv2x = - 0.5 * _normal.x + 0.5;
  9672. _uv2y = - 0.5 * _normal.y + 0.5;
  9673. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9674. _uv3x = - 0.5 * _normal.x + 0.5;
  9675. _uv3y = - 0.5 * _normal.y + 0.5;
  9676. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9677. }
  9678. } else {
  9679. _color.copy( material.color );
  9680. if ( material.vertexColors === THREE.FaceColors ) {
  9681. _color.multiply( element.color );
  9682. }
  9683. material.wireframe === true
  9684. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9685. : fillPath( _color );
  9686. }
  9687. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9688. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  9689. material.wireframe === true
  9690. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9691. : fillPath( _color );
  9692. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9693. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9694. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9695. material.wireframe === true
  9696. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9697. : fillPath( _color );
  9698. } else {
  9699. _color.setRGB( 1, 1, 1 );
  9700. material.wireframe === true
  9701. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9702. : fillPath( _color );
  9703. }
  9704. }
  9705. //
  9706. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9707. _context.beginPath();
  9708. _context.moveTo( x0, y0 );
  9709. _context.lineTo( x1, y1 );
  9710. _context.lineTo( x2, y2 );
  9711. _context.closePath();
  9712. }
  9713. function strokePath( color, linewidth, linecap, linejoin ) {
  9714. setLineWidth( linewidth );
  9715. setLineCap( linecap );
  9716. setLineJoin( linejoin );
  9717. setStrokeStyle( color.getStyle() );
  9718. _context.stroke();
  9719. _elemBox.expandByScalar( linewidth * 2 );
  9720. }
  9721. function fillPath( color ) {
  9722. setFillStyle( color.getStyle() );
  9723. _context.fill();
  9724. }
  9725. function onTextureUpdate ( event ) {
  9726. textureToPattern( event.target );
  9727. }
  9728. function textureToPattern( texture ) {
  9729. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9730. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9731. var image = texture.image;
  9732. var canvas = document.createElement( 'canvas' );
  9733. canvas.width = image.width;
  9734. canvas.height = image.height;
  9735. var context = canvas.getContext( '2d' );
  9736. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9737. context.drawImage( image, 0, 0 );
  9738. _patterns[ texture.id ] = _context.createPattern(
  9739. canvas, repeatX === true && repeatY === true
  9740. ? 'repeat'
  9741. : repeatX === true && repeatY === false
  9742. ? 'repeat-x'
  9743. : repeatX === false && repeatY === true
  9744. ? 'repeat-y'
  9745. : 'no-repeat'
  9746. );
  9747. }
  9748. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9749. if ( texture instanceof THREE.DataTexture ) return;
  9750. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9751. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9752. textureToPattern( texture );
  9753. }
  9754. texture.addEventListener( 'update', onTextureUpdate );
  9755. }
  9756. var pattern = _patterns[ texture.id ];
  9757. if ( pattern !== undefined ) {
  9758. setFillStyle( pattern );
  9759. } else {
  9760. setFillStyle( 'rgba(0,0,0,1)' );
  9761. _context.fill();
  9762. return;
  9763. }
  9764. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9765. var a, b, c, d, e, f, det, idet,
  9766. offsetX = texture.offset.x / texture.repeat.x,
  9767. offsetY = texture.offset.y / texture.repeat.y,
  9768. width = texture.image.width * texture.repeat.x,
  9769. height = texture.image.height * texture.repeat.y;
  9770. u0 = ( u0 + offsetX ) * width;
  9771. v0 = ( v0 + offsetY ) * height;
  9772. u1 = ( u1 + offsetX ) * width;
  9773. v1 = ( v1 + offsetY ) * height;
  9774. u2 = ( u2 + offsetX ) * width;
  9775. v2 = ( v2 + offsetY ) * height;
  9776. x1 -= x0; y1 -= y0;
  9777. x2 -= x0; y2 -= y0;
  9778. u1 -= u0; v1 -= v0;
  9779. u2 -= u0; v2 -= v0;
  9780. det = u1 * v2 - u2 * v1;
  9781. if ( det === 0 ) return;
  9782. idet = 1 / det;
  9783. a = ( v2 * x1 - v1 * x2 ) * idet;
  9784. b = ( v2 * y1 - v1 * y2 ) * idet;
  9785. c = ( u1 * x2 - u2 * x1 ) * idet;
  9786. d = ( u1 * y2 - u2 * y1 ) * idet;
  9787. e = x0 - a * u0 - c * v0;
  9788. f = y0 - b * u0 - d * v0;
  9789. _context.save();
  9790. _context.transform( a, b, c, d, e, f );
  9791. _context.fill();
  9792. _context.restore();
  9793. }
  9794. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9795. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9796. var a, b, c, d, e, f, det, idet,
  9797. width = image.width - 1,
  9798. height = image.height - 1;
  9799. u0 *= width; v0 *= height;
  9800. u1 *= width; v1 *= height;
  9801. u2 *= width; v2 *= height;
  9802. x1 -= x0; y1 -= y0;
  9803. x2 -= x0; y2 -= y0;
  9804. u1 -= u0; v1 -= v0;
  9805. u2 -= u0; v2 -= v0;
  9806. det = u1 * v2 - u2 * v1;
  9807. idet = 1 / det;
  9808. a = ( v2 * x1 - v1 * x2 ) * idet;
  9809. b = ( v2 * y1 - v1 * y2 ) * idet;
  9810. c = ( u1 * x2 - u2 * x1 ) * idet;
  9811. d = ( u1 * y2 - u2 * y1 ) * idet;
  9812. e = x0 - a * u0 - c * v0;
  9813. f = y0 - b * u0 - d * v0;
  9814. _context.save();
  9815. _context.transform( a, b, c, d, e, f );
  9816. _context.clip();
  9817. _context.drawImage( image, 0, 0 );
  9818. _context.restore();
  9819. }
  9820. // Hide anti-alias gaps
  9821. function expand( v1, v2, pixels ) {
  9822. var x = v2.x - v1.x, y = v2.y - v1.y,
  9823. det = x * x + y * y, idet;
  9824. if ( det === 0 ) return;
  9825. idet = pixels / Math.sqrt( det );
  9826. x *= idet; y *= idet;
  9827. v2.x += x; v2.y += y;
  9828. v1.x -= x; v1.y -= y;
  9829. }
  9830. // Context cached methods.
  9831. function setOpacity( value ) {
  9832. if ( _contextGlobalAlpha !== value ) {
  9833. _context.globalAlpha = value;
  9834. _contextGlobalAlpha = value;
  9835. }
  9836. }
  9837. function setBlending( value ) {
  9838. if ( _contextGlobalCompositeOperation !== value ) {
  9839. if ( value === THREE.NormalBlending ) {
  9840. _context.globalCompositeOperation = 'source-over';
  9841. } else if ( value === THREE.AdditiveBlending ) {
  9842. _context.globalCompositeOperation = 'lighter';
  9843. } else if ( value === THREE.SubtractiveBlending ) {
  9844. _context.globalCompositeOperation = 'darker';
  9845. }
  9846. _contextGlobalCompositeOperation = value;
  9847. }
  9848. }
  9849. function setLineWidth( value ) {
  9850. if ( _contextLineWidth !== value ) {
  9851. _context.lineWidth = value;
  9852. _contextLineWidth = value;
  9853. }
  9854. }
  9855. function setLineCap( value ) {
  9856. // "butt", "round", "square"
  9857. if ( _contextLineCap !== value ) {
  9858. _context.lineCap = value;
  9859. _contextLineCap = value;
  9860. }
  9861. }
  9862. function setLineJoin( value ) {
  9863. // "round", "bevel", "miter"
  9864. if ( _contextLineJoin !== value ) {
  9865. _context.lineJoin = value;
  9866. _contextLineJoin = value;
  9867. }
  9868. }
  9869. function setStrokeStyle( value ) {
  9870. if ( _contextStrokeStyle !== value ) {
  9871. _context.strokeStyle = value;
  9872. _contextStrokeStyle = value;
  9873. }
  9874. }
  9875. function setFillStyle( value ) {
  9876. if ( _contextFillStyle !== value ) {
  9877. _context.fillStyle = value;
  9878. _contextFillStyle = value;
  9879. }
  9880. }
  9881. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9882. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9883. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9884. _contextDashSize = dashSizeValue;
  9885. _contextGapSize = gapSizeValue;
  9886. }
  9887. }
  9888. };
  9889. /**
  9890. * Shader chunks for WebLG Shader library
  9891. *
  9892. * @author alteredq / http://alteredqualia.com/
  9893. * @author mrdoob / http://mrdoob.com/
  9894. * @author mikael emtinger / http://gomo.se/
  9895. */
  9896. THREE.ShaderChunk = {
  9897. // FOG
  9898. fog_pars_fragment: [
  9899. "#ifdef USE_FOG",
  9900. " uniform vec3 fogColor;",
  9901. " #ifdef FOG_EXP2",
  9902. " uniform float fogDensity;",
  9903. " #else",
  9904. " uniform float fogNear;",
  9905. " uniform float fogFar;",
  9906. " #endif",
  9907. "#endif"
  9908. ].join("\n"),
  9909. fog_fragment: [
  9910. "#ifdef USE_FOG",
  9911. " #ifdef USE_LOGDEPTHBUF_EXT",
  9912. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  9913. " #else",
  9914. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9915. " #endif",
  9916. " #ifdef FOG_EXP2",
  9917. " const float LOG2 = 1.442695;",
  9918. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9919. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9920. " #else",
  9921. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9922. " #endif",
  9923. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9924. "#endif"
  9925. ].join("\n"),
  9926. // ENVIRONMENT MAP
  9927. envmap_pars_fragment: [
  9928. "#ifdef USE_ENVMAP",
  9929. " uniform float reflectivity;",
  9930. " uniform samplerCube envMap;",
  9931. " uniform float flipEnvMap;",
  9932. " uniform int combine;",
  9933. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9934. " uniform bool useRefract;",
  9935. " uniform float refractionRatio;",
  9936. " #else",
  9937. " varying vec3 vReflect;",
  9938. " #endif",
  9939. "#endif"
  9940. ].join("\n"),
  9941. envmap_fragment: [
  9942. "#ifdef USE_ENVMAP",
  9943. " vec3 reflectVec;",
  9944. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9945. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9946. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  9947. // "Transforming Normal Vectors with the Inverse Transformation"
  9948. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  9949. " if ( useRefract ) {",
  9950. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  9951. " } else { ",
  9952. " reflectVec = reflect( cameraToVertex, worldNormal );",
  9953. " }",
  9954. " #else",
  9955. " reflectVec = vReflect;",
  9956. " #endif",
  9957. " #ifdef DOUBLE_SIDED",
  9958. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9959. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9960. " #else",
  9961. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9962. " #endif",
  9963. " #ifdef GAMMA_INPUT",
  9964. " cubeColor.xyz *= cubeColor.xyz;",
  9965. " #endif",
  9966. " if ( combine == 1 ) {",
  9967. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9968. " } else if ( combine == 2 ) {",
  9969. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9970. " } else {",
  9971. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9972. " }",
  9973. "#endif"
  9974. ].join("\n"),
  9975. envmap_pars_vertex: [
  9976. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9977. " varying vec3 vReflect;",
  9978. " uniform float refractionRatio;",
  9979. " uniform bool useRefract;",
  9980. "#endif"
  9981. ].join("\n"),
  9982. worldpos_vertex : [
  9983. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9984. " #ifdef USE_SKINNING",
  9985. " vec4 worldPosition = modelMatrix * skinned;",
  9986. " #endif",
  9987. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9988. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9989. " #endif",
  9990. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9991. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9992. " #endif",
  9993. "#endif"
  9994. ].join("\n"),
  9995. envmap_vertex : [
  9996. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9997. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9998. " worldNormal = normalize( worldNormal );",
  9999. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10000. " if ( useRefract ) {",
  10001. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10002. " } else {",
  10003. " vReflect = reflect( cameraToVertex, worldNormal );",
  10004. " }",
  10005. "#endif"
  10006. ].join("\n"),
  10007. // COLOR MAP (particles)
  10008. map_particle_pars_fragment: [
  10009. "#ifdef USE_MAP",
  10010. " uniform sampler2D map;",
  10011. "#endif"
  10012. ].join("\n"),
  10013. map_particle_fragment: [
  10014. "#ifdef USE_MAP",
  10015. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10016. "#endif"
  10017. ].join("\n"),
  10018. // COLOR MAP (triangles)
  10019. map_pars_vertex: [
  10020. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10021. " varying vec2 vUv;",
  10022. " uniform vec4 offsetRepeat;",
  10023. "#endif"
  10024. ].join("\n"),
  10025. map_pars_fragment: [
  10026. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10027. " varying vec2 vUv;",
  10028. "#endif",
  10029. "#ifdef USE_MAP",
  10030. " uniform sampler2D map;",
  10031. "#endif"
  10032. ].join("\n"),
  10033. map_vertex: [
  10034. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10035. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10036. "#endif"
  10037. ].join("\n"),
  10038. map_fragment: [
  10039. "#ifdef USE_MAP",
  10040. " vec4 texelColor = texture2D( map, vUv );",
  10041. " #ifdef GAMMA_INPUT",
  10042. " texelColor.xyz *= texelColor.xyz;",
  10043. " #endif",
  10044. " gl_FragColor = gl_FragColor * texelColor;",
  10045. "#endif"
  10046. ].join("\n"),
  10047. // LIGHT MAP
  10048. lightmap_pars_fragment: [
  10049. "#ifdef USE_LIGHTMAP",
  10050. " varying vec2 vUv2;",
  10051. " uniform sampler2D lightMap;",
  10052. "#endif"
  10053. ].join("\n"),
  10054. lightmap_pars_vertex: [
  10055. "#ifdef USE_LIGHTMAP",
  10056. " varying vec2 vUv2;",
  10057. "#endif"
  10058. ].join("\n"),
  10059. lightmap_fragment: [
  10060. "#ifdef USE_LIGHTMAP",
  10061. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10062. "#endif"
  10063. ].join("\n"),
  10064. lightmap_vertex: [
  10065. "#ifdef USE_LIGHTMAP",
  10066. " vUv2 = uv2;",
  10067. "#endif"
  10068. ].join("\n"),
  10069. // BUMP MAP
  10070. bumpmap_pars_fragment: [
  10071. "#ifdef USE_BUMPMAP",
  10072. " uniform sampler2D bumpMap;",
  10073. " uniform float bumpScale;",
  10074. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10075. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10076. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10077. " vec2 dHdxy_fwd() {",
  10078. " vec2 dSTdx = dFdx( vUv );",
  10079. " vec2 dSTdy = dFdy( vUv );",
  10080. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10081. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10082. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10083. " return vec2( dBx, dBy );",
  10084. " }",
  10085. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10086. " vec3 vSigmaX = dFdx( surf_pos );",
  10087. " vec3 vSigmaY = dFdy( surf_pos );",
  10088. " vec3 vN = surf_norm;", // normalized
  10089. " vec3 R1 = cross( vSigmaY, vN );",
  10090. " vec3 R2 = cross( vN, vSigmaX );",
  10091. " float fDet = dot( vSigmaX, R1 );",
  10092. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10093. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10094. " }",
  10095. "#endif"
  10096. ].join("\n"),
  10097. // NORMAL MAP
  10098. normalmap_pars_fragment: [
  10099. "#ifdef USE_NORMALMAP",
  10100. " uniform sampler2D normalMap;",
  10101. " uniform vec2 normalScale;",
  10102. // Per-Pixel Tangent Space Normal Mapping
  10103. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10104. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10105. " vec3 q0 = dFdx( eye_pos.xyz );",
  10106. " vec3 q1 = dFdy( eye_pos.xyz );",
  10107. " vec2 st0 = dFdx( vUv.st );",
  10108. " vec2 st1 = dFdy( vUv.st );",
  10109. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10110. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10111. " vec3 N = normalize( surf_norm );",
  10112. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10113. " mapN.xy = normalScale * mapN.xy;",
  10114. " mat3 tsn = mat3( S, T, N );",
  10115. " return normalize( tsn * mapN );",
  10116. " }",
  10117. "#endif"
  10118. ].join("\n"),
  10119. // SPECULAR MAP
  10120. specularmap_pars_fragment: [
  10121. "#ifdef USE_SPECULARMAP",
  10122. " uniform sampler2D specularMap;",
  10123. "#endif"
  10124. ].join("\n"),
  10125. specularmap_fragment: [
  10126. "float specularStrength;",
  10127. "#ifdef USE_SPECULARMAP",
  10128. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10129. " specularStrength = texelSpecular.r;",
  10130. "#else",
  10131. " specularStrength = 1.0;",
  10132. "#endif"
  10133. ].join("\n"),
  10134. // LIGHTS LAMBERT
  10135. lights_lambert_pars_vertex: [
  10136. "uniform vec3 ambient;",
  10137. "uniform vec3 diffuse;",
  10138. "uniform vec3 emissive;",
  10139. "uniform vec3 ambientLightColor;",
  10140. "#if MAX_DIR_LIGHTS > 0",
  10141. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10142. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10143. "#endif",
  10144. "#if MAX_HEMI_LIGHTS > 0",
  10145. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10146. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10147. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10148. "#endif",
  10149. "#if MAX_POINT_LIGHTS > 0",
  10150. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10151. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10152. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10153. "#endif",
  10154. "#if MAX_SPOT_LIGHTS > 0",
  10155. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10156. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10157. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10158. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10159. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10160. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10161. "#endif",
  10162. "#ifdef WRAP_AROUND",
  10163. " uniform vec3 wrapRGB;",
  10164. "#endif"
  10165. ].join("\n"),
  10166. lights_lambert_vertex: [
  10167. "vLightFront = vec3( 0.0 );",
  10168. "#ifdef DOUBLE_SIDED",
  10169. " vLightBack = vec3( 0.0 );",
  10170. "#endif",
  10171. "transformedNormal = normalize( transformedNormal );",
  10172. "#if MAX_DIR_LIGHTS > 0",
  10173. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10174. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10175. " vec3 dirVector = normalize( lDirection.xyz );",
  10176. " float dotProduct = dot( transformedNormal, dirVector );",
  10177. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10178. " #ifdef DOUBLE_SIDED",
  10179. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10180. " #ifdef WRAP_AROUND",
  10181. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10182. " #endif",
  10183. " #endif",
  10184. " #ifdef WRAP_AROUND",
  10185. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10186. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10187. " #ifdef DOUBLE_SIDED",
  10188. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10189. " #endif",
  10190. " #endif",
  10191. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10192. " #ifdef DOUBLE_SIDED",
  10193. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10194. " #endif",
  10195. "}",
  10196. "#endif",
  10197. "#if MAX_POINT_LIGHTS > 0",
  10198. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10199. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10200. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10201. " float lDistance = 1.0;",
  10202. " if ( pointLightDistance[ i ] > 0.0 )",
  10203. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10204. " lVector = normalize( lVector );",
  10205. " float dotProduct = dot( transformedNormal, lVector );",
  10206. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10207. " #ifdef DOUBLE_SIDED",
  10208. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10209. " #ifdef WRAP_AROUND",
  10210. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10211. " #endif",
  10212. " #endif",
  10213. " #ifdef WRAP_AROUND",
  10214. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10215. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10216. " #ifdef DOUBLE_SIDED",
  10217. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10218. " #endif",
  10219. " #endif",
  10220. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10221. " #ifdef DOUBLE_SIDED",
  10222. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10223. " #endif",
  10224. " }",
  10225. "#endif",
  10226. "#if MAX_SPOT_LIGHTS > 0",
  10227. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10228. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10229. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10230. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10231. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10232. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10233. " float lDistance = 1.0;",
  10234. " if ( spotLightDistance[ i ] > 0.0 )",
  10235. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10236. " lVector = normalize( lVector );",
  10237. " float dotProduct = dot( transformedNormal, lVector );",
  10238. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10239. " #ifdef DOUBLE_SIDED",
  10240. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10241. " #ifdef WRAP_AROUND",
  10242. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10243. " #endif",
  10244. " #endif",
  10245. " #ifdef WRAP_AROUND",
  10246. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10247. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10248. " #ifdef DOUBLE_SIDED",
  10249. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10250. " #endif",
  10251. " #endif",
  10252. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10253. " #ifdef DOUBLE_SIDED",
  10254. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10255. " #endif",
  10256. " }",
  10257. " }",
  10258. "#endif",
  10259. "#if MAX_HEMI_LIGHTS > 0",
  10260. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10261. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10262. " vec3 lVector = normalize( lDirection.xyz );",
  10263. " float dotProduct = dot( transformedNormal, lVector );",
  10264. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10265. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10266. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10267. " #ifdef DOUBLE_SIDED",
  10268. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10269. " #endif",
  10270. " }",
  10271. "#endif",
  10272. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10273. "#ifdef DOUBLE_SIDED",
  10274. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10275. "#endif"
  10276. ].join("\n"),
  10277. // LIGHTS PHONG
  10278. lights_phong_pars_vertex: [
  10279. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10280. " varying vec3 vWorldPosition;",
  10281. "#endif"
  10282. ].join("\n"),
  10283. lights_phong_vertex: [
  10284. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10285. " vWorldPosition = worldPosition.xyz;",
  10286. "#endif"
  10287. ].join("\n"),
  10288. lights_phong_pars_fragment: [
  10289. "uniform vec3 ambientLightColor;",
  10290. "#if MAX_DIR_LIGHTS > 0",
  10291. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10292. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10293. "#endif",
  10294. "#if MAX_HEMI_LIGHTS > 0",
  10295. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10296. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10297. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10298. "#endif",
  10299. "#if MAX_POINT_LIGHTS > 0",
  10300. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10301. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10302. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10303. "#endif",
  10304. "#if MAX_SPOT_LIGHTS > 0",
  10305. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10306. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10307. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10308. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10309. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10310. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10311. "#endif",
  10312. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10313. " varying vec3 vWorldPosition;",
  10314. "#endif",
  10315. "#ifdef WRAP_AROUND",
  10316. " uniform vec3 wrapRGB;",
  10317. "#endif",
  10318. "varying vec3 vViewPosition;",
  10319. "varying vec3 vNormal;"
  10320. ].join("\n"),
  10321. lights_phong_fragment: [
  10322. "vec3 normal = normalize( vNormal );",
  10323. "vec3 viewPosition = normalize( vViewPosition );",
  10324. "#ifdef DOUBLE_SIDED",
  10325. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10326. "#endif",
  10327. "#ifdef USE_NORMALMAP",
  10328. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10329. "#elif defined( USE_BUMPMAP )",
  10330. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10331. "#endif",
  10332. "#if MAX_POINT_LIGHTS > 0",
  10333. " vec3 pointDiffuse = vec3( 0.0 );",
  10334. " vec3 pointSpecular = vec3( 0.0 );",
  10335. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10336. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10337. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10338. " float lDistance = 1.0;",
  10339. " if ( pointLightDistance[ i ] > 0.0 )",
  10340. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10341. " lVector = normalize( lVector );",
  10342. // diffuse
  10343. " float dotProduct = dot( normal, lVector );",
  10344. " #ifdef WRAP_AROUND",
  10345. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10346. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10347. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10348. " #else",
  10349. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10350. " #endif",
  10351. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10352. // specular
  10353. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10354. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10355. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10356. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10357. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10358. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10359. " }",
  10360. "#endif",
  10361. "#if MAX_SPOT_LIGHTS > 0",
  10362. " vec3 spotDiffuse = vec3( 0.0 );",
  10363. " vec3 spotSpecular = vec3( 0.0 );",
  10364. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10365. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10366. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10367. " float lDistance = 1.0;",
  10368. " if ( spotLightDistance[ i ] > 0.0 )",
  10369. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10370. " lVector = normalize( lVector );",
  10371. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10372. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10373. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10374. // diffuse
  10375. " float dotProduct = dot( normal, lVector );",
  10376. " #ifdef WRAP_AROUND",
  10377. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10378. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10379. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10380. " #else",
  10381. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10382. " #endif",
  10383. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10384. // specular
  10385. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10386. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10387. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10388. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10389. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10390. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10391. " }",
  10392. " }",
  10393. "#endif",
  10394. "#if MAX_DIR_LIGHTS > 0",
  10395. " vec3 dirDiffuse = vec3( 0.0 );",
  10396. " vec3 dirSpecular = vec3( 0.0 );" ,
  10397. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10398. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10399. " vec3 dirVector = normalize( lDirection.xyz );",
  10400. // diffuse
  10401. " float dotProduct = dot( normal, dirVector );",
  10402. " #ifdef WRAP_AROUND",
  10403. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10404. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10405. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10406. " #else",
  10407. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10408. " #endif",
  10409. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10410. // specular
  10411. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10412. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10413. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10414. /*
  10415. // fresnel term from skin shader
  10416. " const float F0 = 0.128;",
  10417. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10418. " float exponential = pow( base, 5.0 );",
  10419. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10420. */
  10421. /*
  10422. // fresnel term from fresnel shader
  10423. " const float mFresnelBias = 0.08;",
  10424. " const float mFresnelScale = 0.3;",
  10425. " const float mFresnelPower = 5.0;",
  10426. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10427. */
  10428. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10429. // " dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10430. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10431. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10432. " }",
  10433. "#endif",
  10434. "#if MAX_HEMI_LIGHTS > 0",
  10435. " vec3 hemiDiffuse = vec3( 0.0 );",
  10436. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10437. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10438. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10439. " vec3 lVector = normalize( lDirection.xyz );",
  10440. // diffuse
  10441. " float dotProduct = dot( normal, lVector );",
  10442. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10443. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10444. " hemiDiffuse += diffuse * hemiColor;",
  10445. // specular (sky light)
  10446. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10447. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10448. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10449. // specular (ground light)
  10450. " vec3 lVectorGround = -lVector;",
  10451. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10452. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10453. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10454. " float dotProductGround = dot( normal, lVectorGround );",
  10455. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10456. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10457. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10458. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10459. " }",
  10460. "#endif",
  10461. "vec3 totalDiffuse = vec3( 0.0 );",
  10462. "vec3 totalSpecular = vec3( 0.0 );",
  10463. "#if MAX_DIR_LIGHTS > 0",
  10464. " totalDiffuse += dirDiffuse;",
  10465. " totalSpecular += dirSpecular;",
  10466. "#endif",
  10467. "#if MAX_HEMI_LIGHTS > 0",
  10468. " totalDiffuse += hemiDiffuse;",
  10469. " totalSpecular += hemiSpecular;",
  10470. "#endif",
  10471. "#if MAX_POINT_LIGHTS > 0",
  10472. " totalDiffuse += pointDiffuse;",
  10473. " totalSpecular += pointSpecular;",
  10474. "#endif",
  10475. "#if MAX_SPOT_LIGHTS > 0",
  10476. " totalDiffuse += spotDiffuse;",
  10477. " totalSpecular += spotSpecular;",
  10478. "#endif",
  10479. "#ifdef METAL",
  10480. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10481. "#else",
  10482. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10483. "#endif"
  10484. ].join("\n"),
  10485. // VERTEX COLORS
  10486. color_pars_fragment: [
  10487. "#ifdef USE_COLOR",
  10488. " varying vec3 vColor;",
  10489. "#endif"
  10490. ].join("\n"),
  10491. color_fragment: [
  10492. "#ifdef USE_COLOR",
  10493. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10494. "#endif"
  10495. ].join("\n"),
  10496. color_pars_vertex: [
  10497. "#ifdef USE_COLOR",
  10498. " varying vec3 vColor;",
  10499. "#endif"
  10500. ].join("\n"),
  10501. color_vertex: [
  10502. "#ifdef USE_COLOR",
  10503. " #ifdef GAMMA_INPUT",
  10504. " vColor = color * color;",
  10505. " #else",
  10506. " vColor = color;",
  10507. " #endif",
  10508. "#endif"
  10509. ].join("\n"),
  10510. // SKINNING
  10511. skinning_pars_vertex: [
  10512. "#ifdef USE_SKINNING",
  10513. " #ifdef BONE_TEXTURE",
  10514. " uniform sampler2D boneTexture;",
  10515. " uniform int boneTextureWidth;",
  10516. " uniform int boneTextureHeight;",
  10517. " mat4 getBoneMatrix( const in float i ) {",
  10518. " float j = i * 4.0;",
  10519. " float x = mod( j, float( boneTextureWidth ) );",
  10520. " float y = floor( j / float( boneTextureWidth ) );",
  10521. " float dx = 1.0 / float( boneTextureWidth );",
  10522. " float dy = 1.0 / float( boneTextureHeight );",
  10523. " y = dy * ( y + 0.5 );",
  10524. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10525. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10526. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10527. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10528. " mat4 bone = mat4( v1, v2, v3, v4 );",
  10529. " return bone;",
  10530. " }",
  10531. " #else",
  10532. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10533. " mat4 getBoneMatrix( const in float i ) {",
  10534. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  10535. " return bone;",
  10536. " }",
  10537. " #endif",
  10538. "#endif"
  10539. ].join("\n"),
  10540. skinbase_vertex: [
  10541. "#ifdef USE_SKINNING",
  10542. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10543. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10544. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10545. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10546. "#endif"
  10547. ].join("\n"),
  10548. skinning_vertex: [
  10549. "#ifdef USE_SKINNING",
  10550. " #ifdef USE_MORPHTARGETS",
  10551. " vec4 skinVertex = vec4( morphed, 1.0 );",
  10552. " #else",
  10553. " vec4 skinVertex = vec4( position, 1.0 );",
  10554. " #endif",
  10555. " vec4 skinned = vec4( 0.0 );",
  10556. " skinned += boneMatX * skinVertex * skinWeight.x;",
  10557. " skinned += boneMatY * skinVertex * skinWeight.y;",
  10558. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  10559. " skinned += boneMatW * skinVertex * skinWeight.w;",
  10560. "#endif"
  10561. ].join("\n"),
  10562. // MORPHING
  10563. morphtarget_pars_vertex: [
  10564. "#ifdef USE_MORPHTARGETS",
  10565. " #ifndef USE_MORPHNORMALS",
  10566. " uniform float morphTargetInfluences[ 8 ];",
  10567. " #else",
  10568. " uniform float morphTargetInfluences[ 4 ];",
  10569. " #endif",
  10570. "#endif"
  10571. ].join("\n"),
  10572. morphtarget_vertex: [
  10573. "#ifdef USE_MORPHTARGETS",
  10574. " vec3 morphed = vec3( 0.0 );",
  10575. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10576. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10577. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10578. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10579. " #ifndef USE_MORPHNORMALS",
  10580. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10581. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10582. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10583. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10584. " #endif",
  10585. " morphed += position;",
  10586. "#endif"
  10587. ].join("\n"),
  10588. default_vertex : [
  10589. "vec4 mvPosition;",
  10590. "#ifdef USE_SKINNING",
  10591. " mvPosition = modelViewMatrix * skinned;",
  10592. "#endif",
  10593. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10594. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10595. "#endif",
  10596. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10597. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10598. "#endif",
  10599. "gl_Position = projectionMatrix * mvPosition;"
  10600. ].join("\n"),
  10601. morphnormal_vertex: [
  10602. "#ifdef USE_MORPHNORMALS",
  10603. " vec3 morphedNormal = vec3( 0.0 );",
  10604. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10605. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10606. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10607. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10608. " morphedNormal += normal;",
  10609. "#endif"
  10610. ].join("\n"),
  10611. skinnormal_vertex: [
  10612. "#ifdef USE_SKINNING",
  10613. " mat4 skinMatrix = mat4( 0.0 );",
  10614. " skinMatrix += skinWeight.x * boneMatX;",
  10615. " skinMatrix += skinWeight.y * boneMatY;",
  10616. " skinMatrix += skinWeight.z * boneMatZ;",
  10617. " skinMatrix += skinWeight.w * boneMatW;",
  10618. " #ifdef USE_MORPHNORMALS",
  10619. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10620. " #else",
  10621. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10622. " #endif",
  10623. "#endif"
  10624. ].join("\n"),
  10625. defaultnormal_vertex: [
  10626. "vec3 objectNormal;",
  10627. "#ifdef USE_SKINNING",
  10628. " objectNormal = skinnedNormal.xyz;",
  10629. "#endif",
  10630. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10631. " objectNormal = morphedNormal;",
  10632. "#endif",
  10633. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10634. " objectNormal = normal;",
  10635. "#endif",
  10636. "#ifdef FLIP_SIDED",
  10637. " objectNormal = -objectNormal;",
  10638. "#endif",
  10639. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10640. ].join("\n"),
  10641. // SHADOW MAP
  10642. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10643. // http://spidergl.org/example.php?id=6
  10644. // http://fabiensanglard.net/shadowmapping
  10645. shadowmap_pars_fragment: [
  10646. "#ifdef USE_SHADOWMAP",
  10647. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10648. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10649. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  10650. " uniform float shadowBias[ MAX_SHADOWS ];",
  10651. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10652. " float unpackDepth( const in vec4 rgba_depth ) {",
  10653. " 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 );",
  10654. " float depth = dot( rgba_depth, bit_shift );",
  10655. " return depth;",
  10656. " }",
  10657. "#endif"
  10658. ].join("\n"),
  10659. shadowmap_fragment: [
  10660. "#ifdef USE_SHADOWMAP",
  10661. " #ifdef SHADOWMAP_DEBUG",
  10662. " vec3 frustumColors[3];",
  10663. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10664. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10665. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10666. " #endif",
  10667. " #ifdef SHADOWMAP_CASCADE",
  10668. " int inFrustumCount = 0;",
  10669. " #endif",
  10670. " float fDepth;",
  10671. " vec3 shadowColor = vec3( 1.0 );",
  10672. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10673. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10674. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10675. // "if ( all( something, something ) )" using this instead
  10676. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10677. " bool inFrustum = all( inFrustumVec );",
  10678. // don't shadow pixels outside of light frustum
  10679. // use just first frustum (for cascades)
  10680. // don't shadow pixels behind far plane of light frustum
  10681. " #ifdef SHADOWMAP_CASCADE",
  10682. " inFrustumCount += int( inFrustum );",
  10683. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10684. " #else",
  10685. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10686. " #endif",
  10687. " bool frustumTest = all( frustumTestVec );",
  10688. " if ( frustumTest ) {",
  10689. " shadowCoord.z += shadowBias[ i ];",
  10690. " #if defined( SHADOWMAP_TYPE_PCF )",
  10691. // Percentage-close filtering
  10692. // (9 pixel kernel)
  10693. // http://fabiensanglard.net/shadowmappingPCF/
  10694. " float shadow = 0.0;",
  10695. /*
  10696. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10697. // must enroll loop manually
  10698. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10699. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10700. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10701. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10702. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10703. " float fDepth = unpackDepth( rgbaDepth );",
  10704. " if ( fDepth < shadowCoord.z )",
  10705. " shadow += 1.0;",
  10706. " }",
  10707. " shadow /= 9.0;",
  10708. */
  10709. " const float shadowDelta = 1.0 / 9.0;",
  10710. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10711. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10712. " float dx0 = -1.25 * xPixelOffset;",
  10713. " float dy0 = -1.25 * yPixelOffset;",
  10714. " float dx1 = 1.25 * xPixelOffset;",
  10715. " float dy1 = 1.25 * yPixelOffset;",
  10716. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10717. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10718. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10719. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10720. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10721. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10722. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10723. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10724. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10725. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10726. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10727. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10728. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10729. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10730. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10731. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10732. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10733. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10734. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10735. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10736. // Percentage-close filtering
  10737. // (9 pixel kernel)
  10738. // http://fabiensanglard.net/shadowmappingPCF/
  10739. " float shadow = 0.0;",
  10740. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10741. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10742. " float dx0 = -1.0 * xPixelOffset;",
  10743. " float dy0 = -1.0 * yPixelOffset;",
  10744. " float dx1 = 1.0 * xPixelOffset;",
  10745. " float dy1 = 1.0 * yPixelOffset;",
  10746. " mat3 shadowKernel;",
  10747. " mat3 depthKernel;",
  10748. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10749. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10750. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10751. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10752. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10753. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10754. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10755. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10756. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10757. " vec3 shadowZ = vec3( shadowCoord.z );",
  10758. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10759. " shadowKernel[0] *= vec3(0.25);",
  10760. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10761. " shadowKernel[1] *= vec3(0.25);",
  10762. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10763. " shadowKernel[2] *= vec3(0.25);",
  10764. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10765. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10766. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10767. " vec4 shadowValues;",
  10768. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10769. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10770. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10771. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10772. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  10773. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10774. " #else",
  10775. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10776. " float fDepth = unpackDepth( rgbaDepth );",
  10777. " if ( fDepth < shadowCoord.z )",
  10778. // spot with multiple shadows is darker
  10779. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10780. // spot with multiple shadows has the same color as single shadow spot
  10781. // " shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10782. " #endif",
  10783. " }",
  10784. " #ifdef SHADOWMAP_DEBUG",
  10785. " #ifdef SHADOWMAP_CASCADE",
  10786. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10787. " #else",
  10788. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10789. " #endif",
  10790. " #endif",
  10791. " }",
  10792. " #ifdef GAMMA_OUTPUT",
  10793. " shadowColor *= shadowColor;",
  10794. " #endif",
  10795. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10796. "#endif"
  10797. ].join("\n"),
  10798. shadowmap_pars_vertex: [
  10799. "#ifdef USE_SHADOWMAP",
  10800. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10801. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10802. "#endif"
  10803. ].join("\n"),
  10804. shadowmap_vertex: [
  10805. "#ifdef USE_SHADOWMAP",
  10806. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10807. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10808. " }",
  10809. "#endif"
  10810. ].join("\n"),
  10811. // ALPHATEST
  10812. alphatest_fragment: [
  10813. "#ifdef ALPHATEST",
  10814. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  10815. "#endif"
  10816. ].join("\n"),
  10817. // LINEAR SPACE
  10818. linear_to_gamma_fragment: [
  10819. "#ifdef GAMMA_OUTPUT",
  10820. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10821. "#endif"
  10822. ].join("\n"),
  10823. // LOGARITHMIC DEPTH BUFFER
  10824. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  10825. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  10826. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  10827. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  10828. // the camera is near the surface.
  10829. logdepthbuf_pars_vertex: [
  10830. "#ifdef USE_LOGDEPTHBUF",
  10831. " #ifdef USE_LOGDEPTHBUF_EXT",
  10832. " varying float vFragDepth;",
  10833. " #endif",
  10834. " uniform float logDepthBufFC;",
  10835. "#endif",
  10836. ].join('\n'),
  10837. logdepthbuf_vertex: [
  10838. "#ifdef USE_LOGDEPTHBUF",
  10839. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  10840. " #ifdef USE_LOGDEPTHBUF_EXT",
  10841. " vFragDepth = 1.0 + gl_Position.w;",
  10842. "#else",
  10843. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  10844. " #endif",
  10845. "#endif"
  10846. ].join("\n"),
  10847. logdepthbuf_pars_fragment: [
  10848. "#ifdef USE_LOGDEPTHBUF",
  10849. " uniform float logDepthBufFC;",
  10850. " #ifdef USE_LOGDEPTHBUF_EXT",
  10851. " #extension GL_EXT_frag_depth : enable",
  10852. " varying float vFragDepth;",
  10853. " #endif",
  10854. "#endif"
  10855. ].join('\n'),
  10856. logdepthbuf_fragment: [
  10857. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  10858. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  10859. "#endif"
  10860. ].join("\n")
  10861. };
  10862. /**
  10863. * Uniform Utilities
  10864. */
  10865. THREE.UniformsUtils = {
  10866. merge: function ( uniforms ) {
  10867. var u, p, tmp, merged = {};
  10868. for ( u = 0; u < uniforms.length; u ++ ) {
  10869. tmp = this.clone( uniforms[ u ] );
  10870. for ( p in tmp ) {
  10871. merged[ p ] = tmp[ p ];
  10872. }
  10873. }
  10874. return merged;
  10875. },
  10876. clone: function ( uniforms_src ) {
  10877. var u, p, parameter, parameter_src, uniforms_dst = {};
  10878. for ( u in uniforms_src ) {
  10879. uniforms_dst[ u ] = {};
  10880. for ( p in uniforms_src[ u ] ) {
  10881. parameter_src = uniforms_src[ u ][ p ];
  10882. if ( parameter_src instanceof THREE.Color ||
  10883. parameter_src instanceof THREE.Vector2 ||
  10884. parameter_src instanceof THREE.Vector3 ||
  10885. parameter_src instanceof THREE.Vector4 ||
  10886. parameter_src instanceof THREE.Matrix4 ||
  10887. parameter_src instanceof THREE.Texture ) {
  10888. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10889. } else if ( parameter_src instanceof Array ) {
  10890. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10891. } else {
  10892. uniforms_dst[ u ][ p ] = parameter_src;
  10893. }
  10894. }
  10895. }
  10896. return uniforms_dst;
  10897. }
  10898. };
  10899. /**
  10900. * Uniforms library for shared webgl shaders
  10901. */
  10902. THREE.UniformsLib = {
  10903. common: {
  10904. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10905. "opacity" : { type: "f", value: 1.0 },
  10906. "map" : { type: "t", value: null },
  10907. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10908. "lightMap" : { type: "t", value: null },
  10909. "specularMap" : { type: "t", value: null },
  10910. "envMap" : { type: "t", value: null },
  10911. "flipEnvMap" : { type: "f", value: -1 },
  10912. "useRefract" : { type: "i", value: 0 },
  10913. "reflectivity" : { type: "f", value: 1.0 },
  10914. "refractionRatio" : { type: "f", value: 0.98 },
  10915. "combine" : { type: "i", value: 0 },
  10916. "morphTargetInfluences" : { type: "f", value: 0 }
  10917. },
  10918. bump: {
  10919. "bumpMap" : { type: "t", value: null },
  10920. "bumpScale" : { type: "f", value: 1 }
  10921. },
  10922. normalmap: {
  10923. "normalMap" : { type: "t", value: null },
  10924. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10925. },
  10926. fog : {
  10927. "fogDensity" : { type: "f", value: 0.00025 },
  10928. "fogNear" : { type: "f", value: 1 },
  10929. "fogFar" : { type: "f", value: 2000 },
  10930. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10931. },
  10932. lights: {
  10933. "ambientLightColor" : { type: "fv", value: [] },
  10934. "directionalLightDirection" : { type: "fv", value: [] },
  10935. "directionalLightColor" : { type: "fv", value: [] },
  10936. "hemisphereLightDirection" : { type: "fv", value: [] },
  10937. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10938. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10939. "pointLightColor" : { type: "fv", value: [] },
  10940. "pointLightPosition" : { type: "fv", value: [] },
  10941. "pointLightDistance" : { type: "fv1", value: [] },
  10942. "spotLightColor" : { type: "fv", value: [] },
  10943. "spotLightPosition" : { type: "fv", value: [] },
  10944. "spotLightDirection" : { type: "fv", value: [] },
  10945. "spotLightDistance" : { type: "fv1", value: [] },
  10946. "spotLightAngleCos" : { type: "fv1", value: [] },
  10947. "spotLightExponent" : { type: "fv1", value: [] }
  10948. },
  10949. particle: {
  10950. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10951. "opacity" : { type: "f", value: 1.0 },
  10952. "size" : { type: "f", value: 1.0 },
  10953. "scale" : { type: "f", value: 1.0 },
  10954. "map" : { type: "t", value: null },
  10955. "fogDensity" : { type: "f", value: 0.00025 },
  10956. "fogNear" : { type: "f", value: 1 },
  10957. "fogFar" : { type: "f", value: 2000 },
  10958. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10959. },
  10960. shadowmap: {
  10961. "shadowMap": { type: "tv", value: [] },
  10962. "shadowMapSize": { type: "v2v", value: [] },
  10963. "shadowBias" : { type: "fv1", value: [] },
  10964. "shadowDarkness": { type: "fv1", value: [] },
  10965. "shadowMatrix" : { type: "m4v", value: [] }
  10966. }
  10967. };
  10968. /**
  10969. * Webgl Shader Library for three.js
  10970. *
  10971. * @author alteredq / http://alteredqualia.com/
  10972. * @author mrdoob / http://mrdoob.com/
  10973. * @author mikael emtinger / http://gomo.se/
  10974. */
  10975. THREE.ShaderLib = {
  10976. 'basic': {
  10977. uniforms: THREE.UniformsUtils.merge( [
  10978. THREE.UniformsLib[ "common" ],
  10979. THREE.UniformsLib[ "fog" ],
  10980. THREE.UniformsLib[ "shadowmap" ]
  10981. ] ),
  10982. vertexShader: [
  10983. THREE.ShaderChunk[ "map_pars_vertex" ],
  10984. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10985. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10986. THREE.ShaderChunk[ "color_pars_vertex" ],
  10987. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10988. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10989. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10990. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10991. "void main() {",
  10992. THREE.ShaderChunk[ "map_vertex" ],
  10993. THREE.ShaderChunk[ "lightmap_vertex" ],
  10994. THREE.ShaderChunk[ "color_vertex" ],
  10995. THREE.ShaderChunk[ "skinbase_vertex" ],
  10996. " #ifdef USE_ENVMAP",
  10997. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10998. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10999. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11000. " #endif",
  11001. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11002. THREE.ShaderChunk[ "skinning_vertex" ],
  11003. THREE.ShaderChunk[ "default_vertex" ],
  11004. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11005. THREE.ShaderChunk[ "worldpos_vertex" ],
  11006. THREE.ShaderChunk[ "envmap_vertex" ],
  11007. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11008. "}"
  11009. ].join("\n"),
  11010. fragmentShader: [
  11011. "uniform vec3 diffuse;",
  11012. "uniform float opacity;",
  11013. THREE.ShaderChunk[ "color_pars_fragment" ],
  11014. THREE.ShaderChunk[ "map_pars_fragment" ],
  11015. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11016. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11017. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11018. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11019. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11020. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11021. "void main() {",
  11022. " gl_FragColor = vec4( diffuse, opacity );",
  11023. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11024. THREE.ShaderChunk[ "map_fragment" ],
  11025. THREE.ShaderChunk[ "alphatest_fragment" ],
  11026. THREE.ShaderChunk[ "specularmap_fragment" ],
  11027. THREE.ShaderChunk[ "lightmap_fragment" ],
  11028. THREE.ShaderChunk[ "color_fragment" ],
  11029. THREE.ShaderChunk[ "envmap_fragment" ],
  11030. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11031. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11032. THREE.ShaderChunk[ "fog_fragment" ],
  11033. "}"
  11034. ].join("\n")
  11035. },
  11036. 'lambert': {
  11037. uniforms: THREE.UniformsUtils.merge( [
  11038. THREE.UniformsLib[ "common" ],
  11039. THREE.UniformsLib[ "fog" ],
  11040. THREE.UniformsLib[ "lights" ],
  11041. THREE.UniformsLib[ "shadowmap" ],
  11042. {
  11043. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11044. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11045. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11046. }
  11047. ] ),
  11048. vertexShader: [
  11049. "#define LAMBERT",
  11050. "varying vec3 vLightFront;",
  11051. "#ifdef DOUBLE_SIDED",
  11052. " varying vec3 vLightBack;",
  11053. "#endif",
  11054. THREE.ShaderChunk[ "map_pars_vertex" ],
  11055. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11056. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11057. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11058. THREE.ShaderChunk[ "color_pars_vertex" ],
  11059. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11060. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11061. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11062. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11063. "void main() {",
  11064. THREE.ShaderChunk[ "map_vertex" ],
  11065. THREE.ShaderChunk[ "lightmap_vertex" ],
  11066. THREE.ShaderChunk[ "color_vertex" ],
  11067. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11068. THREE.ShaderChunk[ "skinbase_vertex" ],
  11069. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11070. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11071. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11072. THREE.ShaderChunk[ "skinning_vertex" ],
  11073. THREE.ShaderChunk[ "default_vertex" ],
  11074. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11075. THREE.ShaderChunk[ "worldpos_vertex" ],
  11076. THREE.ShaderChunk[ "envmap_vertex" ],
  11077. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11078. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11079. "}"
  11080. ].join("\n"),
  11081. fragmentShader: [
  11082. "uniform float opacity;",
  11083. "varying vec3 vLightFront;",
  11084. "#ifdef DOUBLE_SIDED",
  11085. " varying vec3 vLightBack;",
  11086. "#endif",
  11087. THREE.ShaderChunk[ "color_pars_fragment" ],
  11088. THREE.ShaderChunk[ "map_pars_fragment" ],
  11089. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11090. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11091. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11092. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11093. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11094. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11095. "void main() {",
  11096. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11097. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11098. THREE.ShaderChunk[ "map_fragment" ],
  11099. THREE.ShaderChunk[ "alphatest_fragment" ],
  11100. THREE.ShaderChunk[ "specularmap_fragment" ],
  11101. " #ifdef DOUBLE_SIDED",
  11102. //"float isFront = float( gl_FrontFacing );",
  11103. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11104. " if ( gl_FrontFacing )",
  11105. " gl_FragColor.xyz *= vLightFront;",
  11106. " else",
  11107. " gl_FragColor.xyz *= vLightBack;",
  11108. " #else",
  11109. " gl_FragColor.xyz *= vLightFront;",
  11110. " #endif",
  11111. THREE.ShaderChunk[ "lightmap_fragment" ],
  11112. THREE.ShaderChunk[ "color_fragment" ],
  11113. THREE.ShaderChunk[ "envmap_fragment" ],
  11114. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11115. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11116. THREE.ShaderChunk[ "fog_fragment" ],
  11117. "}"
  11118. ].join("\n")
  11119. },
  11120. 'phong': {
  11121. uniforms: THREE.UniformsUtils.merge( [
  11122. THREE.UniformsLib[ "common" ],
  11123. THREE.UniformsLib[ "bump" ],
  11124. THREE.UniformsLib[ "normalmap" ],
  11125. THREE.UniformsLib[ "fog" ],
  11126. THREE.UniformsLib[ "lights" ],
  11127. THREE.UniformsLib[ "shadowmap" ],
  11128. {
  11129. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11130. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11131. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11132. "shininess": { type: "f", value: 30 },
  11133. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11134. }
  11135. ] ),
  11136. vertexShader: [
  11137. "#define PHONG",
  11138. "varying vec3 vViewPosition;",
  11139. "varying vec3 vNormal;",
  11140. THREE.ShaderChunk[ "map_pars_vertex" ],
  11141. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11142. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11143. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11144. THREE.ShaderChunk[ "color_pars_vertex" ],
  11145. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11146. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11147. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11148. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11149. "void main() {",
  11150. THREE.ShaderChunk[ "map_vertex" ],
  11151. THREE.ShaderChunk[ "lightmap_vertex" ],
  11152. THREE.ShaderChunk[ "color_vertex" ],
  11153. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11154. THREE.ShaderChunk[ "skinbase_vertex" ],
  11155. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11156. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11157. " vNormal = normalize( transformedNormal );",
  11158. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11159. THREE.ShaderChunk[ "skinning_vertex" ],
  11160. THREE.ShaderChunk[ "default_vertex" ],
  11161. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11162. " vViewPosition = -mvPosition.xyz;",
  11163. THREE.ShaderChunk[ "worldpos_vertex" ],
  11164. THREE.ShaderChunk[ "envmap_vertex" ],
  11165. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11166. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11167. "}"
  11168. ].join("\n"),
  11169. fragmentShader: [
  11170. "uniform vec3 diffuse;",
  11171. "uniform float opacity;",
  11172. "uniform vec3 ambient;",
  11173. "uniform vec3 emissive;",
  11174. "uniform vec3 specular;",
  11175. "uniform float shininess;",
  11176. THREE.ShaderChunk[ "color_pars_fragment" ],
  11177. THREE.ShaderChunk[ "map_pars_fragment" ],
  11178. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11179. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11180. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11181. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11182. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11183. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11184. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11185. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11186. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11187. "void main() {",
  11188. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11189. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11190. THREE.ShaderChunk[ "map_fragment" ],
  11191. THREE.ShaderChunk[ "alphatest_fragment" ],
  11192. THREE.ShaderChunk[ "specularmap_fragment" ],
  11193. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11194. THREE.ShaderChunk[ "lightmap_fragment" ],
  11195. THREE.ShaderChunk[ "color_fragment" ],
  11196. THREE.ShaderChunk[ "envmap_fragment" ],
  11197. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11198. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11199. THREE.ShaderChunk[ "fog_fragment" ],
  11200. "}"
  11201. ].join("\n")
  11202. },
  11203. 'particle_basic': {
  11204. uniforms: THREE.UniformsUtils.merge( [
  11205. THREE.UniformsLib[ "particle" ],
  11206. THREE.UniformsLib[ "shadowmap" ]
  11207. ] ),
  11208. vertexShader: [
  11209. "uniform float size;",
  11210. "uniform float scale;",
  11211. THREE.ShaderChunk[ "color_pars_vertex" ],
  11212. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11213. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11214. "void main() {",
  11215. THREE.ShaderChunk[ "color_vertex" ],
  11216. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11217. " #ifdef USE_SIZEATTENUATION",
  11218. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11219. " #else",
  11220. " gl_PointSize = size;",
  11221. " #endif",
  11222. " gl_Position = projectionMatrix * mvPosition;",
  11223. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11224. THREE.ShaderChunk[ "worldpos_vertex" ],
  11225. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11226. "}"
  11227. ].join("\n"),
  11228. fragmentShader: [
  11229. "uniform vec3 psColor;",
  11230. "uniform float opacity;",
  11231. THREE.ShaderChunk[ "color_pars_fragment" ],
  11232. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11233. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11234. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11235. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11236. "void main() {",
  11237. " gl_FragColor = vec4( psColor, opacity );",
  11238. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11239. THREE.ShaderChunk[ "map_particle_fragment" ],
  11240. THREE.ShaderChunk[ "alphatest_fragment" ],
  11241. THREE.ShaderChunk[ "color_fragment" ],
  11242. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11243. THREE.ShaderChunk[ "fog_fragment" ],
  11244. "}"
  11245. ].join("\n")
  11246. },
  11247. 'dashed': {
  11248. uniforms: THREE.UniformsUtils.merge( [
  11249. THREE.UniformsLib[ "common" ],
  11250. THREE.UniformsLib[ "fog" ],
  11251. {
  11252. "scale" : { type: "f", value: 1 },
  11253. "dashSize" : { type: "f", value: 1 },
  11254. "totalSize": { type: "f", value: 2 }
  11255. }
  11256. ] ),
  11257. vertexShader: [
  11258. "uniform float scale;",
  11259. "attribute float lineDistance;",
  11260. "varying float vLineDistance;",
  11261. THREE.ShaderChunk[ "color_pars_vertex" ],
  11262. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11263. "void main() {",
  11264. THREE.ShaderChunk[ "color_vertex" ],
  11265. " vLineDistance = scale * lineDistance;",
  11266. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11267. " gl_Position = projectionMatrix * mvPosition;",
  11268. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11269. "}"
  11270. ].join("\n"),
  11271. fragmentShader: [
  11272. "uniform vec3 diffuse;",
  11273. "uniform float opacity;",
  11274. "uniform float dashSize;",
  11275. "uniform float totalSize;",
  11276. "varying float vLineDistance;",
  11277. THREE.ShaderChunk[ "color_pars_fragment" ],
  11278. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11279. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11280. "void main() {",
  11281. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11282. " discard;",
  11283. " }",
  11284. " gl_FragColor = vec4( diffuse, opacity );",
  11285. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11286. THREE.ShaderChunk[ "color_fragment" ],
  11287. THREE.ShaderChunk[ "fog_fragment" ],
  11288. "}"
  11289. ].join("\n")
  11290. },
  11291. 'depth': {
  11292. uniforms: {
  11293. "mNear": { type: "f", value: 1.0 },
  11294. "mFar" : { type: "f", value: 2000.0 },
  11295. "opacity" : { type: "f", value: 1.0 }
  11296. },
  11297. vertexShader: [
  11298. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11299. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11300. "void main() {",
  11301. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11302. THREE.ShaderChunk[ "default_vertex" ],
  11303. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11304. "}"
  11305. ].join("\n"),
  11306. fragmentShader: [
  11307. "uniform float mNear;",
  11308. "uniform float mFar;",
  11309. "uniform float opacity;",
  11310. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11311. "void main() {",
  11312. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11313. " #ifdef USE_LOGDEPTHBUF_EXT",
  11314. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11315. " #else",
  11316. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11317. " #endif",
  11318. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11319. " gl_FragColor = vec4( vec3( color ), opacity );",
  11320. "}"
  11321. ].join("\n")
  11322. },
  11323. 'normal': {
  11324. uniforms: {
  11325. "opacity" : { type: "f", value: 1.0 }
  11326. },
  11327. vertexShader: [
  11328. "varying vec3 vNormal;",
  11329. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11330. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11331. "void main() {",
  11332. " vNormal = normalize( normalMatrix * normal );",
  11333. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11334. THREE.ShaderChunk[ "default_vertex" ],
  11335. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11336. "}"
  11337. ].join("\n"),
  11338. fragmentShader: [
  11339. "uniform float opacity;",
  11340. "varying vec3 vNormal;",
  11341. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11342. "void main() {",
  11343. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11344. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11345. "}"
  11346. ].join("\n")
  11347. },
  11348. /* -------------------------------------------------------------------------
  11349. // Normal map shader
  11350. // - Blinn-Phong
  11351. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11352. // - point and directional lights (use with "lights: true" material option)
  11353. ------------------------------------------------------------------------- */
  11354. 'normalmap' : {
  11355. uniforms: THREE.UniformsUtils.merge( [
  11356. THREE.UniformsLib[ "fog" ],
  11357. THREE.UniformsLib[ "lights" ],
  11358. THREE.UniformsLib[ "shadowmap" ],
  11359. {
  11360. "enableAO" : { type: "i", value: 0 },
  11361. "enableDiffuse" : { type: "i", value: 0 },
  11362. "enableSpecular" : { type: "i", value: 0 },
  11363. "enableReflection" : { type: "i", value: 0 },
  11364. "enableDisplacement": { type: "i", value: 0 },
  11365. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11366. "tDiffuse" : { type: "t", value: null },
  11367. "tCube" : { type: "t", value: null },
  11368. "tNormal" : { type: "t", value: null },
  11369. "tSpecular" : { type: "t", value: null },
  11370. "tAO" : { type: "t", value: null },
  11371. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11372. "uDisplacementBias": { type: "f", value: 0.0 },
  11373. "uDisplacementScale": { type: "f", value: 1.0 },
  11374. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11375. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11376. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11377. "shininess": { type: "f", value: 30 },
  11378. "opacity": { type: "f", value: 1 },
  11379. "useRefract": { type: "i", value: 0 },
  11380. "refractionRatio": { type: "f", value: 0.98 },
  11381. "reflectivity": { type: "f", value: 0.5 },
  11382. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11383. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11384. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11385. }
  11386. ] ),
  11387. fragmentShader: [
  11388. "uniform vec3 ambient;",
  11389. "uniform vec3 diffuse;",
  11390. "uniform vec3 specular;",
  11391. "uniform float shininess;",
  11392. "uniform float opacity;",
  11393. "uniform bool enableDiffuse;",
  11394. "uniform bool enableSpecular;",
  11395. "uniform bool enableAO;",
  11396. "uniform bool enableReflection;",
  11397. "uniform sampler2D tDiffuse;",
  11398. "uniform sampler2D tNormal;",
  11399. "uniform sampler2D tSpecular;",
  11400. "uniform sampler2D tAO;",
  11401. "uniform samplerCube tCube;",
  11402. "uniform vec2 uNormalScale;",
  11403. "uniform bool useRefract;",
  11404. "uniform float refractionRatio;",
  11405. "uniform float reflectivity;",
  11406. "varying vec3 vTangent;",
  11407. "varying vec3 vBinormal;",
  11408. "varying vec3 vNormal;",
  11409. "varying vec2 vUv;",
  11410. "uniform vec3 ambientLightColor;",
  11411. "#if MAX_DIR_LIGHTS > 0",
  11412. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11413. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11414. "#endif",
  11415. "#if MAX_HEMI_LIGHTS > 0",
  11416. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11417. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11418. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11419. "#endif",
  11420. "#if MAX_POINT_LIGHTS > 0",
  11421. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11422. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11423. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11424. "#endif",
  11425. "#if MAX_SPOT_LIGHTS > 0",
  11426. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11427. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11428. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11429. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11430. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11431. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11432. "#endif",
  11433. "#ifdef WRAP_AROUND",
  11434. " uniform vec3 wrapRGB;",
  11435. "#endif",
  11436. "varying vec3 vWorldPosition;",
  11437. "varying vec3 vViewPosition;",
  11438. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11439. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11440. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11441. "void main() {",
  11442. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11443. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11444. " vec3 specularTex = vec3( 1.0 );",
  11445. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11446. " normalTex.xy *= uNormalScale;",
  11447. " normalTex = normalize( normalTex );",
  11448. " if( enableDiffuse ) {",
  11449. " #ifdef GAMMA_INPUT",
  11450. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11451. " texelColor.xyz *= texelColor.xyz;",
  11452. " gl_FragColor = gl_FragColor * texelColor;",
  11453. " #else",
  11454. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11455. " #endif",
  11456. " }",
  11457. " if( enableAO ) {",
  11458. " #ifdef GAMMA_INPUT",
  11459. " vec4 aoColor = texture2D( tAO, vUv );",
  11460. " aoColor.xyz *= aoColor.xyz;",
  11461. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11462. " #else",
  11463. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11464. " #endif",
  11465. " }",
  11466. " if( enableSpecular )",
  11467. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11468. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11469. " vec3 finalNormal = tsb * normalTex;",
  11470. " #ifdef FLIP_SIDED",
  11471. " finalNormal = -finalNormal;",
  11472. " #endif",
  11473. " vec3 normal = normalize( finalNormal );",
  11474. " vec3 viewPosition = normalize( vViewPosition );",
  11475. // point lights
  11476. " #if MAX_POINT_LIGHTS > 0",
  11477. " vec3 pointDiffuse = vec3( 0.0 );",
  11478. " vec3 pointSpecular = vec3( 0.0 );",
  11479. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11480. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11481. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11482. " float pointDistance = 1.0;",
  11483. " if ( pointLightDistance[ i ] > 0.0 )",
  11484. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11485. " pointVector = normalize( pointVector );",
  11486. // diffuse
  11487. " #ifdef WRAP_AROUND",
  11488. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11489. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11490. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11491. " #else",
  11492. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11493. " #endif",
  11494. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11495. // specular
  11496. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11497. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11498. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11499. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11500. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11501. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11502. " }",
  11503. " #endif",
  11504. // spot lights
  11505. " #if MAX_SPOT_LIGHTS > 0",
  11506. " vec3 spotDiffuse = vec3( 0.0 );",
  11507. " vec3 spotSpecular = vec3( 0.0 );",
  11508. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11509. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11510. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11511. " float spotDistance = 1.0;",
  11512. " if ( spotLightDistance[ i ] > 0.0 )",
  11513. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11514. " spotVector = normalize( spotVector );",
  11515. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11516. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11517. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11518. // diffuse
  11519. " #ifdef WRAP_AROUND",
  11520. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11521. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11522. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11523. " #else",
  11524. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11525. " #endif",
  11526. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11527. // specular
  11528. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11529. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11530. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11531. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11532. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11533. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11534. " }",
  11535. " }",
  11536. " #endif",
  11537. // directional lights
  11538. " #if MAX_DIR_LIGHTS > 0",
  11539. " vec3 dirDiffuse = vec3( 0.0 );",
  11540. " vec3 dirSpecular = vec3( 0.0 );",
  11541. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11542. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11543. " vec3 dirVector = normalize( lDirection.xyz );",
  11544. // diffuse
  11545. " #ifdef WRAP_AROUND",
  11546. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11547. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11548. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11549. " #else",
  11550. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11551. " #endif",
  11552. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11553. // specular
  11554. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11555. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11556. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11557. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11558. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11559. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11560. " }",
  11561. " #endif",
  11562. // hemisphere lights
  11563. " #if MAX_HEMI_LIGHTS > 0",
  11564. " vec3 hemiDiffuse = vec3( 0.0 );",
  11565. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11566. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11567. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11568. " vec3 lVector = normalize( lDirection.xyz );",
  11569. // diffuse
  11570. " float dotProduct = dot( normal, lVector );",
  11571. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11572. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11573. " hemiDiffuse += diffuse * hemiColor;",
  11574. // specular (sky light)
  11575. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11576. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11577. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11578. // specular (ground light)
  11579. " vec3 lVectorGround = -lVector;",
  11580. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11581. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11582. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11583. " float dotProductGround = dot( normal, lVectorGround );",
  11584. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11585. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11586. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11587. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11588. " }",
  11589. " #endif",
  11590. // all lights contribution summation
  11591. " vec3 totalDiffuse = vec3( 0.0 );",
  11592. " vec3 totalSpecular = vec3( 0.0 );",
  11593. " #if MAX_DIR_LIGHTS > 0",
  11594. " totalDiffuse += dirDiffuse;",
  11595. " totalSpecular += dirSpecular;",
  11596. " #endif",
  11597. " #if MAX_HEMI_LIGHTS > 0",
  11598. " totalDiffuse += hemiDiffuse;",
  11599. " totalSpecular += hemiSpecular;",
  11600. " #endif",
  11601. " #if MAX_POINT_LIGHTS > 0",
  11602. " totalDiffuse += pointDiffuse;",
  11603. " totalSpecular += pointSpecular;",
  11604. " #endif",
  11605. " #if MAX_SPOT_LIGHTS > 0",
  11606. " totalDiffuse += spotDiffuse;",
  11607. " totalSpecular += spotSpecular;",
  11608. " #endif",
  11609. " #ifdef METAL",
  11610. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11611. " #else",
  11612. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11613. " #endif",
  11614. " if ( enableReflection ) {",
  11615. " vec3 vReflect;",
  11616. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11617. " if ( useRefract ) {",
  11618. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11619. " } else {",
  11620. " vReflect = reflect( cameraToVertex, normal );",
  11621. " }",
  11622. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11623. " #ifdef GAMMA_INPUT",
  11624. " cubeColor.xyz *= cubeColor.xyz;",
  11625. " #endif",
  11626. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11627. " }",
  11628. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11629. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11630. THREE.ShaderChunk[ "fog_fragment" ],
  11631. "}"
  11632. ].join("\n"),
  11633. vertexShader: [
  11634. "attribute vec4 tangent;",
  11635. "uniform vec2 uOffset;",
  11636. "uniform vec2 uRepeat;",
  11637. "uniform bool enableDisplacement;",
  11638. "#ifdef VERTEX_TEXTURES",
  11639. " uniform sampler2D tDisplacement;",
  11640. " uniform float uDisplacementScale;",
  11641. " uniform float uDisplacementBias;",
  11642. "#endif",
  11643. "varying vec3 vTangent;",
  11644. "varying vec3 vBinormal;",
  11645. "varying vec3 vNormal;",
  11646. "varying vec2 vUv;",
  11647. "varying vec3 vWorldPosition;",
  11648. "varying vec3 vViewPosition;",
  11649. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11650. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11651. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11652. "void main() {",
  11653. THREE.ShaderChunk[ "skinbase_vertex" ],
  11654. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11655. // normal, tangent and binormal vectors
  11656. " #ifdef USE_SKINNING",
  11657. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11658. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11659. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11660. " #else",
  11661. " vNormal = normalize( normalMatrix * normal );",
  11662. " vTangent = normalize( normalMatrix * tangent.xyz );",
  11663. " #endif",
  11664. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11665. " vUv = uv * uRepeat + uOffset;",
  11666. // displacement mapping
  11667. " vec3 displacedPosition;",
  11668. " #ifdef VERTEX_TEXTURES",
  11669. " if ( enableDisplacement ) {",
  11670. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11671. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11672. " displacedPosition = position + normalize( normal ) * df;",
  11673. " } else {",
  11674. " #ifdef USE_SKINNING",
  11675. " vec4 skinVertex = vec4( position, 1.0 );",
  11676. " vec4 skinned = vec4( 0.0 );",
  11677. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11678. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11679. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11680. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11681. " displacedPosition = skinned.xyz;",
  11682. " #else",
  11683. " displacedPosition = position;",
  11684. " #endif",
  11685. " }",
  11686. " #else",
  11687. " #ifdef USE_SKINNING",
  11688. " vec4 skinVertex = vec4( position, 1.0 );",
  11689. " vec4 skinned = vec4( 0.0 );",
  11690. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11691. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11692. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11693. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11694. " displacedPosition = skinned.xyz;",
  11695. " #else",
  11696. " displacedPosition = position;",
  11697. " #endif",
  11698. " #endif",
  11699. //
  11700. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11701. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11702. " gl_Position = projectionMatrix * mvPosition;",
  11703. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11704. //
  11705. " vWorldPosition = worldPosition.xyz;",
  11706. " vViewPosition = -mvPosition.xyz;",
  11707. // shadows
  11708. " #ifdef USE_SHADOWMAP",
  11709. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11710. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11711. " }",
  11712. " #endif",
  11713. "}"
  11714. ].join("\n")
  11715. },
  11716. /* -------------------------------------------------------------------------
  11717. // Cube map shader
  11718. ------------------------------------------------------------------------- */
  11719. 'cube': {
  11720. uniforms: { "tCube": { type: "t", value: null },
  11721. "tFlip": { type: "f", value: -1 } },
  11722. vertexShader: [
  11723. "varying vec3 vWorldPosition;",
  11724. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11725. "void main() {",
  11726. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11727. " vWorldPosition = worldPosition.xyz;",
  11728. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11729. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11730. "}"
  11731. ].join("\n"),
  11732. fragmentShader: [
  11733. "uniform samplerCube tCube;",
  11734. "uniform float tFlip;",
  11735. "varying vec3 vWorldPosition;",
  11736. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11737. "void main() {",
  11738. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11739. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11740. "}"
  11741. ].join("\n")
  11742. },
  11743. /* Depth encoding into RGBA texture
  11744. *
  11745. * based on SpiderGL shadow map example
  11746. * http://spidergl.org/example.php?id=6
  11747. *
  11748. * originally from
  11749. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11750. *
  11751. * see also
  11752. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11753. */
  11754. 'depthRGBA': {
  11755. uniforms: {},
  11756. vertexShader: [
  11757. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11758. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11759. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11760. "void main() {",
  11761. THREE.ShaderChunk[ "skinbase_vertex" ],
  11762. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11763. THREE.ShaderChunk[ "skinning_vertex" ],
  11764. THREE.ShaderChunk[ "default_vertex" ],
  11765. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11766. "}"
  11767. ].join("\n"),
  11768. fragmentShader: [
  11769. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11770. "vec4 pack_depth( const in float depth ) {",
  11771. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11772. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11773. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11774. " res -= res.xxyz * bit_mask;",
  11775. " return res;",
  11776. "}",
  11777. "void main() {",
  11778. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11779. " #ifdef USE_LOGDEPTHBUF_EXT",
  11780. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11781. " #else",
  11782. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11783. " #endif",
  11784. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11785. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11786. //"gl_FragData[ 0 ] = pack_depth( z );",
  11787. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11788. "}"
  11789. ].join("\n")
  11790. }
  11791. };
  11792. /**
  11793. * @author supereggbert / http://www.paulbrunt.co.uk/
  11794. * @author mrdoob / http://mrdoob.com/
  11795. * @author alteredq / http://alteredqualia.com/
  11796. * @author szimek / https://github.com/szimek/
  11797. */
  11798. THREE.WebGLRenderer = function ( parameters ) {
  11799. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11800. parameters = parameters || {};
  11801. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11802. _context = parameters.context !== undefined ? parameters.context : null,
  11803. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11804. _buffers = {},
  11805. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11806. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11807. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11808. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11809. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11810. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11811. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  11812. _clearColor = new THREE.Color( 0x000000 ),
  11813. _clearAlpha = 0;
  11814. // public properties
  11815. this.domElement = _canvas;
  11816. this.context = null;
  11817. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11818. ? parameters.devicePixelRatio
  11819. : self.devicePixelRatio !== undefined
  11820. ? self.devicePixelRatio
  11821. : 1;
  11822. // clearing
  11823. this.autoClear = true;
  11824. this.autoClearColor = true;
  11825. this.autoClearDepth = true;
  11826. this.autoClearStencil = true;
  11827. // scene graph
  11828. this.sortObjects = true;
  11829. this.autoUpdateObjects = true;
  11830. // physically based shading
  11831. this.gammaInput = false;
  11832. this.gammaOutput = false;
  11833. // shadow map
  11834. this.shadowMapEnabled = false;
  11835. this.shadowMapAutoUpdate = true;
  11836. this.shadowMapType = THREE.PCFShadowMap;
  11837. this.shadowMapCullFace = THREE.CullFaceFront;
  11838. this.shadowMapDebug = false;
  11839. this.shadowMapCascade = false;
  11840. // morphs
  11841. this.maxMorphTargets = 8;
  11842. this.maxMorphNormals = 4;
  11843. // flags
  11844. this.autoScaleCubemaps = true;
  11845. // custom render plugins
  11846. this.renderPluginsPre = [];
  11847. this.renderPluginsPost = [];
  11848. // info
  11849. this.info = {
  11850. memory: {
  11851. programs: 0,
  11852. geometries: 0,
  11853. textures: 0
  11854. },
  11855. render: {
  11856. calls: 0,
  11857. vertices: 0,
  11858. faces: 0,
  11859. points: 0
  11860. }
  11861. };
  11862. // internal properties
  11863. var _this = this,
  11864. _programs = [],
  11865. // internal state cache
  11866. _currentProgram = null,
  11867. _currentFramebuffer = null,
  11868. _currentMaterialId = -1,
  11869. _currentGeometryGroupHash = null,
  11870. _currentCamera = null,
  11871. _usedTextureUnits = 0,
  11872. // GL state cache
  11873. _oldDoubleSided = -1,
  11874. _oldFlipSided = -1,
  11875. _oldBlending = -1,
  11876. _oldBlendEquation = -1,
  11877. _oldBlendSrc = -1,
  11878. _oldBlendDst = -1,
  11879. _oldDepthTest = -1,
  11880. _oldDepthWrite = -1,
  11881. _oldPolygonOffset = null,
  11882. _oldPolygonOffsetFactor = null,
  11883. _oldPolygonOffsetUnits = null,
  11884. _oldLineWidth = null,
  11885. _viewportX = 0,
  11886. _viewportY = 0,
  11887. _viewportWidth = _canvas.width,
  11888. _viewportHeight = _canvas.height,
  11889. _currentWidth = 0,
  11890. _currentHeight = 0,
  11891. _newAttributes = new Uint8Array( 16 ),
  11892. _enabledAttributes = new Uint8Array( 16 ),
  11893. // frustum
  11894. _frustum = new THREE.Frustum(),
  11895. // camera matrices cache
  11896. _projScreenMatrix = new THREE.Matrix4(),
  11897. _projScreenMatrixPS = new THREE.Matrix4(),
  11898. _vector3 = new THREE.Vector3(),
  11899. // light arrays cache
  11900. _direction = new THREE.Vector3(),
  11901. _lightsNeedUpdate = true,
  11902. _lights = {
  11903. ambient: [ 0, 0, 0 ],
  11904. directional: { length: 0, colors: new Array(), positions: new Array() },
  11905. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11906. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11907. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11908. };
  11909. // initialize
  11910. var _gl;
  11911. var _glExtensionTextureFloat;
  11912. var _glExtensionTextureFloatLinear;
  11913. var _glExtensionStandardDerivatives;
  11914. var _glExtensionTextureFilterAnisotropic;
  11915. var _glExtensionCompressedTextureS3TC;
  11916. var _glExtensionElementIndexUint;
  11917. var _glExtensionFragDepth;
  11918. initGL();
  11919. setDefaultGLState();
  11920. this.context = _gl;
  11921. // GPU capabilities
  11922. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11923. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11924. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11925. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11926. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11927. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11928. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11929. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11930. //
  11931. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11932. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11933. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11934. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11935. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11936. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11937. /*
  11938. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11939. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11940. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11941. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11942. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11943. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11944. */
  11945. // clamp precision to maximum available
  11946. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11947. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11948. if ( _precision === "highp" && ! highpAvailable ) {
  11949. if ( mediumpAvailable ) {
  11950. _precision = "mediump";
  11951. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  11952. } else {
  11953. _precision = "lowp";
  11954. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  11955. }
  11956. }
  11957. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11958. _precision = "lowp";
  11959. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  11960. }
  11961. // API
  11962. this.getContext = function () {
  11963. return _gl;
  11964. };
  11965. this.supportsVertexTextures = function () {
  11966. return _supportsVertexTextures;
  11967. };
  11968. this.supportsFloatTextures = function () {
  11969. return _glExtensionTextureFloat;
  11970. };
  11971. this.supportsStandardDerivatives = function () {
  11972. return _glExtensionStandardDerivatives;
  11973. };
  11974. this.supportsCompressedTextureS3TC = function () {
  11975. return _glExtensionCompressedTextureS3TC;
  11976. };
  11977. this.getMaxAnisotropy = function () {
  11978. return _maxAnisotropy;
  11979. };
  11980. this.getPrecision = function () {
  11981. return _precision;
  11982. };
  11983. this.setSize = function ( width, height, updateStyle ) {
  11984. _canvas.width = width * this.devicePixelRatio;
  11985. _canvas.height = height * this.devicePixelRatio;
  11986. if ( updateStyle !== false ) {
  11987. _canvas.style.width = width + 'px';
  11988. _canvas.style.height = height + 'px';
  11989. }
  11990. this.setViewport( 0, 0, width, height );
  11991. };
  11992. this.setViewport = function ( x, y, width, height ) {
  11993. _viewportX = x * this.devicePixelRatio;
  11994. _viewportY = y * this.devicePixelRatio;
  11995. _viewportWidth = width * this.devicePixelRatio;
  11996. _viewportHeight = height * this.devicePixelRatio;
  11997. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11998. };
  11999. this.setScissor = function ( x, y, width, height ) {
  12000. _gl.scissor(
  12001. x * this.devicePixelRatio,
  12002. y * this.devicePixelRatio,
  12003. width * this.devicePixelRatio,
  12004. height * this.devicePixelRatio
  12005. );
  12006. };
  12007. this.enableScissorTest = function ( enable ) {
  12008. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12009. };
  12010. // Clearing
  12011. this.setClearColor = function ( color, alpha ) {
  12012. _clearColor.set( color );
  12013. _clearAlpha = alpha !== undefined ? alpha : 1;
  12014. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12015. };
  12016. this.setClearColorHex = function ( hex, alpha ) {
  12017. console.warn( 'THREE.WebGLRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12018. this.setClearColor( hex, alpha );
  12019. };
  12020. this.getClearColor = function () {
  12021. return _clearColor;
  12022. };
  12023. this.getClearAlpha = function () {
  12024. return _clearAlpha;
  12025. };
  12026. this.clear = function ( color, depth, stencil ) {
  12027. var bits = 0;
  12028. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12029. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12030. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12031. _gl.clear( bits );
  12032. };
  12033. this.clearColor = function () {
  12034. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12035. };
  12036. this.clearDepth = function () {
  12037. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12038. };
  12039. this.clearStencil = function () {
  12040. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12041. };
  12042. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12043. this.setRenderTarget( renderTarget );
  12044. this.clear( color, depth, stencil );
  12045. };
  12046. // Plugins
  12047. this.addPostPlugin = function ( plugin ) {
  12048. plugin.init( this );
  12049. this.renderPluginsPost.push( plugin );
  12050. };
  12051. this.addPrePlugin = function ( plugin ) {
  12052. plugin.init( this );
  12053. this.renderPluginsPre.push( plugin );
  12054. };
  12055. // Rendering
  12056. this.updateShadowMap = function ( scene, camera ) {
  12057. _currentProgram = null;
  12058. _oldBlending = -1;
  12059. _oldDepthTest = -1;
  12060. _oldDepthWrite = -1;
  12061. _currentGeometryGroupHash = -1;
  12062. _currentMaterialId = -1;
  12063. _lightsNeedUpdate = true;
  12064. _oldDoubleSided = -1;
  12065. _oldFlipSided = -1;
  12066. this.shadowMapPlugin.update( scene, camera );
  12067. };
  12068. // Internal functions
  12069. // Buffer allocation
  12070. function createParticleBuffers ( geometry ) {
  12071. geometry.__webglVertexBuffer = _gl.createBuffer();
  12072. geometry.__webglColorBuffer = _gl.createBuffer();
  12073. _this.info.memory.geometries ++;
  12074. };
  12075. function createLineBuffers ( geometry ) {
  12076. geometry.__webglVertexBuffer = _gl.createBuffer();
  12077. geometry.__webglColorBuffer = _gl.createBuffer();
  12078. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12079. _this.info.memory.geometries ++;
  12080. };
  12081. function createMeshBuffers ( geometryGroup ) {
  12082. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12083. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12084. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12085. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12086. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12087. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12088. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12089. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12090. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12091. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12092. var m, ml;
  12093. if ( geometryGroup.numMorphTargets ) {
  12094. geometryGroup.__webglMorphTargetsBuffers = [];
  12095. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12096. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12097. }
  12098. }
  12099. if ( geometryGroup.numMorphNormals ) {
  12100. geometryGroup.__webglMorphNormalsBuffers = [];
  12101. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12102. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12103. }
  12104. }
  12105. _this.info.memory.geometries ++;
  12106. };
  12107. // Events
  12108. var onGeometryDispose = function ( event ) {
  12109. var geometry = event.target;
  12110. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12111. deallocateGeometry( geometry );
  12112. };
  12113. var onTextureDispose = function ( event ) {
  12114. var texture = event.target;
  12115. texture.removeEventListener( 'dispose', onTextureDispose );
  12116. deallocateTexture( texture );
  12117. _this.info.memory.textures --;
  12118. };
  12119. var onRenderTargetDispose = function ( event ) {
  12120. var renderTarget = event.target;
  12121. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12122. deallocateRenderTarget( renderTarget );
  12123. _this.info.memory.textures --;
  12124. };
  12125. var onMaterialDispose = function ( event ) {
  12126. var material = event.target;
  12127. material.removeEventListener( 'dispose', onMaterialDispose );
  12128. deallocateMaterial( material );
  12129. };
  12130. // Buffer deallocation
  12131. var deleteBuffers = function ( geometry ) {
  12132. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12133. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12134. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12135. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12136. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12137. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12138. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12139. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12140. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12141. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12142. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12143. // custom attributes
  12144. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12145. for ( var id in geometry.__webglCustomAttributesList ) {
  12146. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12147. }
  12148. }
  12149. _this.info.memory.geometries --;
  12150. };
  12151. var deallocateGeometry = function ( geometry ) {
  12152. geometry.__webglInit = undefined;
  12153. if ( geometry instanceof THREE.BufferGeometry ) {
  12154. var attributes = geometry.attributes;
  12155. for ( var key in attributes ) {
  12156. if ( attributes[ key ].buffer !== undefined ) {
  12157. _gl.deleteBuffer( attributes[ key ].buffer );
  12158. }
  12159. }
  12160. _this.info.memory.geometries --;
  12161. } else {
  12162. if ( geometry.geometryGroups !== undefined ) {
  12163. for ( var g in geometry.geometryGroups ) {
  12164. var geometryGroup = geometry.geometryGroups[ g ];
  12165. if ( geometryGroup.numMorphTargets !== undefined ) {
  12166. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12167. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12168. }
  12169. }
  12170. if ( geometryGroup.numMorphNormals !== undefined ) {
  12171. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12172. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12173. }
  12174. }
  12175. deleteBuffers( geometryGroup );
  12176. }
  12177. } else {
  12178. deleteBuffers( geometry );
  12179. }
  12180. }
  12181. };
  12182. var deallocateTexture = function ( texture ) {
  12183. if ( texture.image && texture.image.__webglTextureCube ) {
  12184. // cube texture
  12185. _gl.deleteTexture( texture.image.__webglTextureCube );
  12186. } else {
  12187. // 2D texture
  12188. if ( ! texture.__webglInit ) return;
  12189. texture.__webglInit = false;
  12190. _gl.deleteTexture( texture.__webglTexture );
  12191. }
  12192. };
  12193. var deallocateRenderTarget = function ( renderTarget ) {
  12194. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12195. _gl.deleteTexture( renderTarget.__webglTexture );
  12196. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12197. for ( var i = 0; i < 6; i ++ ) {
  12198. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12199. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12200. }
  12201. } else {
  12202. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12203. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12204. }
  12205. };
  12206. var deallocateMaterial = function ( material ) {
  12207. var program = material.program;
  12208. if ( program === undefined ) return;
  12209. material.program = undefined;
  12210. // only deallocate GL program if this was the last use of shared program
  12211. // assumed there is only single copy of any program in the _programs list
  12212. // (that's how it's constructed)
  12213. var i, il, programInfo;
  12214. var deleteProgram = false;
  12215. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12216. programInfo = _programs[ i ];
  12217. if ( programInfo.program === program ) {
  12218. programInfo.usedTimes --;
  12219. if ( programInfo.usedTimes === 0 ) {
  12220. deleteProgram = true;
  12221. }
  12222. break;
  12223. }
  12224. }
  12225. if ( deleteProgram === true ) {
  12226. // avoid using array.splice, this is costlier than creating new array from scratch
  12227. var newPrograms = [];
  12228. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12229. programInfo = _programs[ i ];
  12230. if ( programInfo.program !== program ) {
  12231. newPrograms.push( programInfo );
  12232. }
  12233. }
  12234. _programs = newPrograms;
  12235. _gl.deleteProgram( program );
  12236. _this.info.memory.programs --;
  12237. }
  12238. };
  12239. // Buffer initialization
  12240. function initCustomAttributes ( geometry, object ) {
  12241. var nvertices = geometry.vertices.length;
  12242. var material = object.material;
  12243. if ( material.attributes ) {
  12244. if ( geometry.__webglCustomAttributesList === undefined ) {
  12245. geometry.__webglCustomAttributesList = [];
  12246. }
  12247. for ( var a in material.attributes ) {
  12248. var attribute = material.attributes[ a ];
  12249. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12250. attribute.__webglInitialized = true;
  12251. var size = 1; // "f" and "i"
  12252. if ( attribute.type === "v2" ) size = 2;
  12253. else if ( attribute.type === "v3" ) size = 3;
  12254. else if ( attribute.type === "v4" ) size = 4;
  12255. else if ( attribute.type === "c" ) size = 3;
  12256. attribute.size = size;
  12257. attribute.array = new Float32Array( nvertices * size );
  12258. attribute.buffer = _gl.createBuffer();
  12259. attribute.buffer.belongsToAttribute = a;
  12260. attribute.needsUpdate = true;
  12261. }
  12262. geometry.__webglCustomAttributesList.push( attribute );
  12263. }
  12264. }
  12265. };
  12266. function initParticleBuffers ( geometry, object ) {
  12267. var nvertices = geometry.vertices.length;
  12268. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12269. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12270. geometry.__sortArray = [];
  12271. geometry.__webglParticleCount = nvertices;
  12272. initCustomAttributes ( geometry, object );
  12273. };
  12274. function initLineBuffers ( geometry, object ) {
  12275. var nvertices = geometry.vertices.length;
  12276. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12277. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12278. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12279. geometry.__webglLineCount = nvertices;
  12280. initCustomAttributes ( geometry, object );
  12281. };
  12282. function initMeshBuffers ( geometryGroup, object ) {
  12283. var geometry = object.geometry,
  12284. faces3 = geometryGroup.faces3,
  12285. nvertices = faces3.length * 3,
  12286. ntris = faces3.length * 1,
  12287. nlines = faces3.length * 3,
  12288. material = getBufferMaterial( object, geometryGroup ),
  12289. uvType = bufferGuessUVType( material ),
  12290. normalType = bufferGuessNormalType( material ),
  12291. vertexColorType = bufferGuessVertexColorType( material );
  12292. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12293. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12294. if ( normalType ) {
  12295. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12296. }
  12297. if ( geometry.hasTangents ) {
  12298. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12299. }
  12300. if ( vertexColorType ) {
  12301. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12302. }
  12303. if ( uvType ) {
  12304. if ( geometry.faceVertexUvs.length > 0 ) {
  12305. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12306. }
  12307. if ( geometry.faceVertexUvs.length > 1 ) {
  12308. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12309. }
  12310. }
  12311. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12312. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12313. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12314. }
  12315. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12316. geometryGroup.__typeArray = UintArray;
  12317. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12318. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12319. var m, ml;
  12320. if ( geometryGroup.numMorphTargets ) {
  12321. geometryGroup.__morphTargetsArrays = [];
  12322. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12323. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12324. }
  12325. }
  12326. if ( geometryGroup.numMorphNormals ) {
  12327. geometryGroup.__morphNormalsArrays = [];
  12328. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12329. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12330. }
  12331. }
  12332. geometryGroup.__webglFaceCount = ntris * 3;
  12333. geometryGroup.__webglLineCount = nlines * 2;
  12334. // custom attributes
  12335. if ( material.attributes ) {
  12336. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12337. geometryGroup.__webglCustomAttributesList = [];
  12338. }
  12339. for ( var a in material.attributes ) {
  12340. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12341. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12342. var originalAttribute = material.attributes[ a ];
  12343. var attribute = {};
  12344. for ( var property in originalAttribute ) {
  12345. attribute[ property ] = originalAttribute[ property ];
  12346. }
  12347. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12348. attribute.__webglInitialized = true;
  12349. var size = 1; // "f" and "i"
  12350. if ( attribute.type === "v2" ) size = 2;
  12351. else if ( attribute.type === "v3" ) size = 3;
  12352. else if ( attribute.type === "v4" ) size = 4;
  12353. else if ( attribute.type === "c" ) size = 3;
  12354. attribute.size = size;
  12355. attribute.array = new Float32Array( nvertices * size );
  12356. attribute.buffer = _gl.createBuffer();
  12357. attribute.buffer.belongsToAttribute = a;
  12358. originalAttribute.needsUpdate = true;
  12359. attribute.__original = originalAttribute;
  12360. }
  12361. geometryGroup.__webglCustomAttributesList.push( attribute );
  12362. }
  12363. }
  12364. geometryGroup.__inittedArrays = true;
  12365. };
  12366. function getBufferMaterial( object, geometryGroup ) {
  12367. return object.material instanceof THREE.MeshFaceMaterial
  12368. ? object.material.materials[ geometryGroup.materialIndex ]
  12369. : object.material;
  12370. };
  12371. function materialNeedsSmoothNormals ( material ) {
  12372. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12373. };
  12374. function bufferGuessNormalType ( material ) {
  12375. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12376. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12377. return false;
  12378. }
  12379. if ( materialNeedsSmoothNormals( material ) ) {
  12380. return THREE.SmoothShading;
  12381. } else {
  12382. return THREE.FlatShading;
  12383. }
  12384. };
  12385. function bufferGuessVertexColorType( material ) {
  12386. if ( material.vertexColors ) {
  12387. return material.vertexColors;
  12388. }
  12389. return false;
  12390. };
  12391. function bufferGuessUVType( material ) {
  12392. // material must use some texture to require uvs
  12393. if ( material.map ||
  12394. material.lightMap ||
  12395. material.bumpMap ||
  12396. material.normalMap ||
  12397. material.specularMap ||
  12398. material instanceof THREE.ShaderMaterial ) {
  12399. return true;
  12400. }
  12401. return false;
  12402. };
  12403. //
  12404. function initDirectBuffers( geometry ) {
  12405. for ( var name in geometry.attributes ) {
  12406. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12407. var attribute = geometry.attributes[ name ];
  12408. attribute.buffer = _gl.createBuffer();
  12409. _gl.bindBuffer( bufferType, attribute.buffer );
  12410. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12411. }
  12412. }
  12413. // Buffer setting
  12414. function setParticleBuffers ( geometry, hint, object ) {
  12415. var v, c, vertex, offset, index, color,
  12416. vertices = geometry.vertices,
  12417. vl = vertices.length,
  12418. colors = geometry.colors,
  12419. cl = colors.length,
  12420. vertexArray = geometry.__vertexArray,
  12421. colorArray = geometry.__colorArray,
  12422. sortArray = geometry.__sortArray,
  12423. dirtyVertices = geometry.verticesNeedUpdate,
  12424. dirtyElements = geometry.elementsNeedUpdate,
  12425. dirtyColors = geometry.colorsNeedUpdate,
  12426. customAttributes = geometry.__webglCustomAttributesList,
  12427. i, il,
  12428. a, ca, cal, value,
  12429. customAttribute;
  12430. if ( object.sortParticles ) {
  12431. _projScreenMatrixPS.copy( _projScreenMatrix );
  12432. _projScreenMatrixPS.multiply( object.matrixWorld );
  12433. for ( v = 0; v < vl; v ++ ) {
  12434. vertex = vertices[ v ];
  12435. _vector3.copy( vertex );
  12436. _vector3.applyProjection( _projScreenMatrixPS );
  12437. sortArray[ v ] = [ _vector3.z, v ];
  12438. }
  12439. sortArray.sort( numericalSort );
  12440. for ( v = 0; v < vl; v ++ ) {
  12441. vertex = vertices[ sortArray[v][1] ];
  12442. offset = v * 3;
  12443. vertexArray[ offset ] = vertex.x;
  12444. vertexArray[ offset + 1 ] = vertex.y;
  12445. vertexArray[ offset + 2 ] = vertex.z;
  12446. }
  12447. for ( c = 0; c < cl; c ++ ) {
  12448. offset = c * 3;
  12449. color = colors[ sortArray[c][1] ];
  12450. colorArray[ offset ] = color.r;
  12451. colorArray[ offset + 1 ] = color.g;
  12452. colorArray[ offset + 2 ] = color.b;
  12453. }
  12454. if ( customAttributes ) {
  12455. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12456. customAttribute = customAttributes[ i ];
  12457. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12458. offset = 0;
  12459. cal = customAttribute.value.length;
  12460. if ( customAttribute.size === 1 ) {
  12461. for ( ca = 0; ca < cal; ca ++ ) {
  12462. index = sortArray[ ca ][ 1 ];
  12463. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12464. }
  12465. } else if ( customAttribute.size === 2 ) {
  12466. for ( ca = 0; ca < cal; ca ++ ) {
  12467. index = sortArray[ ca ][ 1 ];
  12468. value = customAttribute.value[ index ];
  12469. customAttribute.array[ offset ] = value.x;
  12470. customAttribute.array[ offset + 1 ] = value.y;
  12471. offset += 2;
  12472. }
  12473. } else if ( customAttribute.size === 3 ) {
  12474. if ( customAttribute.type === "c" ) {
  12475. for ( ca = 0; ca < cal; ca ++ ) {
  12476. index = sortArray[ ca ][ 1 ];
  12477. value = customAttribute.value[ index ];
  12478. customAttribute.array[ offset ] = value.r;
  12479. customAttribute.array[ offset + 1 ] = value.g;
  12480. customAttribute.array[ offset + 2 ] = value.b;
  12481. offset += 3;
  12482. }
  12483. } else {
  12484. for ( ca = 0; ca < cal; ca ++ ) {
  12485. index = sortArray[ ca ][ 1 ];
  12486. value = customAttribute.value[ index ];
  12487. customAttribute.array[ offset ] = value.x;
  12488. customAttribute.array[ offset + 1 ] = value.y;
  12489. customAttribute.array[ offset + 2 ] = value.z;
  12490. offset += 3;
  12491. }
  12492. }
  12493. } else if ( customAttribute.size === 4 ) {
  12494. for ( ca = 0; ca < cal; ca ++ ) {
  12495. index = sortArray[ ca ][ 1 ];
  12496. value = customAttribute.value[ index ];
  12497. customAttribute.array[ offset ] = value.x;
  12498. customAttribute.array[ offset + 1 ] = value.y;
  12499. customAttribute.array[ offset + 2 ] = value.z;
  12500. customAttribute.array[ offset + 3 ] = value.w;
  12501. offset += 4;
  12502. }
  12503. }
  12504. }
  12505. }
  12506. } else {
  12507. if ( dirtyVertices ) {
  12508. for ( v = 0; v < vl; v ++ ) {
  12509. vertex = vertices[ v ];
  12510. offset = v * 3;
  12511. vertexArray[ offset ] = vertex.x;
  12512. vertexArray[ offset + 1 ] = vertex.y;
  12513. vertexArray[ offset + 2 ] = vertex.z;
  12514. }
  12515. }
  12516. if ( dirtyColors ) {
  12517. for ( c = 0; c < cl; c ++ ) {
  12518. color = colors[ c ];
  12519. offset = c * 3;
  12520. colorArray[ offset ] = color.r;
  12521. colorArray[ offset + 1 ] = color.g;
  12522. colorArray[ offset + 2 ] = color.b;
  12523. }
  12524. }
  12525. if ( customAttributes ) {
  12526. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12527. customAttribute = customAttributes[ i ];
  12528. if ( customAttribute.needsUpdate &&
  12529. ( customAttribute.boundTo === undefined ||
  12530. customAttribute.boundTo === "vertices") ) {
  12531. cal = customAttribute.value.length;
  12532. offset = 0;
  12533. if ( customAttribute.size === 1 ) {
  12534. for ( ca = 0; ca < cal; ca ++ ) {
  12535. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12536. }
  12537. } else if ( customAttribute.size === 2 ) {
  12538. for ( ca = 0; ca < cal; ca ++ ) {
  12539. value = customAttribute.value[ ca ];
  12540. customAttribute.array[ offset ] = value.x;
  12541. customAttribute.array[ offset + 1 ] = value.y;
  12542. offset += 2;
  12543. }
  12544. } else if ( customAttribute.size === 3 ) {
  12545. if ( customAttribute.type === "c" ) {
  12546. for ( ca = 0; ca < cal; ca ++ ) {
  12547. value = customAttribute.value[ ca ];
  12548. customAttribute.array[ offset ] = value.r;
  12549. customAttribute.array[ offset + 1 ] = value.g;
  12550. customAttribute.array[ offset + 2 ] = value.b;
  12551. offset += 3;
  12552. }
  12553. } else {
  12554. for ( ca = 0; ca < cal; ca ++ ) {
  12555. value = customAttribute.value[ ca ];
  12556. customAttribute.array[ offset ] = value.x;
  12557. customAttribute.array[ offset + 1 ] = value.y;
  12558. customAttribute.array[ offset + 2 ] = value.z;
  12559. offset += 3;
  12560. }
  12561. }
  12562. } else if ( customAttribute.size === 4 ) {
  12563. for ( ca = 0; ca < cal; ca ++ ) {
  12564. value = customAttribute.value[ ca ];
  12565. customAttribute.array[ offset ] = value.x;
  12566. customAttribute.array[ offset + 1 ] = value.y;
  12567. customAttribute.array[ offset + 2 ] = value.z;
  12568. customAttribute.array[ offset + 3 ] = value.w;
  12569. offset += 4;
  12570. }
  12571. }
  12572. }
  12573. }
  12574. }
  12575. }
  12576. if ( dirtyVertices || object.sortParticles ) {
  12577. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12578. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12579. }
  12580. if ( dirtyColors || object.sortParticles ) {
  12581. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12582. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12583. }
  12584. if ( customAttributes ) {
  12585. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12586. customAttribute = customAttributes[ i ];
  12587. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12588. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12589. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12590. }
  12591. }
  12592. }
  12593. }
  12594. function setLineBuffers ( geometry, hint ) {
  12595. var v, c, d, vertex, offset, color,
  12596. vertices = geometry.vertices,
  12597. colors = geometry.colors,
  12598. lineDistances = geometry.lineDistances,
  12599. vl = vertices.length,
  12600. cl = colors.length,
  12601. dl = lineDistances.length,
  12602. vertexArray = geometry.__vertexArray,
  12603. colorArray = geometry.__colorArray,
  12604. lineDistanceArray = geometry.__lineDistanceArray,
  12605. dirtyVertices = geometry.verticesNeedUpdate,
  12606. dirtyColors = geometry.colorsNeedUpdate,
  12607. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12608. customAttributes = geometry.__webglCustomAttributesList,
  12609. i, il,
  12610. a, ca, cal, value,
  12611. customAttribute;
  12612. if ( dirtyVertices ) {
  12613. for ( v = 0; v < vl; v ++ ) {
  12614. vertex = vertices[ v ];
  12615. offset = v * 3;
  12616. vertexArray[ offset ] = vertex.x;
  12617. vertexArray[ offset + 1 ] = vertex.y;
  12618. vertexArray[ offset + 2 ] = vertex.z;
  12619. }
  12620. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12621. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12622. }
  12623. if ( dirtyColors ) {
  12624. for ( c = 0; c < cl; c ++ ) {
  12625. color = colors[ c ];
  12626. offset = c * 3;
  12627. colorArray[ offset ] = color.r;
  12628. colorArray[ offset + 1 ] = color.g;
  12629. colorArray[ offset + 2 ] = color.b;
  12630. }
  12631. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12632. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12633. }
  12634. if ( dirtyLineDistances ) {
  12635. for ( d = 0; d < dl; d ++ ) {
  12636. lineDistanceArray[ d ] = lineDistances[ d ];
  12637. }
  12638. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12639. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12640. }
  12641. if ( customAttributes ) {
  12642. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12643. customAttribute = customAttributes[ i ];
  12644. if ( customAttribute.needsUpdate &&
  12645. ( customAttribute.boundTo === undefined ||
  12646. customAttribute.boundTo === "vertices" ) ) {
  12647. offset = 0;
  12648. cal = customAttribute.value.length;
  12649. if ( customAttribute.size === 1 ) {
  12650. for ( ca = 0; ca < cal; ca ++ ) {
  12651. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12652. }
  12653. } else if ( customAttribute.size === 2 ) {
  12654. for ( ca = 0; ca < cal; ca ++ ) {
  12655. value = customAttribute.value[ ca ];
  12656. customAttribute.array[ offset ] = value.x;
  12657. customAttribute.array[ offset + 1 ] = value.y;
  12658. offset += 2;
  12659. }
  12660. } else if ( customAttribute.size === 3 ) {
  12661. if ( customAttribute.type === "c" ) {
  12662. for ( ca = 0; ca < cal; ca ++ ) {
  12663. value = customAttribute.value[ ca ];
  12664. customAttribute.array[ offset ] = value.r;
  12665. customAttribute.array[ offset + 1 ] = value.g;
  12666. customAttribute.array[ offset + 2 ] = value.b;
  12667. offset += 3;
  12668. }
  12669. } else {
  12670. for ( ca = 0; ca < cal; ca ++ ) {
  12671. value = customAttribute.value[ ca ];
  12672. customAttribute.array[ offset ] = value.x;
  12673. customAttribute.array[ offset + 1 ] = value.y;
  12674. customAttribute.array[ offset + 2 ] = value.z;
  12675. offset += 3;
  12676. }
  12677. }
  12678. } else if ( customAttribute.size === 4 ) {
  12679. for ( ca = 0; ca < cal; ca ++ ) {
  12680. value = customAttribute.value[ ca ];
  12681. customAttribute.array[ offset ] = value.x;
  12682. customAttribute.array[ offset + 1 ] = value.y;
  12683. customAttribute.array[ offset + 2 ] = value.z;
  12684. customAttribute.array[ offset + 3 ] = value.w;
  12685. offset += 4;
  12686. }
  12687. }
  12688. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12689. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12690. }
  12691. }
  12692. }
  12693. }
  12694. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12695. if ( ! geometryGroup.__inittedArrays ) {
  12696. return;
  12697. }
  12698. var normalType = bufferGuessNormalType( material ),
  12699. vertexColorType = bufferGuessVertexColorType( material ),
  12700. uvType = bufferGuessUVType( material ),
  12701. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12702. var f, fl, fi, face,
  12703. vertexNormals, faceNormal, normal,
  12704. vertexColors, faceColor,
  12705. vertexTangents,
  12706. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12707. c1, c2, c3, c4,
  12708. sw1, sw2, sw3, sw4,
  12709. si1, si2, si3, si4,
  12710. sa1, sa2, sa3, sa4,
  12711. sb1, sb2, sb3, sb4,
  12712. m, ml, i, il,
  12713. vn, uvi, uv2i,
  12714. vk, vkl, vka,
  12715. nka, chf, faceVertexNormals,
  12716. a,
  12717. vertexIndex = 0,
  12718. offset = 0,
  12719. offset_uv = 0,
  12720. offset_uv2 = 0,
  12721. offset_face = 0,
  12722. offset_normal = 0,
  12723. offset_tangent = 0,
  12724. offset_line = 0,
  12725. offset_color = 0,
  12726. offset_skin = 0,
  12727. offset_morphTarget = 0,
  12728. offset_custom = 0,
  12729. offset_customSrc = 0,
  12730. value,
  12731. vertexArray = geometryGroup.__vertexArray,
  12732. uvArray = geometryGroup.__uvArray,
  12733. uv2Array = geometryGroup.__uv2Array,
  12734. normalArray = geometryGroup.__normalArray,
  12735. tangentArray = geometryGroup.__tangentArray,
  12736. colorArray = geometryGroup.__colorArray,
  12737. skinIndexArray = geometryGroup.__skinIndexArray,
  12738. skinWeightArray = geometryGroup.__skinWeightArray,
  12739. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12740. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12741. customAttributes = geometryGroup.__webglCustomAttributesList,
  12742. customAttribute,
  12743. faceArray = geometryGroup.__faceArray,
  12744. lineArray = geometryGroup.__lineArray,
  12745. geometry = object.geometry, // this is shared for all chunks
  12746. dirtyVertices = geometry.verticesNeedUpdate,
  12747. dirtyElements = geometry.elementsNeedUpdate,
  12748. dirtyUvs = geometry.uvsNeedUpdate,
  12749. dirtyNormals = geometry.normalsNeedUpdate,
  12750. dirtyTangents = geometry.tangentsNeedUpdate,
  12751. dirtyColors = geometry.colorsNeedUpdate,
  12752. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12753. vertices = geometry.vertices,
  12754. chunk_faces3 = geometryGroup.faces3,
  12755. obj_faces = geometry.faces,
  12756. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12757. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12758. obj_colors = geometry.colors,
  12759. obj_skinIndices = geometry.skinIndices,
  12760. obj_skinWeights = geometry.skinWeights,
  12761. morphTargets = geometry.morphTargets,
  12762. morphNormals = geometry.morphNormals;
  12763. if ( dirtyVertices ) {
  12764. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12765. face = obj_faces[ chunk_faces3[ f ] ];
  12766. v1 = vertices[ face.a ];
  12767. v2 = vertices[ face.b ];
  12768. v3 = vertices[ face.c ];
  12769. vertexArray[ offset ] = v1.x;
  12770. vertexArray[ offset + 1 ] = v1.y;
  12771. vertexArray[ offset + 2 ] = v1.z;
  12772. vertexArray[ offset + 3 ] = v2.x;
  12773. vertexArray[ offset + 4 ] = v2.y;
  12774. vertexArray[ offset + 5 ] = v2.z;
  12775. vertexArray[ offset + 6 ] = v3.x;
  12776. vertexArray[ offset + 7 ] = v3.y;
  12777. vertexArray[ offset + 8 ] = v3.z;
  12778. offset += 9;
  12779. }
  12780. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12781. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12782. }
  12783. if ( dirtyMorphTargets ) {
  12784. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12785. offset_morphTarget = 0;
  12786. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12787. chf = chunk_faces3[ f ];
  12788. face = obj_faces[ chf ];
  12789. // morph positions
  12790. v1 = morphTargets[ vk ].vertices[ face.a ];
  12791. v2 = morphTargets[ vk ].vertices[ face.b ];
  12792. v3 = morphTargets[ vk ].vertices[ face.c ];
  12793. vka = morphTargetsArrays[ vk ];
  12794. vka[ offset_morphTarget ] = v1.x;
  12795. vka[ offset_morphTarget + 1 ] = v1.y;
  12796. vka[ offset_morphTarget + 2 ] = v1.z;
  12797. vka[ offset_morphTarget + 3 ] = v2.x;
  12798. vka[ offset_morphTarget + 4 ] = v2.y;
  12799. vka[ offset_morphTarget + 5 ] = v2.z;
  12800. vka[ offset_morphTarget + 6 ] = v3.x;
  12801. vka[ offset_morphTarget + 7 ] = v3.y;
  12802. vka[ offset_morphTarget + 8 ] = v3.z;
  12803. // morph normals
  12804. if ( material.morphNormals ) {
  12805. if ( needsSmoothNormals ) {
  12806. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12807. n1 = faceVertexNormals.a;
  12808. n2 = faceVertexNormals.b;
  12809. n3 = faceVertexNormals.c;
  12810. } else {
  12811. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12812. n2 = n1;
  12813. n3 = n1;
  12814. }
  12815. nka = morphNormalsArrays[ vk ];
  12816. nka[ offset_morphTarget ] = n1.x;
  12817. nka[ offset_morphTarget + 1 ] = n1.y;
  12818. nka[ offset_morphTarget + 2 ] = n1.z;
  12819. nka[ offset_morphTarget + 3 ] = n2.x;
  12820. nka[ offset_morphTarget + 4 ] = n2.y;
  12821. nka[ offset_morphTarget + 5 ] = n2.z;
  12822. nka[ offset_morphTarget + 6 ] = n3.x;
  12823. nka[ offset_morphTarget + 7 ] = n3.y;
  12824. nka[ offset_morphTarget + 8 ] = n3.z;
  12825. }
  12826. //
  12827. offset_morphTarget += 9;
  12828. }
  12829. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12830. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12831. if ( material.morphNormals ) {
  12832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12833. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12834. }
  12835. }
  12836. }
  12837. if ( obj_skinWeights.length ) {
  12838. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12839. face = obj_faces[ chunk_faces3[ f ] ];
  12840. // weights
  12841. sw1 = obj_skinWeights[ face.a ];
  12842. sw2 = obj_skinWeights[ face.b ];
  12843. sw3 = obj_skinWeights[ face.c ];
  12844. skinWeightArray[ offset_skin ] = sw1.x;
  12845. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12846. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12847. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12848. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12849. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12850. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12851. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12852. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12853. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12854. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12855. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12856. // indices
  12857. si1 = obj_skinIndices[ face.a ];
  12858. si2 = obj_skinIndices[ face.b ];
  12859. si3 = obj_skinIndices[ face.c ];
  12860. skinIndexArray[ offset_skin ] = si1.x;
  12861. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12862. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12863. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12864. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12865. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12866. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12867. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12868. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12869. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12870. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12871. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12872. offset_skin += 12;
  12873. }
  12874. if ( offset_skin > 0 ) {
  12875. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12876. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12877. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12878. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12879. }
  12880. }
  12881. if ( dirtyColors && vertexColorType ) {
  12882. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12883. face = obj_faces[ chunk_faces3[ f ] ];
  12884. vertexColors = face.vertexColors;
  12885. faceColor = face.color;
  12886. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12887. c1 = vertexColors[ 0 ];
  12888. c2 = vertexColors[ 1 ];
  12889. c3 = vertexColors[ 2 ];
  12890. } else {
  12891. c1 = faceColor;
  12892. c2 = faceColor;
  12893. c3 = faceColor;
  12894. }
  12895. colorArray[ offset_color ] = c1.r;
  12896. colorArray[ offset_color + 1 ] = c1.g;
  12897. colorArray[ offset_color + 2 ] = c1.b;
  12898. colorArray[ offset_color + 3 ] = c2.r;
  12899. colorArray[ offset_color + 4 ] = c2.g;
  12900. colorArray[ offset_color + 5 ] = c2.b;
  12901. colorArray[ offset_color + 6 ] = c3.r;
  12902. colorArray[ offset_color + 7 ] = c3.g;
  12903. colorArray[ offset_color + 8 ] = c3.b;
  12904. offset_color += 9;
  12905. }
  12906. if ( offset_color > 0 ) {
  12907. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12908. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12909. }
  12910. }
  12911. if ( dirtyTangents && geometry.hasTangents ) {
  12912. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12913. face = obj_faces[ chunk_faces3[ f ] ];
  12914. vertexTangents = face.vertexTangents;
  12915. t1 = vertexTangents[ 0 ];
  12916. t2 = vertexTangents[ 1 ];
  12917. t3 = vertexTangents[ 2 ];
  12918. tangentArray[ offset_tangent ] = t1.x;
  12919. tangentArray[ offset_tangent + 1 ] = t1.y;
  12920. tangentArray[ offset_tangent + 2 ] = t1.z;
  12921. tangentArray[ offset_tangent + 3 ] = t1.w;
  12922. tangentArray[ offset_tangent + 4 ] = t2.x;
  12923. tangentArray[ offset_tangent + 5 ] = t2.y;
  12924. tangentArray[ offset_tangent + 6 ] = t2.z;
  12925. tangentArray[ offset_tangent + 7 ] = t2.w;
  12926. tangentArray[ offset_tangent + 8 ] = t3.x;
  12927. tangentArray[ offset_tangent + 9 ] = t3.y;
  12928. tangentArray[ offset_tangent + 10 ] = t3.z;
  12929. tangentArray[ offset_tangent + 11 ] = t3.w;
  12930. offset_tangent += 12;
  12931. }
  12932. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12933. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12934. }
  12935. if ( dirtyNormals && normalType ) {
  12936. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12937. face = obj_faces[ chunk_faces3[ f ] ];
  12938. vertexNormals = face.vertexNormals;
  12939. faceNormal = face.normal;
  12940. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12941. for ( i = 0; i < 3; i ++ ) {
  12942. vn = vertexNormals[ i ];
  12943. normalArray[ offset_normal ] = vn.x;
  12944. normalArray[ offset_normal + 1 ] = vn.y;
  12945. normalArray[ offset_normal + 2 ] = vn.z;
  12946. offset_normal += 3;
  12947. }
  12948. } else {
  12949. for ( i = 0; i < 3; i ++ ) {
  12950. normalArray[ offset_normal ] = faceNormal.x;
  12951. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12952. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12953. offset_normal += 3;
  12954. }
  12955. }
  12956. }
  12957. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12958. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12959. }
  12960. if ( dirtyUvs && obj_uvs && uvType ) {
  12961. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12962. fi = chunk_faces3[ f ];
  12963. uv = obj_uvs[ fi ];
  12964. if ( uv === undefined ) continue;
  12965. for ( i = 0; i < 3; i ++ ) {
  12966. uvi = uv[ i ];
  12967. uvArray[ offset_uv ] = uvi.x;
  12968. uvArray[ offset_uv + 1 ] = uvi.y;
  12969. offset_uv += 2;
  12970. }
  12971. }
  12972. if ( offset_uv > 0 ) {
  12973. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12974. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12975. }
  12976. }
  12977. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12978. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12979. fi = chunk_faces3[ f ];
  12980. uv2 = obj_uvs2[ fi ];
  12981. if ( uv2 === undefined ) continue;
  12982. for ( i = 0; i < 3; i ++ ) {
  12983. uv2i = uv2[ i ];
  12984. uv2Array[ offset_uv2 ] = uv2i.x;
  12985. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12986. offset_uv2 += 2;
  12987. }
  12988. }
  12989. if ( offset_uv2 > 0 ) {
  12990. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12991. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12992. }
  12993. }
  12994. if ( dirtyElements ) {
  12995. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12996. faceArray[ offset_face ] = vertexIndex;
  12997. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12998. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12999. offset_face += 3;
  13000. lineArray[ offset_line ] = vertexIndex;
  13001. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13002. lineArray[ offset_line + 2 ] = vertexIndex;
  13003. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13004. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13005. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13006. offset_line += 6;
  13007. vertexIndex += 3;
  13008. }
  13009. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13010. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13011. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13012. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13013. }
  13014. if ( customAttributes ) {
  13015. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13016. customAttribute = customAttributes[ i ];
  13017. if ( ! customAttribute.__original.needsUpdate ) continue;
  13018. offset_custom = 0;
  13019. offset_customSrc = 0;
  13020. if ( customAttribute.size === 1 ) {
  13021. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13022. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13023. face = obj_faces[ chunk_faces3[ f ] ];
  13024. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13025. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13026. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13027. offset_custom += 3;
  13028. }
  13029. } else if ( customAttribute.boundTo === "faces" ) {
  13030. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13031. value = customAttribute.value[ chunk_faces3[ f ] ];
  13032. customAttribute.array[ offset_custom ] = value;
  13033. customAttribute.array[ offset_custom + 1 ] = value;
  13034. customAttribute.array[ offset_custom + 2 ] = value;
  13035. offset_custom += 3;
  13036. }
  13037. }
  13038. } else if ( customAttribute.size === 2 ) {
  13039. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13040. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13041. face = obj_faces[ chunk_faces3[ f ] ];
  13042. v1 = customAttribute.value[ face.a ];
  13043. v2 = customAttribute.value[ face.b ];
  13044. v3 = customAttribute.value[ face.c ];
  13045. customAttribute.array[ offset_custom ] = v1.x;
  13046. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13047. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13048. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13049. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13050. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13051. offset_custom += 6;
  13052. }
  13053. } else if ( customAttribute.boundTo === "faces" ) {
  13054. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13055. value = customAttribute.value[ chunk_faces3[ f ] ];
  13056. v1 = value;
  13057. v2 = value;
  13058. v3 = value;
  13059. customAttribute.array[ offset_custom ] = v1.x;
  13060. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13061. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13062. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13063. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13064. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13065. offset_custom += 6;
  13066. }
  13067. }
  13068. } else if ( customAttribute.size === 3 ) {
  13069. var pp;
  13070. if ( customAttribute.type === "c" ) {
  13071. pp = [ "r", "g", "b" ];
  13072. } else {
  13073. pp = [ "x", "y", "z" ];
  13074. }
  13075. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13076. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13077. face = obj_faces[ chunk_faces3[ f ] ];
  13078. v1 = customAttribute.value[ face.a ];
  13079. v2 = customAttribute.value[ face.b ];
  13080. v3 = customAttribute.value[ face.c ];
  13081. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13082. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13083. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13084. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13085. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13086. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13087. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13088. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13089. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13090. offset_custom += 9;
  13091. }
  13092. } else if ( customAttribute.boundTo === "faces" ) {
  13093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13094. value = customAttribute.value[ chunk_faces3[ f ] ];
  13095. v1 = value;
  13096. v2 = value;
  13097. v3 = value;
  13098. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13099. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13100. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13101. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13102. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13103. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13104. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13105. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13106. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13107. offset_custom += 9;
  13108. }
  13109. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13110. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13111. value = customAttribute.value[ chunk_faces3[ f ] ];
  13112. v1 = value[ 0 ];
  13113. v2 = value[ 1 ];
  13114. v3 = value[ 2 ];
  13115. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13116. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13117. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13118. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13119. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13120. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13121. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13122. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13123. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13124. offset_custom += 9;
  13125. }
  13126. }
  13127. } else if ( customAttribute.size === 4 ) {
  13128. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13129. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13130. face = obj_faces[ chunk_faces3[ f ] ];
  13131. v1 = customAttribute.value[ face.a ];
  13132. v2 = customAttribute.value[ face.b ];
  13133. v3 = customAttribute.value[ face.c ];
  13134. customAttribute.array[ offset_custom ] = v1.x;
  13135. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13136. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13137. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13138. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13139. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13140. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13141. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13142. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13143. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13144. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13145. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13146. offset_custom += 12;
  13147. }
  13148. } else if ( customAttribute.boundTo === "faces" ) {
  13149. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13150. value = customAttribute.value[ chunk_faces3[ f ] ];
  13151. v1 = value;
  13152. v2 = value;
  13153. v3 = value;
  13154. customAttribute.array[ offset_custom ] = v1.x;
  13155. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13156. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13157. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13158. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13159. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13160. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13161. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13162. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13163. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13164. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13165. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13166. offset_custom += 12;
  13167. }
  13168. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13169. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13170. value = customAttribute.value[ chunk_faces3[ f ] ];
  13171. v1 = value[ 0 ];
  13172. v2 = value[ 1 ];
  13173. v3 = value[ 2 ];
  13174. customAttribute.array[ offset_custom ] = v1.x;
  13175. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13176. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13177. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13178. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13179. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13180. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13181. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13182. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13183. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13184. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13185. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13186. offset_custom += 12;
  13187. }
  13188. }
  13189. }
  13190. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13191. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13192. }
  13193. }
  13194. if ( dispose ) {
  13195. delete geometryGroup.__inittedArrays;
  13196. delete geometryGroup.__colorArray;
  13197. delete geometryGroup.__normalArray;
  13198. delete geometryGroup.__tangentArray;
  13199. delete geometryGroup.__uvArray;
  13200. delete geometryGroup.__uv2Array;
  13201. delete geometryGroup.__faceArray;
  13202. delete geometryGroup.__vertexArray;
  13203. delete geometryGroup.__lineArray;
  13204. delete geometryGroup.__skinIndexArray;
  13205. delete geometryGroup.__skinWeightArray;
  13206. }
  13207. };
  13208. function setDirectBuffers( geometry, hint ) {
  13209. var attributes = geometry.attributes;
  13210. var attributeName, attributeItem;
  13211. for ( attributeName in attributes ) {
  13212. attributeItem = attributes[ attributeName ];
  13213. if ( attributeItem.needsUpdate ) {
  13214. if ( attributeName === 'index' ) {
  13215. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13216. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13217. } else {
  13218. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13219. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13220. }
  13221. attributeItem.needsUpdate = false;
  13222. }
  13223. }
  13224. }
  13225. // Buffer rendering
  13226. this.renderBufferImmediate = function ( object, program, material ) {
  13227. initAttributes();
  13228. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13229. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13230. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13231. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13232. if ( object.hasPositions ) {
  13233. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13234. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13235. enableAttribute( program.attributes.position );
  13236. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13237. }
  13238. if ( object.hasNormals ) {
  13239. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13240. if ( material.shading === THREE.FlatShading ) {
  13241. var nx, ny, nz,
  13242. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13243. normalArray,
  13244. i, il = object.count * 3;
  13245. for ( i = 0; i < il; i += 9 ) {
  13246. normalArray = object.normalArray;
  13247. nax = normalArray[ i ];
  13248. nay = normalArray[ i + 1 ];
  13249. naz = normalArray[ i + 2 ];
  13250. nbx = normalArray[ i + 3 ];
  13251. nby = normalArray[ i + 4 ];
  13252. nbz = normalArray[ i + 5 ];
  13253. ncx = normalArray[ i + 6 ];
  13254. ncy = normalArray[ i + 7 ];
  13255. ncz = normalArray[ i + 8 ];
  13256. nx = ( nax + nbx + ncx ) / 3;
  13257. ny = ( nay + nby + ncy ) / 3;
  13258. nz = ( naz + nbz + ncz ) / 3;
  13259. normalArray[ i ] = nx;
  13260. normalArray[ i + 1 ] = ny;
  13261. normalArray[ i + 2 ] = nz;
  13262. normalArray[ i + 3 ] = nx;
  13263. normalArray[ i + 4 ] = ny;
  13264. normalArray[ i + 5 ] = nz;
  13265. normalArray[ i + 6 ] = nx;
  13266. normalArray[ i + 7 ] = ny;
  13267. normalArray[ i + 8 ] = nz;
  13268. }
  13269. }
  13270. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13271. enableAttribute( program.attributes.normal );
  13272. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13273. }
  13274. if ( object.hasUvs && material.map ) {
  13275. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13276. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13277. enableAttribute( program.attributes.uv );
  13278. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13279. }
  13280. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13281. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13282. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13283. enableAttribute( program.attributes.color );
  13284. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13285. }
  13286. disableUnusedAttributes();
  13287. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13288. object.count = 0;
  13289. };
  13290. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13291. for ( var attributeName in programAttributes ) {
  13292. var attributePointer = programAttributes[ attributeName ];
  13293. var attributeItem = geometryAttributes[ attributeName ];
  13294. if ( attributePointer >= 0 ) {
  13295. if ( attributeItem ) {
  13296. var attributeSize = attributeItem.itemSize;
  13297. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13298. enableAttribute( attributePointer );
  13299. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13300. } else if ( material.defaultAttributeValues ) {
  13301. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13302. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13303. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13304. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13305. }
  13306. }
  13307. }
  13308. }
  13309. disableUnusedAttributes();
  13310. }
  13311. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13312. if ( material.visible === false ) return;
  13313. var linewidth, a, attribute;
  13314. var attributeItem, attributeName, attributePointer, attributeSize;
  13315. var program = setProgram( camera, lights, fog, material, object );
  13316. var programAttributes = program.attributes;
  13317. var geometryAttributes = geometry.attributes;
  13318. var updateBuffers = false,
  13319. wireframeBit = material.wireframe ? 1 : 0,
  13320. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13321. if ( geometryHash !== _currentGeometryGroupHash ) {
  13322. _currentGeometryGroupHash = geometryHash;
  13323. updateBuffers = true;
  13324. }
  13325. if ( updateBuffers ) {
  13326. initAttributes();
  13327. }
  13328. // render mesh
  13329. if ( object instanceof THREE.Mesh ) {
  13330. var index = geometryAttributes[ "index" ];
  13331. if ( index ) {
  13332. // indexed triangles
  13333. var type, size;
  13334. if ( index.array instanceof Uint32Array ) {
  13335. type = _gl.UNSIGNED_INT;
  13336. size = 4;
  13337. } else {
  13338. type = _gl.UNSIGNED_SHORT;
  13339. size = 2;
  13340. }
  13341. var offsets = geometry.offsets;
  13342. if ( offsets.length === 0 ) {
  13343. if ( updateBuffers ) {
  13344. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13345. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13346. }
  13347. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13348. _this.info.render.calls ++;
  13349. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13350. _this.info.render.faces += index.array.length / 3;
  13351. } else {
  13352. // if there is more than 1 chunk
  13353. // must set attribute pointers to use new offsets for each chunk
  13354. // even if geometry and materials didn't change
  13355. updateBuffers = true;
  13356. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13357. var startIndex = offsets[ i ].index;
  13358. if ( updateBuffers ) {
  13359. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13360. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13361. }
  13362. // render indexed triangles
  13363. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13364. _this.info.render.calls ++;
  13365. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13366. _this.info.render.faces += offsets[ i ].count / 3;
  13367. }
  13368. }
  13369. } else {
  13370. // non-indexed triangles
  13371. if ( updateBuffers ) {
  13372. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13373. }
  13374. var position = geometry.attributes[ "position" ];
  13375. // render non-indexed triangles
  13376. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13377. _this.info.render.calls ++;
  13378. _this.info.render.vertices += position.array.length / 3;
  13379. _this.info.render.faces += position.array.length / 9;
  13380. }
  13381. } else if ( object instanceof THREE.PointCloud ) {
  13382. // render particles
  13383. if ( updateBuffers ) {
  13384. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13385. }
  13386. var position = geometryAttributes[ "position" ];
  13387. // render particles
  13388. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13389. _this.info.render.calls ++;
  13390. _this.info.render.points += position.array.length / 3;
  13391. } else if ( object instanceof THREE.Line ) {
  13392. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13393. setLineWidth( material.linewidth );
  13394. var index = geometryAttributes[ "index" ];
  13395. if ( index ) {
  13396. // indexed lines
  13397. var type, size;
  13398. if ( index.array instanceof Uint32Array ) {
  13399. type = _gl.UNSIGNED_INT;
  13400. size = 4;
  13401. } else {
  13402. type = _gl.UNSIGNED_SHORT;
  13403. size = 2;
  13404. }
  13405. var offsets = geometry.offsets;
  13406. if ( offsets.length === 0 ) {
  13407. if ( updateBuffers ) {
  13408. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13409. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13410. }
  13411. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13412. _this.info.render.calls ++;
  13413. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13414. } else {
  13415. // if there is more than 1 chunk
  13416. // must set attribute pointers to use new offsets for each chunk
  13417. // even if geometry and materials didn't change
  13418. if ( offsets.length > 1 ) updateBuffers = true;
  13419. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13420. var startIndex = offsets[ i ].index;
  13421. if ( updateBuffers ) {
  13422. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13423. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13424. }
  13425. // render indexed lines
  13426. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13427. _this.info.render.calls ++;
  13428. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13429. }
  13430. }
  13431. } else {
  13432. // non-indexed lines
  13433. if ( updateBuffers ) {
  13434. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13435. }
  13436. var position = geometryAttributes[ "position" ];
  13437. _gl.drawArrays( mode, 0, position.array.length / 3 );
  13438. _this.info.render.calls ++;
  13439. _this.info.render.points += position.array.length / 3;
  13440. }
  13441. }
  13442. };
  13443. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13444. if ( material.visible === false ) return;
  13445. var linewidth, a, attribute, i, il;
  13446. var program = setProgram( camera, lights, fog, material, object );
  13447. var attributes = program.attributes;
  13448. var updateBuffers = false,
  13449. wireframeBit = material.wireframe ? 1 : 0,
  13450. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13451. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13452. _currentGeometryGroupHash = geometryGroupHash;
  13453. updateBuffers = true;
  13454. }
  13455. if ( updateBuffers ) {
  13456. initAttributes();
  13457. }
  13458. // vertices
  13459. if ( !material.morphTargets && attributes.position >= 0 ) {
  13460. if ( updateBuffers ) {
  13461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13462. enableAttribute( attributes.position );
  13463. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13464. }
  13465. } else {
  13466. if ( object.morphTargetBase ) {
  13467. setupMorphTargets( material, geometryGroup, object );
  13468. }
  13469. }
  13470. if ( updateBuffers ) {
  13471. // custom attributes
  13472. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13473. if ( geometryGroup.__webglCustomAttributesList ) {
  13474. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13475. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13476. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13477. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13478. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13479. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13480. }
  13481. }
  13482. }
  13483. // colors
  13484. if ( attributes.color >= 0 ) {
  13485. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13486. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13487. enableAttribute( attributes.color );
  13488. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13489. } else if ( material.defaultAttributeValues ) {
  13490. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13491. }
  13492. }
  13493. // normals
  13494. if ( attributes.normal >= 0 ) {
  13495. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13496. enableAttribute( attributes.normal );
  13497. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13498. }
  13499. // tangents
  13500. if ( attributes.tangent >= 0 ) {
  13501. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13502. enableAttribute( attributes.tangent );
  13503. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13504. }
  13505. // uvs
  13506. if ( attributes.uv >= 0 ) {
  13507. if ( object.geometry.faceVertexUvs[0] ) {
  13508. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13509. enableAttribute( attributes.uv );
  13510. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13511. } else if ( material.defaultAttributeValues ) {
  13512. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13513. }
  13514. }
  13515. if ( attributes.uv2 >= 0 ) {
  13516. if ( object.geometry.faceVertexUvs[1] ) {
  13517. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13518. enableAttribute( attributes.uv2 );
  13519. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13520. } else if ( material.defaultAttributeValues ) {
  13521. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13522. }
  13523. }
  13524. if ( material.skinning &&
  13525. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13526. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13527. enableAttribute( attributes.skinIndex );
  13528. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13530. enableAttribute( attributes.skinWeight );
  13531. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13532. }
  13533. // line distances
  13534. if ( attributes.lineDistance >= 0 ) {
  13535. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13536. enableAttribute( attributes.lineDistance );
  13537. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13538. }
  13539. }
  13540. disableUnusedAttributes();
  13541. // render mesh
  13542. if ( object instanceof THREE.Mesh ) {
  13543. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13544. // wireframe
  13545. if ( material.wireframe ) {
  13546. setLineWidth( material.wireframeLinewidth );
  13547. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13548. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13549. // triangles
  13550. } else {
  13551. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13552. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13553. }
  13554. _this.info.render.calls ++;
  13555. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13556. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13557. // render lines
  13558. } else if ( object instanceof THREE.Line ) {
  13559. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13560. setLineWidth( material.linewidth );
  13561. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  13562. _this.info.render.calls ++;
  13563. // render particles
  13564. } else if ( object instanceof THREE.PointCloud ) {
  13565. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13566. _this.info.render.calls ++;
  13567. _this.info.render.points += geometryGroup.__webglParticleCount;
  13568. }
  13569. };
  13570. function initAttributes() {
  13571. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13572. _newAttributes[ i ] = 0;
  13573. }
  13574. }
  13575. function enableAttribute( attribute ) {
  13576. _newAttributes[ attribute ] = 1;
  13577. if ( _enabledAttributes[ attribute ] === 0 ) {
  13578. _gl.enableVertexAttribArray( attribute );
  13579. _enabledAttributes[ attribute ] = 1;
  13580. }
  13581. }
  13582. function disableUnusedAttributes() {
  13583. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13584. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13585. _gl.disableVertexAttribArray( i );
  13586. _enabledAttributes[ i ] = 0;
  13587. }
  13588. }
  13589. }
  13590. function setupMorphTargets ( material, geometryGroup, object ) {
  13591. // set base
  13592. var attributes = material.program.attributes;
  13593. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13594. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13595. enableAttribute( attributes.position );
  13596. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13597. } else if ( attributes.position >= 0 ) {
  13598. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13599. enableAttribute( attributes.position );
  13600. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13601. }
  13602. if ( object.morphTargetForcedOrder.length ) {
  13603. // set forced order
  13604. var m = 0;
  13605. var order = object.morphTargetForcedOrder;
  13606. var influences = object.morphTargetInfluences;
  13607. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13608. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13609. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13610. enableAttribute( attributes[ "morphTarget" + m ] );
  13611. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13612. }
  13613. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13614. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13615. enableAttribute( attributes[ "morphNormal" + m ] );
  13616. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13617. }
  13618. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13619. m ++;
  13620. }
  13621. } else {
  13622. // find the most influencing
  13623. var influence, activeInfluenceIndices = [];
  13624. var influences = object.morphTargetInfluences;
  13625. var i, il = influences.length;
  13626. for ( i = 0; i < il; i ++ ) {
  13627. influence = influences[ i ];
  13628. if ( influence > 0 ) {
  13629. activeInfluenceIndices.push( [ influence, i ] );
  13630. }
  13631. }
  13632. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13633. activeInfluenceIndices.sort( numericalSort );
  13634. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13635. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13636. activeInfluenceIndices.sort( numericalSort );
  13637. } else if ( activeInfluenceIndices.length === 0 ) {
  13638. activeInfluenceIndices.push( [ 0, 0 ] );
  13639. };
  13640. var influenceIndex, m = 0;
  13641. while ( m < material.numSupportedMorphTargets ) {
  13642. if ( activeInfluenceIndices[ m ] ) {
  13643. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13644. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13645. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13646. enableAttribute( attributes[ "morphTarget" + m ] );
  13647. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13648. }
  13649. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13650. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13651. enableAttribute( attributes[ "morphNormal" + m ] );
  13652. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13653. }
  13654. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13655. } else {
  13656. /*
  13657. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13658. if ( material.morphNormals ) {
  13659. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13660. }
  13661. */
  13662. object.__webglMorphTargetInfluences[ m ] = 0;
  13663. }
  13664. m ++;
  13665. }
  13666. }
  13667. // load updated influences uniform
  13668. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13669. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13670. }
  13671. };
  13672. // Sorting
  13673. function painterSortStable ( a, b ) {
  13674. if ( a.z !== b.z ) {
  13675. return b.z - a.z;
  13676. } else {
  13677. return a.id - b.id;
  13678. }
  13679. };
  13680. function numericalSort ( a, b ) {
  13681. return b[ 0 ] - a[ 0 ];
  13682. };
  13683. // Rendering
  13684. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13685. if ( camera instanceof THREE.Camera === false ) {
  13686. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13687. return;
  13688. }
  13689. var i, il,
  13690. webglObject, object,
  13691. renderList,
  13692. lights = scene.__lights,
  13693. fog = scene.fog;
  13694. // reset caching for this frame
  13695. _currentMaterialId = -1;
  13696. _lightsNeedUpdate = true;
  13697. // update scene graph
  13698. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13699. // update camera matrices and frustum
  13700. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13701. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13702. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13703. _frustum.setFromMatrix( _projScreenMatrix );
  13704. // update WebGL objects
  13705. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13706. // custom render plugins (pre pass)
  13707. renderPlugins( this.renderPluginsPre, scene, camera );
  13708. //
  13709. _this.info.render.calls = 0;
  13710. _this.info.render.vertices = 0;
  13711. _this.info.render.faces = 0;
  13712. _this.info.render.points = 0;
  13713. this.setRenderTarget( renderTarget );
  13714. if ( this.autoClear || forceClear ) {
  13715. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13716. }
  13717. // set matrices for regular objects (frustum culled)
  13718. renderList = scene.__webglObjects;
  13719. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13720. webglObject = renderList[ i ];
  13721. object = webglObject.object;
  13722. webglObject.id = i;
  13723. webglObject.render = false;
  13724. if ( object.visible ) {
  13725. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  13726. setupMatrices( object, camera );
  13727. unrollBufferMaterial( webglObject );
  13728. webglObject.render = true;
  13729. if ( this.sortObjects === true ) {
  13730. if ( object.renderDepth !== null ) {
  13731. webglObject.z = object.renderDepth;
  13732. } else {
  13733. _vector3.setFromMatrixPosition( object.matrixWorld );
  13734. _vector3.applyProjection( _projScreenMatrix );
  13735. webglObject.z = _vector3.z;
  13736. }
  13737. }
  13738. }
  13739. }
  13740. }
  13741. if ( this.sortObjects ) {
  13742. renderList.sort( painterSortStable );
  13743. }
  13744. // set matrices for immediate objects
  13745. renderList = scene.__webglObjectsImmediate;
  13746. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13747. webglObject = renderList[ i ];
  13748. object = webglObject.object;
  13749. if ( object.visible ) {
  13750. setupMatrices( object, camera );
  13751. unrollImmediateBufferMaterial( webglObject );
  13752. }
  13753. }
  13754. if ( scene.overrideMaterial ) {
  13755. var material = scene.overrideMaterial;
  13756. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13757. this.setDepthTest( material.depthTest );
  13758. this.setDepthWrite( material.depthWrite );
  13759. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13760. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13761. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13762. } else {
  13763. var material = null;
  13764. // opaque pass (front-to-back order)
  13765. this.setBlending( THREE.NoBlending );
  13766. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13767. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13768. // transparent pass (back-to-front order)
  13769. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13770. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13771. }
  13772. // custom render plugins (post pass)
  13773. renderPlugins( this.renderPluginsPost, scene, camera );
  13774. // Generate mipmap if we're using any kind of mipmap filtering
  13775. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13776. updateRenderTargetMipmap( renderTarget );
  13777. }
  13778. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13779. this.setDepthTest( true );
  13780. this.setDepthWrite( true );
  13781. // _gl.finish();
  13782. };
  13783. function renderPlugins( plugins, scene, camera ) {
  13784. if ( ! plugins.length ) return;
  13785. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13786. // reset state for plugin (to start from clean slate)
  13787. _currentProgram = null;
  13788. _currentCamera = null;
  13789. _oldBlending = -1;
  13790. _oldDepthTest = -1;
  13791. _oldDepthWrite = -1;
  13792. _oldDoubleSided = -1;
  13793. _oldFlipSided = -1;
  13794. _currentGeometryGroupHash = -1;
  13795. _currentMaterialId = -1;
  13796. _lightsNeedUpdate = true;
  13797. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13798. // reset state after plugin (anything could have changed)
  13799. _currentProgram = null;
  13800. _currentCamera = null;
  13801. _oldBlending = -1;
  13802. _oldDepthTest = -1;
  13803. _oldDepthWrite = -1;
  13804. _oldDoubleSided = -1;
  13805. _oldFlipSided = -1;
  13806. _currentGeometryGroupHash = -1;
  13807. _currentMaterialId = -1;
  13808. _lightsNeedUpdate = true;
  13809. }
  13810. };
  13811. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13812. var webglObject, object, buffer, material, start, end, delta;
  13813. if ( reverse ) {
  13814. start = renderList.length - 1;
  13815. end = -1;
  13816. delta = -1;
  13817. } else {
  13818. start = 0;
  13819. end = renderList.length;
  13820. delta = 1;
  13821. }
  13822. for ( var i = start; i !== end; i += delta ) {
  13823. webglObject = renderList[ i ];
  13824. if ( webglObject.render ) {
  13825. object = webglObject.object;
  13826. buffer = webglObject.buffer;
  13827. if ( overrideMaterial ) {
  13828. material = overrideMaterial;
  13829. } else {
  13830. material = webglObject[ materialType ];
  13831. if ( ! material ) continue;
  13832. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13833. _this.setDepthTest( material.depthTest );
  13834. _this.setDepthWrite( material.depthWrite );
  13835. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13836. }
  13837. _this.setMaterialFaces( material );
  13838. if ( buffer instanceof THREE.BufferGeometry ) {
  13839. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13840. } else {
  13841. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13842. }
  13843. }
  13844. }
  13845. };
  13846. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13847. var webglObject, object, material, program;
  13848. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13849. webglObject = renderList[ i ];
  13850. object = webglObject.object;
  13851. if ( object.visible ) {
  13852. if ( overrideMaterial ) {
  13853. material = overrideMaterial;
  13854. } else {
  13855. material = webglObject[ materialType ];
  13856. if ( ! material ) continue;
  13857. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13858. _this.setDepthTest( material.depthTest );
  13859. _this.setDepthWrite( material.depthWrite );
  13860. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13861. }
  13862. _this.renderImmediateObject( camera, lights, fog, material, object );
  13863. }
  13864. }
  13865. };
  13866. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13867. var program = setProgram( camera, lights, fog, material, object );
  13868. _currentGeometryGroupHash = -1;
  13869. _this.setMaterialFaces( material );
  13870. if ( object.immediateRenderCallback ) {
  13871. object.immediateRenderCallback( program, _gl, _frustum );
  13872. } else {
  13873. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13874. }
  13875. };
  13876. function unrollImmediateBufferMaterial ( globject ) {
  13877. var object = globject.object,
  13878. material = object.material;
  13879. if ( material.transparent ) {
  13880. globject.transparent = material;
  13881. globject.opaque = null;
  13882. } else {
  13883. globject.opaque = material;
  13884. globject.transparent = null;
  13885. }
  13886. };
  13887. function unrollBufferMaterial ( globject ) {
  13888. var object = globject.object;
  13889. var buffer = globject.buffer;
  13890. var geometry = object.geometry;
  13891. var material = object.material;
  13892. if ( material instanceof THREE.MeshFaceMaterial ) {
  13893. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  13894. material = material.materials[ materialIndex ];
  13895. if ( material.transparent ) {
  13896. globject.transparent = material;
  13897. globject.opaque = null;
  13898. } else {
  13899. globject.opaque = material;
  13900. globject.transparent = null;
  13901. }
  13902. } else {
  13903. if ( material ) {
  13904. if ( material.transparent ) {
  13905. globject.transparent = material;
  13906. globject.opaque = null;
  13907. } else {
  13908. globject.opaque = material;
  13909. globject.transparent = null;
  13910. }
  13911. }
  13912. }
  13913. };
  13914. // Objects refresh
  13915. this.initWebGLObjects = function ( scene ) {
  13916. if ( !scene.__webglObjects ) {
  13917. scene.__webglObjects = [];
  13918. scene.__webglObjectsImmediate = [];
  13919. scene.__webglSprites = [];
  13920. scene.__webglFlares = [];
  13921. }
  13922. while ( scene.__objectsAdded.length ) {
  13923. addObject( scene.__objectsAdded[ 0 ], scene );
  13924. scene.__objectsAdded.splice( 0, 1 );
  13925. }
  13926. while ( scene.__objectsRemoved.length ) {
  13927. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13928. scene.__objectsRemoved.splice( 0, 1 );
  13929. }
  13930. // update must be called after objects adding / removal
  13931. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13932. var object = scene.__webglObjects[ o ].object;
  13933. // TODO: Remove this hack (WebGLRenderer refactoring)
  13934. if ( object.__webglInit === undefined ) {
  13935. if ( object.__webglActive !== undefined ) {
  13936. removeObject( object, scene );
  13937. }
  13938. addObject( object, scene );
  13939. }
  13940. updateObject( object );
  13941. }
  13942. };
  13943. // Objects adding
  13944. function addObject( object, scene ) {
  13945. var g, geometry, material, geometryGroup;
  13946. if ( object.__webglInit === undefined ) {
  13947. object.__webglInit = true;
  13948. object._modelViewMatrix = new THREE.Matrix4();
  13949. object._normalMatrix = new THREE.Matrix3();
  13950. geometry = object.geometry;
  13951. if ( geometry === undefined ) {
  13952. // ImmediateRenderObject
  13953. } else if ( geometry.__webglInit === undefined ) {
  13954. geometry.__webglInit = true;
  13955. geometry.addEventListener( 'dispose', onGeometryDispose );
  13956. if ( geometry instanceof THREE.BufferGeometry ) {
  13957. initDirectBuffers( geometry );
  13958. } else if ( object instanceof THREE.Mesh ) {
  13959. material = object.material;
  13960. if ( geometry.geometryGroups === undefined ) {
  13961. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  13962. }
  13963. // create separate VBOs per geometry chunk
  13964. for ( g in geometry.geometryGroups ) {
  13965. geometryGroup = geometry.geometryGroups[ g ];
  13966. // initialise VBO on the first access
  13967. if ( ! geometryGroup.__webglVertexBuffer ) {
  13968. createMeshBuffers( geometryGroup );
  13969. initMeshBuffers( geometryGroup, object );
  13970. geometry.verticesNeedUpdate = true;
  13971. geometry.morphTargetsNeedUpdate = true;
  13972. geometry.elementsNeedUpdate = true;
  13973. geometry.uvsNeedUpdate = true;
  13974. geometry.normalsNeedUpdate = true;
  13975. geometry.tangentsNeedUpdate = true;
  13976. geometry.colorsNeedUpdate = true;
  13977. }
  13978. }
  13979. } else if ( object instanceof THREE.Line ) {
  13980. if ( ! geometry.__webglVertexBuffer ) {
  13981. createLineBuffers( geometry );
  13982. initLineBuffers( geometry, object );
  13983. geometry.verticesNeedUpdate = true;
  13984. geometry.colorsNeedUpdate = true;
  13985. geometry.lineDistancesNeedUpdate = true;
  13986. }
  13987. } else if ( object instanceof THREE.PointCloud ) {
  13988. if ( ! geometry.__webglVertexBuffer ) {
  13989. createParticleBuffers( geometry );
  13990. initParticleBuffers( geometry, object );
  13991. geometry.verticesNeedUpdate = true;
  13992. geometry.colorsNeedUpdate = true;
  13993. }
  13994. }
  13995. }
  13996. }
  13997. if ( object.__webglActive === undefined ) {
  13998. if ( object instanceof THREE.Mesh ) {
  13999. geometry = object.geometry;
  14000. if ( geometry instanceof THREE.BufferGeometry ) {
  14001. addBuffer( scene.__webglObjects, geometry, object );
  14002. } else if ( geometry instanceof THREE.Geometry ) {
  14003. for ( g in geometry.geometryGroups ) {
  14004. geometryGroup = geometry.geometryGroups[ g ];
  14005. addBuffer( scene.__webglObjects, geometryGroup, object );
  14006. }
  14007. }
  14008. } else if ( object instanceof THREE.Line ||
  14009. object instanceof THREE.PointCloud ) {
  14010. geometry = object.geometry;
  14011. addBuffer( scene.__webglObjects, geometry, object );
  14012. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14013. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14014. } else if ( object instanceof THREE.Sprite ) {
  14015. scene.__webglSprites.push( object );
  14016. } else if ( object instanceof THREE.LensFlare ) {
  14017. scene.__webglFlares.push( object );
  14018. }
  14019. object.__webglActive = true;
  14020. }
  14021. };
  14022. function addBuffer( objlist, buffer, object ) {
  14023. objlist.push(
  14024. {
  14025. id: null,
  14026. buffer: buffer,
  14027. object: object,
  14028. opaque: null,
  14029. transparent: null,
  14030. z: 0
  14031. }
  14032. );
  14033. };
  14034. function addBufferImmediate( objlist, object ) {
  14035. objlist.push(
  14036. {
  14037. id: null,
  14038. object: object,
  14039. opaque: null,
  14040. transparent: null,
  14041. z: 0
  14042. }
  14043. );
  14044. };
  14045. // Objects updates
  14046. function updateObject( object ) {
  14047. var geometry = object.geometry,
  14048. geometryGroup, customAttributesDirty, material;
  14049. if ( geometry instanceof THREE.BufferGeometry ) {
  14050. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14051. } else if ( object instanceof THREE.Mesh ) {
  14052. // check all geometry groups
  14053. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14054. geometryGroup = geometry.geometryGroupsList[ i ];
  14055. material = getBufferMaterial( object, geometryGroup );
  14056. if ( geometry.buffersNeedUpdate ) {
  14057. initMeshBuffers( geometryGroup, object );
  14058. }
  14059. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14060. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14061. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14062. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14063. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14064. }
  14065. }
  14066. geometry.verticesNeedUpdate = false;
  14067. geometry.morphTargetsNeedUpdate = false;
  14068. geometry.elementsNeedUpdate = false;
  14069. geometry.uvsNeedUpdate = false;
  14070. geometry.normalsNeedUpdate = false;
  14071. geometry.colorsNeedUpdate = false;
  14072. geometry.tangentsNeedUpdate = false;
  14073. geometry.buffersNeedUpdate = false;
  14074. material.attributes && clearCustomAttributes( material );
  14075. } else if ( object instanceof THREE.Line ) {
  14076. material = getBufferMaterial( object, geometry );
  14077. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14078. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14079. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14080. }
  14081. geometry.verticesNeedUpdate = false;
  14082. geometry.colorsNeedUpdate = false;
  14083. geometry.lineDistancesNeedUpdate = false;
  14084. material.attributes && clearCustomAttributes( material );
  14085. } else if ( object instanceof THREE.PointCloud ) {
  14086. material = getBufferMaterial( object, geometry );
  14087. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14088. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14089. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14090. }
  14091. geometry.verticesNeedUpdate = false;
  14092. geometry.colorsNeedUpdate = false;
  14093. material.attributes && clearCustomAttributes( material );
  14094. }
  14095. };
  14096. // Objects updates - custom attributes check
  14097. function areCustomAttributesDirty( material ) {
  14098. for ( var a in material.attributes ) {
  14099. if ( material.attributes[ a ].needsUpdate ) return true;
  14100. }
  14101. return false;
  14102. };
  14103. function clearCustomAttributes( material ) {
  14104. for ( var a in material.attributes ) {
  14105. material.attributes[ a ].needsUpdate = false;
  14106. }
  14107. };
  14108. // Objects removal
  14109. function removeObject( object, scene ) {
  14110. if ( object instanceof THREE.Mesh ||
  14111. object instanceof THREE.PointCloud ||
  14112. object instanceof THREE.Line ) {
  14113. removeInstances( scene.__webglObjects, object );
  14114. } else if ( object instanceof THREE.Sprite ) {
  14115. removeInstancesDirect( scene.__webglSprites, object );
  14116. } else if ( object instanceof THREE.LensFlare ) {
  14117. removeInstancesDirect( scene.__webglFlares, object );
  14118. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14119. removeInstances( scene.__webglObjectsImmediate, object );
  14120. }
  14121. delete object.__webglActive;
  14122. };
  14123. function removeInstances( objlist, object ) {
  14124. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14125. if ( objlist[ o ].object === object ) {
  14126. objlist.splice( o, 1 );
  14127. }
  14128. }
  14129. };
  14130. function removeInstancesDirect( objlist, object ) {
  14131. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14132. if ( objlist[ o ] === object ) {
  14133. objlist.splice( o, 1 );
  14134. }
  14135. }
  14136. };
  14137. // Materials
  14138. this.initMaterial = function ( material, lights, fog, object ) {
  14139. material.addEventListener( 'dispose', onMaterialDispose );
  14140. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14141. if ( material instanceof THREE.MeshDepthMaterial ) {
  14142. shaderID = 'depth';
  14143. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14144. shaderID = 'normal';
  14145. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14146. shaderID = 'basic';
  14147. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14148. shaderID = 'lambert';
  14149. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14150. shaderID = 'phong';
  14151. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14152. shaderID = 'basic';
  14153. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14154. shaderID = 'dashed';
  14155. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14156. shaderID = 'particle_basic';
  14157. }
  14158. if ( shaderID ) {
  14159. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14160. }
  14161. // heuristics to create shader parameters according to lights in the scene
  14162. // (not to blow over maxLights budget)
  14163. maxLightCount = allocateLights( lights );
  14164. maxShadows = allocateShadows( lights );
  14165. maxBones = allocateBones( object );
  14166. parameters = {
  14167. precision: _precision,
  14168. supportsVertexTextures: _supportsVertexTextures,
  14169. map: !!material.map,
  14170. envMap: !!material.envMap,
  14171. lightMap: !!material.lightMap,
  14172. bumpMap: !!material.bumpMap,
  14173. normalMap: !!material.normalMap,
  14174. specularMap: !!material.specularMap,
  14175. vertexColors: material.vertexColors,
  14176. fog: fog,
  14177. useFog: material.fog,
  14178. fogExp: fog instanceof THREE.FogExp2,
  14179. sizeAttenuation: material.sizeAttenuation,
  14180. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14181. skinning: material.skinning,
  14182. maxBones: maxBones,
  14183. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14184. morphTargets: material.morphTargets,
  14185. morphNormals: material.morphNormals,
  14186. maxMorphTargets: this.maxMorphTargets,
  14187. maxMorphNormals: this.maxMorphNormals,
  14188. maxDirLights: maxLightCount.directional,
  14189. maxPointLights: maxLightCount.point,
  14190. maxSpotLights: maxLightCount.spot,
  14191. maxHemiLights: maxLightCount.hemi,
  14192. maxShadows: maxShadows,
  14193. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14194. shadowMapType: this.shadowMapType,
  14195. shadowMapDebug: this.shadowMapDebug,
  14196. shadowMapCascade: this.shadowMapCascade,
  14197. alphaTest: material.alphaTest,
  14198. metal: material.metal,
  14199. wrapAround: material.wrapAround,
  14200. doubleSided: material.side === THREE.DoubleSide,
  14201. flipSided: material.side === THREE.BackSide
  14202. };
  14203. // Generate code
  14204. var chunks = [];
  14205. if ( shaderID ) {
  14206. chunks.push( shaderID );
  14207. } else {
  14208. chunks.push( material.fragmentShader );
  14209. chunks.push( material.vertexShader );
  14210. }
  14211. for ( var d in material.defines ) {
  14212. chunks.push( d );
  14213. chunks.push( material.defines[ d ] );
  14214. }
  14215. for ( var p in parameters ) {
  14216. chunks.push( p );
  14217. chunks.push( parameters[ p ] );
  14218. }
  14219. var code = chunks.join();
  14220. var program;
  14221. // Check if code has been already compiled
  14222. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14223. var programInfo = _programs[ p ];
  14224. if ( programInfo.code === code ) {
  14225. program = programInfo;
  14226. program.usedTimes ++;
  14227. break;
  14228. }
  14229. }
  14230. if ( program === undefined ) {
  14231. program = new THREE.WebGLProgram( this, code, material, parameters );
  14232. _programs.push( program );
  14233. _this.info.memory.programs = _programs.length;
  14234. }
  14235. material.program = program;
  14236. var attributes = material.program.attributes;
  14237. if ( material.morphTargets ) {
  14238. material.numSupportedMorphTargets = 0;
  14239. var id, base = "morphTarget";
  14240. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14241. id = base + i;
  14242. if ( attributes[ id ] >= 0 ) {
  14243. material.numSupportedMorphTargets ++;
  14244. }
  14245. }
  14246. }
  14247. if ( material.morphNormals ) {
  14248. material.numSupportedMorphNormals = 0;
  14249. var id, base = "morphNormal";
  14250. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14251. id = base + i;
  14252. if ( attributes[ id ] >= 0 ) {
  14253. material.numSupportedMorphNormals ++;
  14254. }
  14255. }
  14256. }
  14257. material.uniformsList = [];
  14258. for ( u in material.uniforms ) {
  14259. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14260. }
  14261. };
  14262. function setMaterialShaders( material, shaders ) {
  14263. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14264. material.vertexShader = shaders.vertexShader;
  14265. material.fragmentShader = shaders.fragmentShader;
  14266. };
  14267. function setProgram( camera, lights, fog, material, object ) {
  14268. _usedTextureUnits = 0;
  14269. if ( material.needsUpdate ) {
  14270. if ( material.program ) deallocateMaterial( material );
  14271. _this.initMaterial( material, lights, fog, object );
  14272. material.needsUpdate = false;
  14273. }
  14274. if ( material.morphTargets ) {
  14275. if ( ! object.__webglMorphTargetInfluences ) {
  14276. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14277. }
  14278. }
  14279. var refreshMaterial = false;
  14280. var program = material.program,
  14281. p_uniforms = program.uniforms,
  14282. m_uniforms = material.uniforms;
  14283. if ( program.id !== _currentProgram ) {
  14284. _gl.useProgram( program.program );
  14285. _currentProgram = program.id;
  14286. refreshMaterial = true;
  14287. }
  14288. if ( material.id !== _currentMaterialId ) {
  14289. _currentMaterialId = material.id;
  14290. refreshMaterial = true;
  14291. }
  14292. if ( refreshMaterial || camera !== _currentCamera ) {
  14293. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14294. if ( _logarithmicDepthBuffer ) {
  14295. _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14296. }
  14297. if ( camera !== _currentCamera ) _currentCamera = camera;
  14298. }
  14299. // skinning uniforms must be set even if material didn't change
  14300. // auto-setting of texture unit for bone texture must go before other textures
  14301. // not sure why, but otherwise weird things happen
  14302. if ( material.skinning ) {
  14303. if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) {
  14304. if ( p_uniforms.boneTexture !== null ) {
  14305. var textureUnit = getTextureUnit();
  14306. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14307. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  14308. }
  14309. if ( p_uniforms.boneTextureWidth !== null ) {
  14310. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  14311. }
  14312. if ( p_uniforms.boneTextureHeight !== null ) {
  14313. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  14314. }
  14315. } else {
  14316. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14317. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  14318. }
  14319. }
  14320. }
  14321. if ( refreshMaterial ) {
  14322. // refresh uniforms common to several materials
  14323. if ( fog && material.fog ) {
  14324. refreshUniformsFog( m_uniforms, fog );
  14325. }
  14326. if ( material instanceof THREE.MeshPhongMaterial ||
  14327. material instanceof THREE.MeshLambertMaterial ||
  14328. material.lights ) {
  14329. if ( _lightsNeedUpdate ) {
  14330. setupLights( program, lights );
  14331. _lightsNeedUpdate = false;
  14332. }
  14333. refreshUniformsLights( m_uniforms, _lights );
  14334. }
  14335. if ( material instanceof THREE.MeshBasicMaterial ||
  14336. material instanceof THREE.MeshLambertMaterial ||
  14337. material instanceof THREE.MeshPhongMaterial ) {
  14338. refreshUniformsCommon( m_uniforms, material );
  14339. }
  14340. // refresh single material specific uniforms
  14341. if ( material instanceof THREE.LineBasicMaterial ) {
  14342. refreshUniformsLine( m_uniforms, material );
  14343. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14344. refreshUniformsLine( m_uniforms, material );
  14345. refreshUniformsDash( m_uniforms, material );
  14346. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14347. refreshUniformsParticle( m_uniforms, material );
  14348. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14349. refreshUniformsPhong( m_uniforms, material );
  14350. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14351. refreshUniformsLambert( m_uniforms, material );
  14352. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14353. m_uniforms.mNear.value = camera.near;
  14354. m_uniforms.mFar.value = camera.far;
  14355. m_uniforms.opacity.value = material.opacity;
  14356. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14357. m_uniforms.opacity.value = material.opacity;
  14358. }
  14359. if ( object.receiveShadow && ! material._shadowPass ) {
  14360. refreshUniformsShadow( m_uniforms, lights );
  14361. }
  14362. // load common uniforms
  14363. loadUniformsGeneric( program, material.uniformsList );
  14364. // load material specific uniforms
  14365. // (shader material also gets them for the sake of genericity)
  14366. if ( material instanceof THREE.ShaderMaterial ||
  14367. material instanceof THREE.MeshPhongMaterial ||
  14368. material.envMap ) {
  14369. if ( p_uniforms.cameraPosition !== null ) {
  14370. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14371. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14372. }
  14373. }
  14374. if ( material instanceof THREE.MeshPhongMaterial ||
  14375. material instanceof THREE.MeshLambertMaterial ||
  14376. material instanceof THREE.ShaderMaterial ||
  14377. material.skinning ) {
  14378. if ( p_uniforms.viewMatrix !== null ) {
  14379. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14380. }
  14381. }
  14382. }
  14383. loadUniformsMatrices( p_uniforms, object );
  14384. if ( p_uniforms.modelMatrix !== null ) {
  14385. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14386. }
  14387. return program;
  14388. };
  14389. // Uniforms (refresh uniforms objects)
  14390. function refreshUniformsCommon ( uniforms, material ) {
  14391. uniforms.opacity.value = material.opacity;
  14392. if ( _this.gammaInput ) {
  14393. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14394. } else {
  14395. uniforms.diffuse.value = material.color;
  14396. }
  14397. uniforms.map.value = material.map;
  14398. uniforms.lightMap.value = material.lightMap;
  14399. uniforms.specularMap.value = material.specularMap;
  14400. if ( material.bumpMap ) {
  14401. uniforms.bumpMap.value = material.bumpMap;
  14402. uniforms.bumpScale.value = material.bumpScale;
  14403. }
  14404. if ( material.normalMap ) {
  14405. uniforms.normalMap.value = material.normalMap;
  14406. uniforms.normalScale.value.copy( material.normalScale );
  14407. }
  14408. // uv repeat and offset setting priorities
  14409. // 1. color map
  14410. // 2. specular map
  14411. // 3. normal map
  14412. // 4. bump map
  14413. var uvScaleMap;
  14414. if ( material.map ) {
  14415. uvScaleMap = material.map;
  14416. } else if ( material.specularMap ) {
  14417. uvScaleMap = material.specularMap;
  14418. } else if ( material.normalMap ) {
  14419. uvScaleMap = material.normalMap;
  14420. } else if ( material.bumpMap ) {
  14421. uvScaleMap = material.bumpMap;
  14422. }
  14423. if ( uvScaleMap !== undefined ) {
  14424. var offset = uvScaleMap.offset;
  14425. var repeat = uvScaleMap.repeat;
  14426. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14427. }
  14428. uniforms.envMap.value = material.envMap;
  14429. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14430. if ( _this.gammaInput ) {
  14431. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14432. uniforms.reflectivity.value = material.reflectivity;
  14433. } else {
  14434. uniforms.reflectivity.value = material.reflectivity;
  14435. }
  14436. uniforms.refractionRatio.value = material.refractionRatio;
  14437. uniforms.combine.value = material.combine;
  14438. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14439. };
  14440. function refreshUniformsLine ( uniforms, material ) {
  14441. uniforms.diffuse.value = material.color;
  14442. uniforms.opacity.value = material.opacity;
  14443. };
  14444. function refreshUniformsDash ( uniforms, material ) {
  14445. uniforms.dashSize.value = material.dashSize;
  14446. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14447. uniforms.scale.value = material.scale;
  14448. };
  14449. function refreshUniformsParticle ( uniforms, material ) {
  14450. uniforms.psColor.value = material.color;
  14451. uniforms.opacity.value = material.opacity;
  14452. uniforms.size.value = material.size;
  14453. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14454. uniforms.map.value = material.map;
  14455. };
  14456. function refreshUniformsFog ( uniforms, fog ) {
  14457. uniforms.fogColor.value = fog.color;
  14458. if ( fog instanceof THREE.Fog ) {
  14459. uniforms.fogNear.value = fog.near;
  14460. uniforms.fogFar.value = fog.far;
  14461. } else if ( fog instanceof THREE.FogExp2 ) {
  14462. uniforms.fogDensity.value = fog.density;
  14463. }
  14464. };
  14465. function refreshUniformsPhong ( uniforms, material ) {
  14466. uniforms.shininess.value = material.shininess;
  14467. if ( _this.gammaInput ) {
  14468. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14469. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14470. uniforms.specular.value.copyGammaToLinear( material.specular );
  14471. } else {
  14472. uniforms.ambient.value = material.ambient;
  14473. uniforms.emissive.value = material.emissive;
  14474. uniforms.specular.value = material.specular;
  14475. }
  14476. if ( material.wrapAround ) {
  14477. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14478. }
  14479. };
  14480. function refreshUniformsLambert ( uniforms, material ) {
  14481. if ( _this.gammaInput ) {
  14482. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14483. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14484. } else {
  14485. uniforms.ambient.value = material.ambient;
  14486. uniforms.emissive.value = material.emissive;
  14487. }
  14488. if ( material.wrapAround ) {
  14489. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14490. }
  14491. };
  14492. function refreshUniformsLights ( uniforms, lights ) {
  14493. uniforms.ambientLightColor.value = lights.ambient;
  14494. uniforms.directionalLightColor.value = lights.directional.colors;
  14495. uniforms.directionalLightDirection.value = lights.directional.positions;
  14496. uniforms.pointLightColor.value = lights.point.colors;
  14497. uniforms.pointLightPosition.value = lights.point.positions;
  14498. uniforms.pointLightDistance.value = lights.point.distances;
  14499. uniforms.spotLightColor.value = lights.spot.colors;
  14500. uniforms.spotLightPosition.value = lights.spot.positions;
  14501. uniforms.spotLightDistance.value = lights.spot.distances;
  14502. uniforms.spotLightDirection.value = lights.spot.directions;
  14503. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14504. uniforms.spotLightExponent.value = lights.spot.exponents;
  14505. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14506. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14507. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14508. };
  14509. function refreshUniformsShadow ( uniforms, lights ) {
  14510. if ( uniforms.shadowMatrix ) {
  14511. var j = 0;
  14512. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14513. var light = lights[ i ];
  14514. if ( ! light.castShadow ) continue;
  14515. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14516. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14517. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14518. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14519. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14520. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14521. j ++;
  14522. }
  14523. }
  14524. }
  14525. };
  14526. // Uniforms (load to GPU)
  14527. function loadUniformsMatrices ( uniforms, object ) {
  14528. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14529. if ( uniforms.normalMatrix ) {
  14530. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14531. }
  14532. };
  14533. function getTextureUnit() {
  14534. var textureUnit = _usedTextureUnits;
  14535. if ( textureUnit >= _maxTextures ) {
  14536. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14537. }
  14538. _usedTextureUnits += 1;
  14539. return textureUnit;
  14540. };
  14541. function loadUniformsGeneric ( program, uniforms ) {
  14542. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14543. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14544. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14545. if ( !location ) continue;
  14546. uniform = uniforms[ j ][ 0 ];
  14547. type = uniform.type;
  14548. value = uniform.value;
  14549. if ( type === "i" ) { // single integer
  14550. _gl.uniform1i( location, value );
  14551. } else if ( type === "f" ) { // single float
  14552. _gl.uniform1f( location, value );
  14553. } else if ( type === "v2" ) { // single THREE.Vector2
  14554. _gl.uniform2f( location, value.x, value.y );
  14555. } else if ( type === "v3" ) { // single THREE.Vector3
  14556. _gl.uniform3f( location, value.x, value.y, value.z );
  14557. } else if ( type === "v4" ) { // single THREE.Vector4
  14558. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14559. } else if ( type === "c" ) { // single THREE.Color
  14560. _gl.uniform3f( location, value.r, value.g, value.b );
  14561. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14562. _gl.uniform1iv( location, value );
  14563. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14564. _gl.uniform3iv( location, value );
  14565. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14566. _gl.uniform1fv( location, value );
  14567. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14568. _gl.uniform3fv( location, value );
  14569. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14570. if ( uniform._array === undefined ) {
  14571. uniform._array = new Float32Array( 2 * value.length );
  14572. }
  14573. for ( i = 0, il = value.length; i < il; i ++ ) {
  14574. offset = i * 2;
  14575. uniform._array[ offset ] = value[ i ].x;
  14576. uniform._array[ offset + 1 ] = value[ i ].y;
  14577. }
  14578. _gl.uniform2fv( location, uniform._array );
  14579. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14580. if ( uniform._array === undefined ) {
  14581. uniform._array = new Float32Array( 3 * value.length );
  14582. }
  14583. for ( i = 0, il = value.length; i < il; i ++ ) {
  14584. offset = i * 3;
  14585. uniform._array[ offset ] = value[ i ].x;
  14586. uniform._array[ offset + 1 ] = value[ i ].y;
  14587. uniform._array[ offset + 2 ] = value[ i ].z;
  14588. }
  14589. _gl.uniform3fv( location, uniform._array );
  14590. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14591. if ( uniform._array === undefined ) {
  14592. uniform._array = new Float32Array( 4 * value.length );
  14593. }
  14594. for ( i = 0, il = value.length; i < il; i ++ ) {
  14595. offset = i * 4;
  14596. uniform._array[ offset ] = value[ i ].x;
  14597. uniform._array[ offset + 1 ] = value[ i ].y;
  14598. uniform._array[ offset + 2 ] = value[ i ].z;
  14599. uniform._array[ offset + 3 ] = value[ i ].w;
  14600. }
  14601. _gl.uniform4fv( location, uniform._array );
  14602. } else if ( type === "m3") { // single THREE.Matrix3
  14603. _gl.uniformMatrix3fv( location, false, value.elements );
  14604. } else if ( type === "m3v" ) { // array of THREE.Matrix3
  14605. if ( uniform._array === undefined ) {
  14606. uniform._array = new Float32Array( 9 * value.length );
  14607. }
  14608. for ( i = 0, il = value.length; i < il; i ++ ) {
  14609. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  14610. }
  14611. _gl.uniformMatrix3fv( location, false, uniform._array );
  14612. } else if ( type === "m4") { // single THREE.Matrix4
  14613. _gl.uniformMatrix4fv( location, false, value.elements );
  14614. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14615. if ( uniform._array === undefined ) {
  14616. uniform._array = new Float32Array( 16 * value.length );
  14617. }
  14618. for ( i = 0, il = value.length; i < il; i ++ ) {
  14619. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14620. }
  14621. _gl.uniformMatrix4fv( location, false, uniform._array );
  14622. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14623. texture = value;
  14624. textureUnit = getTextureUnit();
  14625. _gl.uniform1i( location, textureUnit );
  14626. if ( !texture ) continue;
  14627. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14628. setCubeTexture( texture, textureUnit );
  14629. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14630. setCubeTextureDynamic( texture, textureUnit );
  14631. } else {
  14632. _this.setTexture( texture, textureUnit );
  14633. }
  14634. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14635. if ( uniform._array === undefined ) {
  14636. uniform._array = [];
  14637. }
  14638. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14639. uniform._array[ i ] = getTextureUnit();
  14640. }
  14641. _gl.uniform1iv( location, uniform._array );
  14642. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14643. texture = uniform.value[ i ];
  14644. textureUnit = uniform._array[ i ];
  14645. if ( !texture ) continue;
  14646. _this.setTexture( texture, textureUnit );
  14647. }
  14648. } else {
  14649. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14650. }
  14651. }
  14652. };
  14653. function setupMatrices ( object, camera ) {
  14654. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14655. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14656. };
  14657. //
  14658. function setColorGamma( array, offset, color, intensitySq ) {
  14659. array[ offset ] = color.r * color.r * intensitySq;
  14660. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14661. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14662. };
  14663. function setColorLinear( array, offset, color, intensity ) {
  14664. array[ offset ] = color.r * intensity;
  14665. array[ offset + 1 ] = color.g * intensity;
  14666. array[ offset + 2 ] = color.b * intensity;
  14667. };
  14668. function setupLights ( program, lights ) {
  14669. var l, ll, light, n,
  14670. r = 0, g = 0, b = 0,
  14671. color, skyColor, groundColor,
  14672. intensity, intensitySq,
  14673. position,
  14674. distance,
  14675. zlights = _lights,
  14676. dirColors = zlights.directional.colors,
  14677. dirPositions = zlights.directional.positions,
  14678. pointColors = zlights.point.colors,
  14679. pointPositions = zlights.point.positions,
  14680. pointDistances = zlights.point.distances,
  14681. spotColors = zlights.spot.colors,
  14682. spotPositions = zlights.spot.positions,
  14683. spotDistances = zlights.spot.distances,
  14684. spotDirections = zlights.spot.directions,
  14685. spotAnglesCos = zlights.spot.anglesCos,
  14686. spotExponents = zlights.spot.exponents,
  14687. hemiSkyColors = zlights.hemi.skyColors,
  14688. hemiGroundColors = zlights.hemi.groundColors,
  14689. hemiPositions = zlights.hemi.positions,
  14690. dirLength = 0,
  14691. pointLength = 0,
  14692. spotLength = 0,
  14693. hemiLength = 0,
  14694. dirCount = 0,
  14695. pointCount = 0,
  14696. spotCount = 0,
  14697. hemiCount = 0,
  14698. dirOffset = 0,
  14699. pointOffset = 0,
  14700. spotOffset = 0,
  14701. hemiOffset = 0;
  14702. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14703. light = lights[ l ];
  14704. if ( light.onlyShadow ) continue;
  14705. color = light.color;
  14706. intensity = light.intensity;
  14707. distance = light.distance;
  14708. if ( light instanceof THREE.AmbientLight ) {
  14709. if ( ! light.visible ) continue;
  14710. if ( _this.gammaInput ) {
  14711. r += color.r * color.r;
  14712. g += color.g * color.g;
  14713. b += color.b * color.b;
  14714. } else {
  14715. r += color.r;
  14716. g += color.g;
  14717. b += color.b;
  14718. }
  14719. } else if ( light instanceof THREE.DirectionalLight ) {
  14720. dirCount += 1;
  14721. if ( ! light.visible ) continue;
  14722. _direction.setFromMatrixPosition( light.matrixWorld );
  14723. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14724. _direction.sub( _vector3 );
  14725. _direction.normalize();
  14726. // skip lights with undefined direction
  14727. // these create troubles in OpenGL (making pixel black)
  14728. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14729. dirOffset = dirLength * 3;
  14730. dirPositions[ dirOffset ] = _direction.x;
  14731. dirPositions[ dirOffset + 1 ] = _direction.y;
  14732. dirPositions[ dirOffset + 2 ] = _direction.z;
  14733. if ( _this.gammaInput ) {
  14734. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14735. } else {
  14736. setColorLinear( dirColors, dirOffset, color, intensity );
  14737. }
  14738. dirLength += 1;
  14739. } else if ( light instanceof THREE.PointLight ) {
  14740. pointCount += 1;
  14741. if ( ! light.visible ) continue;
  14742. pointOffset = pointLength * 3;
  14743. if ( _this.gammaInput ) {
  14744. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14745. } else {
  14746. setColorLinear( pointColors, pointOffset, color, intensity );
  14747. }
  14748. _vector3.setFromMatrixPosition( light.matrixWorld );
  14749. pointPositions[ pointOffset ] = _vector3.x;
  14750. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14751. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14752. pointDistances[ pointLength ] = distance;
  14753. pointLength += 1;
  14754. } else if ( light instanceof THREE.SpotLight ) {
  14755. spotCount += 1;
  14756. if ( ! light.visible ) continue;
  14757. spotOffset = spotLength * 3;
  14758. if ( _this.gammaInput ) {
  14759. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14760. } else {
  14761. setColorLinear( spotColors, spotOffset, color, intensity );
  14762. }
  14763. _vector3.setFromMatrixPosition( light.matrixWorld );
  14764. spotPositions[ spotOffset ] = _vector3.x;
  14765. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14766. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14767. spotDistances[ spotLength ] = distance;
  14768. _direction.copy( _vector3 );
  14769. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14770. _direction.sub( _vector3 );
  14771. _direction.normalize();
  14772. spotDirections[ spotOffset ] = _direction.x;
  14773. spotDirections[ spotOffset + 1 ] = _direction.y;
  14774. spotDirections[ spotOffset + 2 ] = _direction.z;
  14775. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14776. spotExponents[ spotLength ] = light.exponent;
  14777. spotLength += 1;
  14778. } else if ( light instanceof THREE.HemisphereLight ) {
  14779. hemiCount += 1;
  14780. if ( ! light.visible ) continue;
  14781. _direction.setFromMatrixPosition( light.matrixWorld );
  14782. _direction.normalize();
  14783. // skip lights with undefined direction
  14784. // these create troubles in OpenGL (making pixel black)
  14785. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14786. hemiOffset = hemiLength * 3;
  14787. hemiPositions[ hemiOffset ] = _direction.x;
  14788. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14789. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14790. skyColor = light.color;
  14791. groundColor = light.groundColor;
  14792. if ( _this.gammaInput ) {
  14793. intensitySq = intensity * intensity;
  14794. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14795. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14796. } else {
  14797. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14798. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14799. }
  14800. hemiLength += 1;
  14801. }
  14802. }
  14803. // null eventual remains from removed lights
  14804. // (this is to avoid if in shader)
  14805. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14806. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14807. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14808. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14809. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14810. zlights.directional.length = dirLength;
  14811. zlights.point.length = pointLength;
  14812. zlights.spot.length = spotLength;
  14813. zlights.hemi.length = hemiLength;
  14814. zlights.ambient[ 0 ] = r;
  14815. zlights.ambient[ 1 ] = g;
  14816. zlights.ambient[ 2 ] = b;
  14817. };
  14818. // GL state setting
  14819. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14820. if ( cullFace === THREE.CullFaceNone ) {
  14821. _gl.disable( _gl.CULL_FACE );
  14822. } else {
  14823. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14824. _gl.frontFace( _gl.CW );
  14825. } else {
  14826. _gl.frontFace( _gl.CCW );
  14827. }
  14828. if ( cullFace === THREE.CullFaceBack ) {
  14829. _gl.cullFace( _gl.BACK );
  14830. } else if ( cullFace === THREE.CullFaceFront ) {
  14831. _gl.cullFace( _gl.FRONT );
  14832. } else {
  14833. _gl.cullFace( _gl.FRONT_AND_BACK );
  14834. }
  14835. _gl.enable( _gl.CULL_FACE );
  14836. }
  14837. };
  14838. this.setMaterialFaces = function ( material ) {
  14839. var doubleSided = material.side === THREE.DoubleSide;
  14840. var flipSided = material.side === THREE.BackSide;
  14841. if ( _oldDoubleSided !== doubleSided ) {
  14842. if ( doubleSided ) {
  14843. _gl.disable( _gl.CULL_FACE );
  14844. } else {
  14845. _gl.enable( _gl.CULL_FACE );
  14846. }
  14847. _oldDoubleSided = doubleSided;
  14848. }
  14849. if ( _oldFlipSided !== flipSided ) {
  14850. if ( flipSided ) {
  14851. _gl.frontFace( _gl.CW );
  14852. } else {
  14853. _gl.frontFace( _gl.CCW );
  14854. }
  14855. _oldFlipSided = flipSided;
  14856. }
  14857. };
  14858. this.setDepthTest = function ( depthTest ) {
  14859. if ( _oldDepthTest !== depthTest ) {
  14860. if ( depthTest ) {
  14861. _gl.enable( _gl.DEPTH_TEST );
  14862. } else {
  14863. _gl.disable( _gl.DEPTH_TEST );
  14864. }
  14865. _oldDepthTest = depthTest;
  14866. }
  14867. };
  14868. this.setDepthWrite = function ( depthWrite ) {
  14869. if ( _oldDepthWrite !== depthWrite ) {
  14870. _gl.depthMask( depthWrite );
  14871. _oldDepthWrite = depthWrite;
  14872. }
  14873. };
  14874. function setLineWidth ( width ) {
  14875. if ( width !== _oldLineWidth ) {
  14876. _gl.lineWidth( width );
  14877. _oldLineWidth = width;
  14878. }
  14879. };
  14880. function setPolygonOffset ( polygonoffset, factor, units ) {
  14881. if ( _oldPolygonOffset !== polygonoffset ) {
  14882. if ( polygonoffset ) {
  14883. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14884. } else {
  14885. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14886. }
  14887. _oldPolygonOffset = polygonoffset;
  14888. }
  14889. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14890. _gl.polygonOffset( factor, units );
  14891. _oldPolygonOffsetFactor = factor;
  14892. _oldPolygonOffsetUnits = units;
  14893. }
  14894. };
  14895. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14896. if ( blending !== _oldBlending ) {
  14897. if ( blending === THREE.NoBlending ) {
  14898. _gl.disable( _gl.BLEND );
  14899. } else if ( blending === THREE.AdditiveBlending ) {
  14900. _gl.enable( _gl.BLEND );
  14901. _gl.blendEquation( _gl.FUNC_ADD );
  14902. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14903. } else if ( blending === THREE.SubtractiveBlending ) {
  14904. // TODO: Find blendFuncSeparate() combination
  14905. _gl.enable( _gl.BLEND );
  14906. _gl.blendEquation( _gl.FUNC_ADD );
  14907. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14908. } else if ( blending === THREE.MultiplyBlending ) {
  14909. // TODO: Find blendFuncSeparate() combination
  14910. _gl.enable( _gl.BLEND );
  14911. _gl.blendEquation( _gl.FUNC_ADD );
  14912. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14913. } else if ( blending === THREE.CustomBlending ) {
  14914. _gl.enable( _gl.BLEND );
  14915. } else {
  14916. _gl.enable( _gl.BLEND );
  14917. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14918. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14919. }
  14920. _oldBlending = blending;
  14921. }
  14922. if ( blending === THREE.CustomBlending ) {
  14923. if ( blendEquation !== _oldBlendEquation ) {
  14924. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14925. _oldBlendEquation = blendEquation;
  14926. }
  14927. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14928. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14929. _oldBlendSrc = blendSrc;
  14930. _oldBlendDst = blendDst;
  14931. }
  14932. } else {
  14933. _oldBlendEquation = null;
  14934. _oldBlendSrc = null;
  14935. _oldBlendDst = null;
  14936. }
  14937. };
  14938. // Textures
  14939. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14940. if ( isImagePowerOfTwo ) {
  14941. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14942. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14943. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14944. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14945. } else {
  14946. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14947. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14948. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14949. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14950. }
  14951. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14952. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14953. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14954. texture.__oldAnisotropy = texture.anisotropy;
  14955. }
  14956. }
  14957. };
  14958. this.setTexture = function ( texture, slot ) {
  14959. if ( texture.needsUpdate ) {
  14960. if ( ! texture.__webglInit ) {
  14961. texture.__webglInit = true;
  14962. texture.addEventListener( 'dispose', onTextureDispose );
  14963. texture.__webglTexture = _gl.createTexture();
  14964. _this.info.memory.textures ++;
  14965. }
  14966. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14967. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14968. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14969. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14970. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14971. var image = texture.image,
  14972. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  14973. glFormat = paramThreeToGL( texture.format ),
  14974. glType = paramThreeToGL( texture.type );
  14975. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14976. var mipmap, mipmaps = texture.mipmaps;
  14977. if ( texture instanceof THREE.DataTexture ) {
  14978. // use manually created mipmaps if available
  14979. // if there are no manual mipmaps
  14980. // set 0 level mipmap and then use GL to generate other mipmap levels
  14981. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14982. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14983. mipmap = mipmaps[ i ];
  14984. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14985. }
  14986. texture.generateMipmaps = false;
  14987. } else {
  14988. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14989. }
  14990. } else if ( texture instanceof THREE.CompressedTexture ) {
  14991. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14992. mipmap = mipmaps[ i ];
  14993. if ( texture.format !== THREE.RGBAFormat ) {
  14994. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14995. } else {
  14996. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14997. }
  14998. }
  14999. } else { // regular Texture (image, video, canvas)
  15000. // use manually created mipmaps if available
  15001. // if there are no manual mipmaps
  15002. // set 0 level mipmap and then use GL to generate other mipmap levels
  15003. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15004. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15005. mipmap = mipmaps[ i ];
  15006. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15007. }
  15008. texture.generateMipmaps = false;
  15009. } else {
  15010. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15011. }
  15012. }
  15013. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15014. texture.needsUpdate = false;
  15015. if ( texture.onUpdate ) texture.onUpdate();
  15016. } else {
  15017. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15018. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15019. }
  15020. };
  15021. function clampToMaxSize ( image, maxSize ) {
  15022. if ( image.width <= maxSize && image.height <= maxSize ) {
  15023. return image;
  15024. }
  15025. // Warning: Scaling through the canvas will only work with images that use
  15026. // premultiplied alpha.
  15027. var maxDimension = Math.max( image.width, image.height );
  15028. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15029. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15030. var canvas = document.createElement( 'canvas' );
  15031. canvas.width = newWidth;
  15032. canvas.height = newHeight;
  15033. var ctx = canvas.getContext( "2d" );
  15034. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15035. return canvas;
  15036. }
  15037. function setCubeTexture ( texture, slot ) {
  15038. if ( texture.image.length === 6 ) {
  15039. if ( texture.needsUpdate ) {
  15040. if ( ! texture.image.__webglTextureCube ) {
  15041. texture.addEventListener( 'dispose', onTextureDispose );
  15042. texture.image.__webglTextureCube = _gl.createTexture();
  15043. _this.info.memory.textures ++;
  15044. }
  15045. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15046. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15047. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15048. var isCompressed = texture instanceof THREE.CompressedTexture;
  15049. var cubeImage = [];
  15050. for ( var i = 0; i < 6; i ++ ) {
  15051. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15052. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15053. } else {
  15054. cubeImage[ i ] = texture.image[ i ];
  15055. }
  15056. }
  15057. var image = cubeImage[ 0 ],
  15058. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15059. glFormat = paramThreeToGL( texture.format ),
  15060. glType = paramThreeToGL( texture.type );
  15061. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15062. for ( var i = 0; i < 6; i ++ ) {
  15063. if ( !isCompressed ) {
  15064. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15065. } else {
  15066. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15067. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15068. mipmap = mipmaps[ j ];
  15069. if ( texture.format !== THREE.RGBAFormat ) {
  15070. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15071. } else {
  15072. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15073. }
  15074. }
  15075. }
  15076. }
  15077. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15078. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15079. }
  15080. texture.needsUpdate = false;
  15081. if ( texture.onUpdate ) texture.onUpdate();
  15082. } else {
  15083. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15084. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15085. }
  15086. }
  15087. };
  15088. function setCubeTextureDynamic ( texture, slot ) {
  15089. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15090. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15091. };
  15092. // Render targets
  15093. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15094. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15095. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15096. };
  15097. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15098. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15099. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15100. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15101. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15102. /* For some reason this is not working. Defaulting to RGBA4.
  15103. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15104. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15105. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15106. */
  15107. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15108. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15109. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15110. } else {
  15111. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15112. }
  15113. };
  15114. this.setRenderTarget = function ( renderTarget ) {
  15115. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15116. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15117. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15118. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15119. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15120. renderTarget.__webglTexture = _gl.createTexture();
  15121. _this.info.memory.textures ++;
  15122. // Setup texture, create render and frame buffers
  15123. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15124. glFormat = paramThreeToGL( renderTarget.format ),
  15125. glType = paramThreeToGL( renderTarget.type );
  15126. if ( isCube ) {
  15127. renderTarget.__webglFramebuffer = [];
  15128. renderTarget.__webglRenderbuffer = [];
  15129. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15130. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15131. for ( var i = 0; i < 6; i ++ ) {
  15132. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15133. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15134. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15135. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15136. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15137. }
  15138. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15139. } else {
  15140. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15141. if ( renderTarget.shareDepthFrom ) {
  15142. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15143. } else {
  15144. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15145. }
  15146. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15147. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15148. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15149. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15150. if ( renderTarget.shareDepthFrom ) {
  15151. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15152. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15153. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15154. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15155. }
  15156. } else {
  15157. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15158. }
  15159. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15160. }
  15161. // Release everything
  15162. if ( isCube ) {
  15163. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15164. } else {
  15165. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15166. }
  15167. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15168. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15169. }
  15170. var framebuffer, width, height, vx, vy;
  15171. if ( renderTarget ) {
  15172. if ( isCube ) {
  15173. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15174. } else {
  15175. framebuffer = renderTarget.__webglFramebuffer;
  15176. }
  15177. width = renderTarget.width;
  15178. height = renderTarget.height;
  15179. vx = 0;
  15180. vy = 0;
  15181. } else {
  15182. framebuffer = null;
  15183. width = _viewportWidth;
  15184. height = _viewportHeight;
  15185. vx = _viewportX;
  15186. vy = _viewportY;
  15187. }
  15188. if ( framebuffer !== _currentFramebuffer ) {
  15189. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15190. _gl.viewport( vx, vy, width, height );
  15191. _currentFramebuffer = framebuffer;
  15192. }
  15193. _currentWidth = width;
  15194. _currentHeight = height;
  15195. };
  15196. function updateRenderTargetMipmap ( renderTarget ) {
  15197. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15198. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15199. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15200. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15201. } else {
  15202. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15203. _gl.generateMipmap( _gl.TEXTURE_2D );
  15204. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15205. }
  15206. };
  15207. // Fallback filters for non-power-of-2 textures
  15208. function filterFallback ( f ) {
  15209. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15210. return _gl.NEAREST;
  15211. }
  15212. return _gl.LINEAR;
  15213. };
  15214. // Map three.js constants to WebGL constants
  15215. function paramThreeToGL ( p ) {
  15216. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15217. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15218. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15219. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15220. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15221. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15222. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15223. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15224. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15225. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15226. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15227. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15228. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15229. if ( p === THREE.ByteType ) return _gl.BYTE;
  15230. if ( p === THREE.ShortType ) return _gl.SHORT;
  15231. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15232. if ( p === THREE.IntType ) return _gl.INT;
  15233. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15234. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15235. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15236. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15237. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15238. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15239. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15240. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15241. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15242. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15243. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15244. if ( p === THREE.OneFactor ) return _gl.ONE;
  15245. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15246. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15247. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15248. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15249. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15250. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15251. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15252. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15253. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15254. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15255. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15256. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15257. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15258. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15259. }
  15260. return 0;
  15261. };
  15262. // Allocations
  15263. function allocateBones ( object ) {
  15264. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  15265. return 1024;
  15266. } else {
  15267. // default for when object is not specified
  15268. // ( for example when prebuilding shader
  15269. // to be used with multiple objects )
  15270. //
  15271. // - leave some extra space for other uniforms
  15272. // - limit here is ANGLE's 254 max uniform vectors
  15273. // (up to 54 should be safe)
  15274. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15275. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15276. var maxBones = nVertexMatrices;
  15277. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15278. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  15279. if ( maxBones < object.skeleton.bones.length ) {
  15280. console.warn( "WebGLRenderer: too many bones - " + object.skeleton.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15281. }
  15282. }
  15283. return maxBones;
  15284. }
  15285. };
  15286. function allocateLights( lights ) {
  15287. var dirLights = 0;
  15288. var pointLights = 0;
  15289. var spotLights = 0;
  15290. var hemiLights = 0;
  15291. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15292. var light = lights[ l ];
  15293. if ( light.onlyShadow || light.visible === false ) continue;
  15294. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15295. if ( light instanceof THREE.PointLight ) pointLights ++;
  15296. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15297. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15298. }
  15299. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15300. };
  15301. function allocateShadows( lights ) {
  15302. var maxShadows = 0;
  15303. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15304. var light = lights[ l ];
  15305. if ( ! light.castShadow ) continue;
  15306. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15307. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15308. }
  15309. return maxShadows;
  15310. };
  15311. // Initialization
  15312. function initGL() {
  15313. try {
  15314. var attributes = {
  15315. alpha: _alpha,
  15316. depth: _depth,
  15317. stencil: _stencil,
  15318. antialias: _antialias,
  15319. premultipliedAlpha: _premultipliedAlpha,
  15320. preserveDrawingBuffer: _preserveDrawingBuffer
  15321. };
  15322. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15323. if ( _gl === null ) {
  15324. throw 'Error creating WebGL context.';
  15325. }
  15326. } catch ( error ) {
  15327. console.error( error );
  15328. }
  15329. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15330. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15331. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15332. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15333. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15334. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15335. if ( _glExtensionTextureFloat === null ) {
  15336. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15337. }
  15338. if ( _glExtensionStandardDerivatives === null ) {
  15339. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15340. }
  15341. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15342. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15343. }
  15344. if ( _glExtensionCompressedTextureS3TC === null ) {
  15345. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15346. }
  15347. if ( _glExtensionElementIndexUint === null ) {
  15348. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15349. }
  15350. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15351. _gl.getShaderPrecisionFormat = function() {
  15352. return {
  15353. "rangeMin" : 1,
  15354. "rangeMax" : 1,
  15355. "precision" : 1
  15356. };
  15357. }
  15358. }
  15359. if ( _logarithmicDepthBuffer ) {
  15360. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  15361. }
  15362. };
  15363. function setDefaultGLState () {
  15364. _gl.clearColor( 0, 0, 0, 1 );
  15365. _gl.clearDepth( 1 );
  15366. _gl.clearStencil( 0 );
  15367. _gl.enable( _gl.DEPTH_TEST );
  15368. _gl.depthFunc( _gl.LEQUAL );
  15369. _gl.frontFace( _gl.CCW );
  15370. _gl.cullFace( _gl.BACK );
  15371. _gl.enable( _gl.CULL_FACE );
  15372. _gl.enable( _gl.BLEND );
  15373. _gl.blendEquation( _gl.FUNC_ADD );
  15374. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15375. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15376. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15377. };
  15378. // default plugins (order is important)
  15379. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15380. this.addPrePlugin( this.shadowMapPlugin );
  15381. this.addPostPlugin( new THREE.SpritePlugin() );
  15382. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15383. };
  15384. /**
  15385. * @author szimek / https://github.com/szimek/
  15386. * @author alteredq / http://alteredqualia.com/
  15387. */
  15388. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15389. this.width = width;
  15390. this.height = height;
  15391. options = options || {};
  15392. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15393. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15394. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15395. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15396. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15397. this.offset = new THREE.Vector2( 0, 0 );
  15398. this.repeat = new THREE.Vector2( 1, 1 );
  15399. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15400. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15401. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15402. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15403. this.generateMipmaps = true;
  15404. this.shareDepthFrom = null;
  15405. };
  15406. THREE.WebGLRenderTarget.prototype = {
  15407. constructor: THREE.WebGLRenderTarget,
  15408. setSize: function ( width, height ) {
  15409. this.width = width;
  15410. this.height = height;
  15411. },
  15412. clone: function () {
  15413. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15414. tmp.wrapS = this.wrapS;
  15415. tmp.wrapT = this.wrapT;
  15416. tmp.magFilter = this.magFilter;
  15417. tmp.minFilter = this.minFilter;
  15418. tmp.anisotropy = this.anisotropy;
  15419. tmp.offset.copy( this.offset );
  15420. tmp.repeat.copy( this.repeat );
  15421. tmp.format = this.format;
  15422. tmp.type = this.type;
  15423. tmp.depthBuffer = this.depthBuffer;
  15424. tmp.stencilBuffer = this.stencilBuffer;
  15425. tmp.generateMipmaps = this.generateMipmaps;
  15426. tmp.shareDepthFrom = this.shareDepthFrom;
  15427. return tmp;
  15428. },
  15429. dispose: function () {
  15430. this.dispatchEvent( { type: 'dispose' } );
  15431. }
  15432. };
  15433. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15434. /**
  15435. * @author alteredq / http://alteredqualia.com
  15436. */
  15437. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15438. THREE.WebGLRenderTarget.call( this, width, height, options );
  15439. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15440. };
  15441. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15442. THREE.WebGLProgram = ( function () {
  15443. var programIdCount = 0;
  15444. var generateDefines = function ( defines ) {
  15445. var value, chunk, chunks = [];
  15446. for ( var d in defines ) {
  15447. value = defines[ d ];
  15448. if ( value === false ) continue;
  15449. chunk = "#define " + d + " " + value;
  15450. chunks.push( chunk );
  15451. }
  15452. return chunks.join( "\n" );
  15453. };
  15454. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15455. var uniforms = {};
  15456. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15457. var id = identifiers[ i ];
  15458. uniforms[ id ] = gl.getUniformLocation( program, id );
  15459. }
  15460. return uniforms;
  15461. };
  15462. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15463. var attributes = {};
  15464. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15465. var id = identifiers[ i ];
  15466. attributes[ id ] = gl.getAttribLocation( program, id );
  15467. }
  15468. return attributes;
  15469. };
  15470. return function ( renderer, code, material, parameters ) {
  15471. var _this = renderer;
  15472. var _gl = _this.context;
  15473. var fragmentShader = material.fragmentShader;
  15474. var vertexShader = material.vertexShader;
  15475. var uniforms = material.uniforms;
  15476. var attributes = material.attributes;
  15477. var defines = material.defines;
  15478. var index0AttributeName = material.index0AttributeName;
  15479. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  15480. // programs with morphTargets displace position out of attribute 0
  15481. index0AttributeName = 'position';
  15482. }
  15483. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15484. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15485. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15486. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15487. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15488. }
  15489. // console.log( "building new program " );
  15490. //
  15491. var customDefines = generateDefines( defines );
  15492. //
  15493. var program = _gl.createProgram();
  15494. var prefix_vertex, prefix_fragment;
  15495. if ( material instanceof THREE.RawShaderMaterial ) {
  15496. prefix_vertex = '';
  15497. prefix_fragment = '';
  15498. } else {
  15499. prefix_vertex = [
  15500. "precision " + parameters.precision + " float;",
  15501. "precision " + parameters.precision + " int;",
  15502. customDefines,
  15503. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15504. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15505. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15506. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15507. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15508. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15509. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15510. "#define MAX_SHADOWS " + parameters.maxShadows,
  15511. "#define MAX_BONES " + parameters.maxBones,
  15512. parameters.map ? "#define USE_MAP" : "",
  15513. parameters.envMap ? "#define USE_ENVMAP" : "",
  15514. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15515. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15516. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15517. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15518. parameters.vertexColors ? "#define USE_COLOR" : "",
  15519. parameters.skinning ? "#define USE_SKINNING" : "",
  15520. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15521. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15522. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15523. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15524. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15525. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15526. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15527. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15528. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15529. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15530. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15531. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15532. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15533. "uniform mat4 modelMatrix;",
  15534. "uniform mat4 modelViewMatrix;",
  15535. "uniform mat4 projectionMatrix;",
  15536. "uniform mat4 viewMatrix;",
  15537. "uniform mat3 normalMatrix;",
  15538. "uniform vec3 cameraPosition;",
  15539. "attribute vec3 position;",
  15540. "attribute vec3 normal;",
  15541. "attribute vec2 uv;",
  15542. "attribute vec2 uv2;",
  15543. "#ifdef USE_COLOR",
  15544. " attribute vec3 color;",
  15545. "#endif",
  15546. "#ifdef USE_MORPHTARGETS",
  15547. " attribute vec3 morphTarget0;",
  15548. " attribute vec3 morphTarget1;",
  15549. " attribute vec3 morphTarget2;",
  15550. " attribute vec3 morphTarget3;",
  15551. " #ifdef USE_MORPHNORMALS",
  15552. " attribute vec3 morphNormal0;",
  15553. " attribute vec3 morphNormal1;",
  15554. " attribute vec3 morphNormal2;",
  15555. " attribute vec3 morphNormal3;",
  15556. " #else",
  15557. " attribute vec3 morphTarget4;",
  15558. " attribute vec3 morphTarget5;",
  15559. " attribute vec3 morphTarget6;",
  15560. " attribute vec3 morphTarget7;",
  15561. " #endif",
  15562. "#endif",
  15563. "#ifdef USE_SKINNING",
  15564. " attribute vec4 skinIndex;",
  15565. " attribute vec4 skinWeight;",
  15566. "#endif",
  15567. ""
  15568. ].join( '\n' );
  15569. prefix_fragment = [
  15570. "precision " + parameters.precision + " float;",
  15571. "precision " + parameters.precision + " int;",
  15572. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15573. customDefines,
  15574. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15575. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15576. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15577. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15578. "#define MAX_SHADOWS " + parameters.maxShadows,
  15579. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15580. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15581. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15582. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15583. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15584. parameters.map ? "#define USE_MAP" : "",
  15585. parameters.envMap ? "#define USE_ENVMAP" : "",
  15586. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15587. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15588. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15589. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15590. parameters.vertexColors ? "#define USE_COLOR" : "",
  15591. parameters.metal ? "#define METAL" : "",
  15592. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15593. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15594. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15595. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15596. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15597. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15598. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15599. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15600. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15601. "uniform mat4 viewMatrix;",
  15602. "uniform vec3 cameraPosition;",
  15603. ""
  15604. ].join( '\n' );
  15605. }
  15606. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15607. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15608. _gl.attachShader( program, glVertexShader );
  15609. _gl.attachShader( program, glFragmentShader );
  15610. if ( index0AttributeName !== undefined ) {
  15611. // Force a particular attribute to index 0.
  15612. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15613. // And, color, for example is often automatically bound to index 0 so disabling it
  15614. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15615. }
  15616. _gl.linkProgram( program );
  15617. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15618. console.error( 'THREE.WebGLProgram: Could not initialise shader.' );
  15619. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15620. console.error( 'gl.getError()', _gl.getError() );
  15621. }
  15622. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15623. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15624. }
  15625. // clean up
  15626. _gl.deleteShader( glVertexShader );
  15627. _gl.deleteShader( glFragmentShader );
  15628. // cache uniform locations
  15629. var identifiers = [
  15630. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15631. 'morphTargetInfluences'
  15632. ];
  15633. if ( parameters.useVertexTexture ) {
  15634. identifiers.push( 'boneTexture' );
  15635. identifiers.push( 'boneTextureWidth' );
  15636. identifiers.push( 'boneTextureHeight' );
  15637. } else {
  15638. identifiers.push( 'boneGlobalMatrices' );
  15639. }
  15640. if ( parameters.logarithmicDepthBuffer ) {
  15641. identifiers.push('logDepthBufFC');
  15642. }
  15643. for ( var u in uniforms ) {
  15644. identifiers.push( u );
  15645. }
  15646. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  15647. // cache attributes locations
  15648. identifiers = [
  15649. "position", "normal", "uv", "uv2", "tangent", "color",
  15650. "skinIndex", "skinWeight", "lineDistance"
  15651. ];
  15652. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15653. identifiers.push( "morphTarget" + i );
  15654. }
  15655. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15656. identifiers.push( "morphNormal" + i );
  15657. }
  15658. for ( var a in attributes ) {
  15659. identifiers.push( a );
  15660. }
  15661. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  15662. //
  15663. this.id = programIdCount ++;
  15664. this.code = code;
  15665. this.usedTimes = 1;
  15666. this.program = program;
  15667. this.vertexShader = glVertexShader;
  15668. this.fragmentShader = glFragmentShader;
  15669. return this;
  15670. };
  15671. } )();
  15672. THREE.WebGLShader = ( function () {
  15673. var addLineNumbers = function ( string ) {
  15674. var lines = string.split( '\n' );
  15675. for ( var i = 0; i < lines.length; i ++ ) {
  15676. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15677. }
  15678. return lines.join( '\n' );
  15679. };
  15680. return function ( gl, type, string ) {
  15681. var shader = gl.createShader( type );
  15682. gl.shaderSource( shader, string );
  15683. gl.compileShader( shader );
  15684. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  15685. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  15686. }
  15687. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15688. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  15689. console.error( addLineNumbers( string ) );
  15690. }
  15691. // --enable-privileged-webgl-extension
  15692. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15693. return shader;
  15694. };
  15695. } )();
  15696. /**
  15697. * @author mrdoob / http://mrdoob.com/
  15698. */
  15699. THREE.RenderableVertex = function () {
  15700. this.position = new THREE.Vector3();
  15701. this.positionWorld = new THREE.Vector3();
  15702. this.positionScreen = new THREE.Vector4();
  15703. this.visible = true;
  15704. };
  15705. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15706. this.positionWorld.copy( vertex.positionWorld );
  15707. this.positionScreen.copy( vertex.positionScreen );
  15708. };
  15709. /**
  15710. * @author mrdoob / http://mrdoob.com/
  15711. */
  15712. THREE.RenderableFace = function () {
  15713. this.id = 0;
  15714. this.v1 = new THREE.RenderableVertex();
  15715. this.v2 = new THREE.RenderableVertex();
  15716. this.v3 = new THREE.RenderableVertex();
  15717. this.normalModel = new THREE.Vector3();
  15718. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15719. this.vertexNormalsLength = 0;
  15720. this.color = new THREE.Color();
  15721. this.material = null;
  15722. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  15723. this.z = 0;
  15724. };
  15725. /**
  15726. * @author mrdoob / http://mrdoob.com/
  15727. */
  15728. THREE.RenderableObject = function () {
  15729. this.id = 0;
  15730. this.object = null;
  15731. this.z = 0;
  15732. };
  15733. /**
  15734. * @author mrdoob / http://mrdoob.com/
  15735. */
  15736. THREE.RenderableSprite = function () {
  15737. this.id = 0;
  15738. this.object = null;
  15739. this.x = 0;
  15740. this.y = 0;
  15741. this.z = 0;
  15742. this.rotation = 0;
  15743. this.scale = new THREE.Vector2();
  15744. this.material = null;
  15745. };
  15746. /**
  15747. * @author mrdoob / http://mrdoob.com/
  15748. */
  15749. THREE.RenderableLine = function () {
  15750. this.id = 0;
  15751. this.v1 = new THREE.RenderableVertex();
  15752. this.v2 = new THREE.RenderableVertex();
  15753. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15754. this.material = null;
  15755. this.z = 0;
  15756. };
  15757. /**
  15758. * @author mrdoob / http://mrdoob.com/
  15759. * @author alteredq / http://alteredqualia.com/
  15760. */
  15761. THREE.GeometryUtils = {
  15762. // Merge two geometries or geometry and geometry from object (using object's transform)
  15763. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15764. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15765. var matrix;
  15766. if ( geometry2 instanceof THREE.Mesh ) {
  15767. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15768. matrix = geometry2.matrix;
  15769. geometry2 = geometry2.geometry;
  15770. }
  15771. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15772. },
  15773. // Get random point in triangle (via barycentric coordinates)
  15774. // (uniform distribution)
  15775. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15776. randomPointInTriangle: function () {
  15777. var vector = new THREE.Vector3();
  15778. return function ( vectorA, vectorB, vectorC ) {
  15779. var point = new THREE.Vector3();
  15780. var a = THREE.Math.random16();
  15781. var b = THREE.Math.random16();
  15782. if ( ( a + b ) > 1 ) {
  15783. a = 1 - a;
  15784. b = 1 - b;
  15785. }
  15786. var c = 1 - a - b;
  15787. point.copy( vectorA );
  15788. point.multiplyScalar( a );
  15789. vector.copy( vectorB );
  15790. vector.multiplyScalar( b );
  15791. point.add( vector );
  15792. vector.copy( vectorC );
  15793. vector.multiplyScalar( c );
  15794. point.add( vector );
  15795. return point;
  15796. };
  15797. }(),
  15798. // Get random point in face (triangle)
  15799. // (uniform distribution)
  15800. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15801. var vA, vB, vC;
  15802. vA = geometry.vertices[ face.a ];
  15803. vB = geometry.vertices[ face.b ];
  15804. vC = geometry.vertices[ face.c ];
  15805. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15806. },
  15807. // Get uniformly distributed random points in mesh
  15808. // - create array with cumulative sums of face areas
  15809. // - pick random number from 0 to total area
  15810. // - find corresponding place in area array by binary search
  15811. // - get random point in face
  15812. randomPointsInGeometry: function ( geometry, n ) {
  15813. var face, i,
  15814. faces = geometry.faces,
  15815. vertices = geometry.vertices,
  15816. il = faces.length,
  15817. totalArea = 0,
  15818. cumulativeAreas = [],
  15819. vA, vB, vC, vD;
  15820. // precompute face areas
  15821. for ( i = 0; i < il; i ++ ) {
  15822. face = faces[ i ];
  15823. vA = vertices[ face.a ];
  15824. vB = vertices[ face.b ];
  15825. vC = vertices[ face.c ];
  15826. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15827. totalArea += face._area;
  15828. cumulativeAreas[ i ] = totalArea;
  15829. }
  15830. // binary search cumulative areas array
  15831. function binarySearchIndices( value ) {
  15832. function binarySearch( start, end ) {
  15833. // return closest larger index
  15834. // if exact number is not found
  15835. if ( end < start )
  15836. return start;
  15837. var mid = start + Math.floor( ( end - start ) / 2 );
  15838. if ( cumulativeAreas[ mid ] > value ) {
  15839. return binarySearch( start, mid - 1 );
  15840. } else if ( cumulativeAreas[ mid ] < value ) {
  15841. return binarySearch( mid + 1, end );
  15842. } else {
  15843. return mid;
  15844. }
  15845. }
  15846. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15847. return result;
  15848. }
  15849. // pick random face weighted by face area
  15850. var r, index,
  15851. result = [];
  15852. var stats = {};
  15853. for ( i = 0; i < n; i ++ ) {
  15854. r = THREE.Math.random16() * totalArea;
  15855. index = binarySearchIndices( r );
  15856. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15857. if ( ! stats[ index ] ) {
  15858. stats[ index ] = 1;
  15859. } else {
  15860. stats[ index ] += 1;
  15861. }
  15862. }
  15863. return result;
  15864. },
  15865. // Get triangle area (half of parallelogram)
  15866. // http://mathworld.wolfram.com/TriangleArea.html
  15867. triangleArea: function () {
  15868. var vector1 = new THREE.Vector3();
  15869. var vector2 = new THREE.Vector3();
  15870. return function ( vectorA, vectorB, vectorC ) {
  15871. vector1.subVectors( vectorB, vectorA );
  15872. vector2.subVectors( vectorC, vectorA );
  15873. vector1.cross( vector2 );
  15874. return 0.5 * vector1.length();
  15875. };
  15876. }(),
  15877. // Center geometry so that 0,0,0 is in center of bounding box
  15878. center: function ( geometry ) {
  15879. geometry.computeBoundingBox();
  15880. var bb = geometry.boundingBox;
  15881. var offset = new THREE.Vector3();
  15882. offset.addVectors( bb.min, bb.max );
  15883. offset.multiplyScalar( -0.5 );
  15884. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15885. geometry.computeBoundingBox();
  15886. return offset;
  15887. }
  15888. };
  15889. /**
  15890. * @author alteredq / http://alteredqualia.com/
  15891. * @author mrdoob / http://mrdoob.com/
  15892. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15893. */
  15894. THREE.ImageUtils = {
  15895. crossOrigin: undefined,
  15896. loadTexture: function ( url, mapping, onLoad, onError ) {
  15897. var loader = new THREE.ImageLoader();
  15898. loader.crossOrigin = this.crossOrigin;
  15899. var texture = new THREE.Texture( undefined, mapping );
  15900. var image = loader.load( url, function () {
  15901. texture.needsUpdate = true;
  15902. if ( onLoad ) onLoad( texture );
  15903. }, undefined, function ( event ) {
  15904. if ( onError ) onError( event );
  15905. } );
  15906. texture.image = image;
  15907. texture.sourceFile = url;
  15908. return texture;
  15909. },
  15910. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15911. var images = [];
  15912. images.loadCount = 0;
  15913. var loader = new THREE.ImageLoader();
  15914. loader.crossOrigin = this.crossOrigin;
  15915. var texture = new THREE.Texture();
  15916. texture.image = images;
  15917. if ( mapping !== undefined ) texture.mapping = mapping;
  15918. // no flipping needed for cube textures
  15919. texture.flipY = false;
  15920. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15921. var cubeImage = loader.load( array[i], function () {
  15922. images.loadCount += 1;
  15923. if ( images.loadCount === 6 ) {
  15924. texture.needsUpdate = true;
  15925. if ( onLoad ) onLoad( texture );
  15926. }
  15927. } );
  15928. images[ i ] = cubeImage;
  15929. }
  15930. return texture;
  15931. },
  15932. getNormalMap: function ( image, depth ) {
  15933. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15934. var cross = function ( a, b ) {
  15935. 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 ] ];
  15936. }
  15937. var subtract = function ( a, b ) {
  15938. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15939. }
  15940. var normalize = function ( a ) {
  15941. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15942. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15943. }
  15944. depth = depth | 1;
  15945. var width = image.width;
  15946. var height = image.height;
  15947. var canvas = document.createElement( 'canvas' );
  15948. canvas.width = width;
  15949. canvas.height = height;
  15950. var context = canvas.getContext( '2d' );
  15951. context.drawImage( image, 0, 0 );
  15952. var data = context.getImageData( 0, 0, width, height ).data;
  15953. var imageData = context.createImageData( width, height );
  15954. var output = imageData.data;
  15955. for ( var x = 0; x < width; x ++ ) {
  15956. for ( var y = 0; y < height; y ++ ) {
  15957. var ly = y - 1 < 0 ? 0 : y - 1;
  15958. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15959. var lx = x - 1 < 0 ? 0 : x - 1;
  15960. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15961. var points = [];
  15962. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15963. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15964. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15965. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15966. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15967. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15968. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15969. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15970. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15971. var normals = [];
  15972. var num_points = points.length;
  15973. for ( var i = 0; i < num_points; i ++ ) {
  15974. var v1 = points[ i ];
  15975. var v2 = points[ ( i + 1 ) % num_points ];
  15976. v1 = subtract( v1, origin );
  15977. v2 = subtract( v2, origin );
  15978. normals.push( normalize( cross( v1, v2 ) ) );
  15979. }
  15980. var normal = [ 0, 0, 0 ];
  15981. for ( var i = 0; i < normals.length; i ++ ) {
  15982. normal[ 0 ] += normals[ i ][ 0 ];
  15983. normal[ 1 ] += normals[ i ][ 1 ];
  15984. normal[ 2 ] += normals[ i ][ 2 ];
  15985. }
  15986. normal[ 0 ] /= normals.length;
  15987. normal[ 1 ] /= normals.length;
  15988. normal[ 2 ] /= normals.length;
  15989. var idx = ( y * width + x ) * 4;
  15990. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15991. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15992. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15993. output[ idx + 3 ] = 255;
  15994. }
  15995. }
  15996. context.putImageData( imageData, 0, 0 );
  15997. return canvas;
  15998. },
  15999. generateDataTexture: function ( width, height, color ) {
  16000. var size = width * height;
  16001. var data = new Uint8Array( 3 * size );
  16002. var r = Math.floor( color.r * 255 );
  16003. var g = Math.floor( color.g * 255 );
  16004. var b = Math.floor( color.b * 255 );
  16005. for ( var i = 0; i < size; i ++ ) {
  16006. data[ i * 3 ] = r;
  16007. data[ i * 3 + 1 ] = g;
  16008. data[ i * 3 + 2 ] = b;
  16009. }
  16010. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16011. texture.needsUpdate = true;
  16012. return texture;
  16013. }
  16014. };
  16015. /**
  16016. * @author alteredq / http://alteredqualia.com/
  16017. */
  16018. THREE.SceneUtils = {
  16019. createMultiMaterialObject: function ( geometry, materials ) {
  16020. var group = new THREE.Object3D();
  16021. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16022. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16023. }
  16024. return group;
  16025. },
  16026. detach : function ( child, parent, scene ) {
  16027. child.applyMatrix( parent.matrixWorld );
  16028. parent.remove( child );
  16029. scene.add( child );
  16030. },
  16031. attach: function ( child, scene, parent ) {
  16032. var matrixWorldInverse = new THREE.Matrix4();
  16033. matrixWorldInverse.getInverse( parent.matrixWorld );
  16034. child.applyMatrix( matrixWorldInverse );
  16035. scene.remove( child );
  16036. parent.add( child );
  16037. }
  16038. };
  16039. /**
  16040. * @author zz85 / http://www.lab4games.net/zz85/blog
  16041. * @author alteredq / http://alteredqualia.com/
  16042. *
  16043. * For Text operations in three.js (See TextGeometry)
  16044. *
  16045. * It uses techniques used in:
  16046. *
  16047. * typeface.js and canvastext
  16048. * For converting fonts and rendering with javascript
  16049. * http://typeface.neocracy.org
  16050. *
  16051. * Triangulation ported from AS3
  16052. * Simple Polygon Triangulation
  16053. * http://actionsnippet.com/?p=1462
  16054. *
  16055. * A Method to triangulate shapes with holes
  16056. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16057. *
  16058. */
  16059. THREE.FontUtils = {
  16060. faces : {},
  16061. // Just for now. face[weight][style]
  16062. face : "helvetiker",
  16063. weight: "normal",
  16064. style : "normal",
  16065. size : 150,
  16066. divisions : 10,
  16067. getFace : function() {
  16068. return this.faces[ this.face ][ this.weight ][ this.style ];
  16069. },
  16070. loadFace : function( data ) {
  16071. var family = data.familyName.toLowerCase();
  16072. var ThreeFont = this;
  16073. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16074. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16075. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16076. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16077. return data;
  16078. },
  16079. drawText : function( text ) {
  16080. var characterPts = [], allPts = [];
  16081. // RenderText
  16082. var i, p,
  16083. face = this.getFace(),
  16084. scale = this.size / face.resolution,
  16085. offset = 0,
  16086. chars = String( text ).split( '' ),
  16087. length = chars.length;
  16088. var fontPaths = [];
  16089. for ( i = 0; i < length; i ++ ) {
  16090. var path = new THREE.Path();
  16091. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16092. offset += ret.offset;
  16093. fontPaths.push( ret.path );
  16094. }
  16095. // get the width
  16096. var width = offset / 2;
  16097. //
  16098. // for ( p = 0; p < allPts.length; p++ ) {
  16099. //
  16100. // allPts[ p ].x -= width;
  16101. //
  16102. // }
  16103. //var extract = this.extractPoints( allPts, characterPts );
  16104. //extract.contour = allPts;
  16105. //extract.paths = fontPaths;
  16106. //extract.offset = width;
  16107. return { paths : fontPaths, offset : width };
  16108. },
  16109. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16110. var pts = [];
  16111. var i, i2, divisions,
  16112. outline, action, length,
  16113. scaleX, scaleY,
  16114. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16115. laste,
  16116. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16117. if ( !glyph ) return;
  16118. if ( glyph.o ) {
  16119. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16120. length = outline.length;
  16121. scaleX = scale;
  16122. scaleY = scale;
  16123. for ( i = 0; i < length; ) {
  16124. action = outline[ i ++ ];
  16125. //console.log( action );
  16126. switch( action ) {
  16127. case 'm':
  16128. // Move To
  16129. x = outline[ i++ ] * scaleX + offset;
  16130. y = outline[ i++ ] * scaleY;
  16131. path.moveTo( x, y );
  16132. break;
  16133. case 'l':
  16134. // Line To
  16135. x = outline[ i++ ] * scaleX + offset;
  16136. y = outline[ i++ ] * scaleY;
  16137. path.lineTo(x,y);
  16138. break;
  16139. case 'q':
  16140. // QuadraticCurveTo
  16141. cpx = outline[ i++ ] * scaleX + offset;
  16142. cpy = outline[ i++ ] * scaleY;
  16143. cpx1 = outline[ i++ ] * scaleX + offset;
  16144. cpy1 = outline[ i++ ] * scaleY;
  16145. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16146. laste = pts[ pts.length - 1 ];
  16147. if ( laste ) {
  16148. cpx0 = laste.x;
  16149. cpy0 = laste.y;
  16150. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16151. var t = i2 / divisions;
  16152. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16153. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16154. }
  16155. }
  16156. break;
  16157. case 'b':
  16158. // Cubic Bezier Curve
  16159. cpx = outline[ i++ ] * scaleX + offset;
  16160. cpy = outline[ i++ ] * scaleY;
  16161. cpx1 = outline[ i++ ] * scaleX + offset;
  16162. cpy1 = outline[ i++ ] * -scaleY;
  16163. cpx2 = outline[ i++ ] * scaleX + offset;
  16164. cpy2 = outline[ i++ ] * -scaleY;
  16165. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16166. laste = pts[ pts.length - 1 ];
  16167. if ( laste ) {
  16168. cpx0 = laste.x;
  16169. cpy0 = laste.y;
  16170. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16171. var t = i2 / divisions;
  16172. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16173. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16174. }
  16175. }
  16176. break;
  16177. }
  16178. }
  16179. }
  16180. return { offset: glyph.ha*scale, path:path};
  16181. }
  16182. };
  16183. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16184. // Parameters
  16185. parameters = parameters || {};
  16186. var size = parameters.size !== undefined ? parameters.size : 100;
  16187. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16188. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16189. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16190. var style = parameters.style !== undefined ? parameters.style : "normal";
  16191. THREE.FontUtils.size = size;
  16192. THREE.FontUtils.divisions = curveSegments;
  16193. THREE.FontUtils.face = font;
  16194. THREE.FontUtils.weight = weight;
  16195. THREE.FontUtils.style = style;
  16196. // Get a Font data json object
  16197. var data = THREE.FontUtils.drawText( text );
  16198. var paths = data.paths;
  16199. var shapes = [];
  16200. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16201. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16202. }
  16203. return shapes;
  16204. };
  16205. /**
  16206. * This code is a quick port of code written in C++ which was submitted to
  16207. * flipcode.com by John W. Ratcliff // July 22, 2000
  16208. * See original code and more information here:
  16209. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16210. *
  16211. * ported to actionscript by Zevan Rosser
  16212. * www.actionsnippet.com
  16213. *
  16214. * ported to javascript by Joshua Koo
  16215. * http://www.lab4games.net/zz85/blog
  16216. *
  16217. */
  16218. ( function( namespace ) {
  16219. var EPSILON = 0.0000000001;
  16220. // takes in an contour array and returns
  16221. var process = function( contour, indices ) {
  16222. var n = contour.length;
  16223. if ( n < 3 ) return null;
  16224. var result = [],
  16225. verts = [],
  16226. vertIndices = [];
  16227. /* we want a counter-clockwise polygon in verts */
  16228. var u, v, w;
  16229. if ( area( contour ) > 0.0 ) {
  16230. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16231. } else {
  16232. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16233. }
  16234. var nv = n;
  16235. /* remove nv - 2 vertices, creating 1 triangle every time */
  16236. var count = 2 * nv; /* error detection */
  16237. for( v = nv - 1; nv > 2; ) {
  16238. /* if we loop, it is probably a non-simple polygon */
  16239. if ( ( count-- ) <= 0 ) {
  16240. //** Triangulate: ERROR - probable bad polygon!
  16241. //throw ( "Warning, unable to triangulate polygon!" );
  16242. //return null;
  16243. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16244. console.log( "Warning, unable to triangulate polygon!" );
  16245. if ( indices ) return vertIndices;
  16246. return result;
  16247. }
  16248. /* three consecutive vertices in current polygon, <u,v,w> */
  16249. u = v; if ( nv <= u ) u = 0; /* previous */
  16250. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16251. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16252. if ( snip( contour, u, v, w, nv, verts ) ) {
  16253. var a, b, c, s, t;
  16254. /* true names of the vertices */
  16255. a = verts[ u ];
  16256. b = verts[ v ];
  16257. c = verts[ w ];
  16258. /* output Triangle */
  16259. result.push( [ contour[ a ],
  16260. contour[ b ],
  16261. contour[ c ] ] );
  16262. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16263. /* remove v from the remaining polygon */
  16264. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16265. verts[ s ] = verts[ t ];
  16266. }
  16267. nv--;
  16268. /* reset error detection counter */
  16269. count = 2 * nv;
  16270. }
  16271. }
  16272. if ( indices ) return vertIndices;
  16273. return result;
  16274. };
  16275. // calculate area of the contour polygon
  16276. var area = function ( contour ) {
  16277. var n = contour.length;
  16278. var a = 0.0;
  16279. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16280. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16281. }
  16282. return a * 0.5;
  16283. };
  16284. var snip = function ( contour, u, v, w, n, verts ) {
  16285. var p;
  16286. var ax, ay, bx, by;
  16287. var cx, cy, px, py;
  16288. ax = contour[ verts[ u ] ].x;
  16289. ay = contour[ verts[ u ] ].y;
  16290. bx = contour[ verts[ v ] ].x;
  16291. by = contour[ verts[ v ] ].y;
  16292. cx = contour[ verts[ w ] ].x;
  16293. cy = contour[ verts[ w ] ].y;
  16294. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16295. var aX, aY, bX, bY, cX, cY;
  16296. var apx, apy, bpx, bpy, cpx, cpy;
  16297. var cCROSSap, bCROSScp, aCROSSbp;
  16298. aX = cx - bx; aY = cy - by;
  16299. bX = ax - cx; bY = ay - cy;
  16300. cX = bx - ax; cY = by - ay;
  16301. for ( p = 0; p < n; p++ ) {
  16302. px = contour[ verts[ p ] ].x
  16303. py = contour[ verts[ p ] ].y
  16304. if ( ( (px === ax) && (py === ay) ) ||
  16305. ( (px === bx) && (py === by) ) ||
  16306. ( (px === cx) && (py === cy) ) ) continue;
  16307. apx = px - ax; apy = py - ay;
  16308. bpx = px - bx; bpy = py - by;
  16309. cpx = px - cx; cpy = py - cy;
  16310. // see if p is inside triangle abc
  16311. aCROSSbp = aX*bpy - aY*bpx;
  16312. cCROSSap = cX*apy - cY*apx;
  16313. bCROSScp = bX*cpy - bY*cpx;
  16314. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16315. }
  16316. return true;
  16317. };
  16318. namespace.Triangulate = process;
  16319. namespace.Triangulate.area = area;
  16320. return namespace;
  16321. })(THREE.FontUtils);
  16322. // To use the typeface.js face files, hook up the API
  16323. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16324. THREE.typeface_js = self._typeface_js;
  16325. /**
  16326. * @author zz85 / http://www.lab4games.net/zz85/blog
  16327. * Extensible curve object
  16328. *
  16329. * Some common of Curve methods
  16330. * .getPoint(t), getTangent(t)
  16331. * .getPointAt(u), getTagentAt(u)
  16332. * .getPoints(), .getSpacedPoints()
  16333. * .getLength()
  16334. * .updateArcLengths()
  16335. *
  16336. * This following classes subclasses THREE.Curve:
  16337. *
  16338. * -- 2d classes --
  16339. * THREE.LineCurve
  16340. * THREE.QuadraticBezierCurve
  16341. * THREE.CubicBezierCurve
  16342. * THREE.SplineCurve
  16343. * THREE.ArcCurve
  16344. * THREE.EllipseCurve
  16345. *
  16346. * -- 3d classes --
  16347. * THREE.LineCurve3
  16348. * THREE.QuadraticBezierCurve3
  16349. * THREE.CubicBezierCurve3
  16350. * THREE.SplineCurve3
  16351. * THREE.ClosedSplineCurve3
  16352. *
  16353. * A series of curves can be represented as a THREE.CurvePath
  16354. *
  16355. **/
  16356. /**************************************************************
  16357. * Abstract Curve base class
  16358. **************************************************************/
  16359. THREE.Curve = function () {
  16360. };
  16361. // Virtual base class method to overwrite and implement in subclasses
  16362. // - t [0 .. 1]
  16363. THREE.Curve.prototype.getPoint = function ( t ) {
  16364. console.log( "Warning, getPoint() not implemented!" );
  16365. return null;
  16366. };
  16367. // Get point at relative position in curve according to arc length
  16368. // - u [0 .. 1]
  16369. THREE.Curve.prototype.getPointAt = function ( u ) {
  16370. var t = this.getUtoTmapping( u );
  16371. return this.getPoint( t );
  16372. };
  16373. // Get sequence of points using getPoint( t )
  16374. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16375. if ( !divisions ) divisions = 5;
  16376. var d, pts = [];
  16377. for ( d = 0; d <= divisions; d ++ ) {
  16378. pts.push( this.getPoint( d / divisions ) );
  16379. }
  16380. return pts;
  16381. };
  16382. // Get sequence of points using getPointAt( u )
  16383. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16384. if ( !divisions ) divisions = 5;
  16385. var d, pts = [];
  16386. for ( d = 0; d <= divisions; d ++ ) {
  16387. pts.push( this.getPointAt( d / divisions ) );
  16388. }
  16389. return pts;
  16390. };
  16391. // Get total curve arc length
  16392. THREE.Curve.prototype.getLength = function () {
  16393. var lengths = this.getLengths();
  16394. return lengths[ lengths.length - 1 ];
  16395. };
  16396. // Get list of cumulative segment lengths
  16397. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16398. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16399. if ( this.cacheArcLengths
  16400. && ( this.cacheArcLengths.length == divisions + 1 )
  16401. && !this.needsUpdate) {
  16402. //console.log( "cached", this.cacheArcLengths );
  16403. return this.cacheArcLengths;
  16404. }
  16405. this.needsUpdate = false;
  16406. var cache = [];
  16407. var current, last = this.getPoint( 0 );
  16408. var p, sum = 0;
  16409. cache.push( 0 );
  16410. for ( p = 1; p <= divisions; p ++ ) {
  16411. current = this.getPoint ( p / divisions );
  16412. sum += current.distanceTo( last );
  16413. cache.push( sum );
  16414. last = current;
  16415. }
  16416. this.cacheArcLengths = cache;
  16417. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16418. };
  16419. THREE.Curve.prototype.updateArcLengths = function() {
  16420. this.needsUpdate = true;
  16421. this.getLengths();
  16422. };
  16423. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16424. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16425. var arcLengths = this.getLengths();
  16426. var i = 0, il = arcLengths.length;
  16427. var targetArcLength; // The targeted u distance value to get
  16428. if ( distance ) {
  16429. targetArcLength = distance;
  16430. } else {
  16431. targetArcLength = u * arcLengths[ il - 1 ];
  16432. }
  16433. //var time = Date.now();
  16434. // binary search for the index with largest value smaller than target u distance
  16435. var low = 0, high = il - 1, comparison;
  16436. while ( low <= high ) {
  16437. 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
  16438. comparison = arcLengths[ i ] - targetArcLength;
  16439. if ( comparison < 0 ) {
  16440. low = i + 1;
  16441. continue;
  16442. } else if ( comparison > 0 ) {
  16443. high = i - 1;
  16444. continue;
  16445. } else {
  16446. high = i;
  16447. break;
  16448. // DONE
  16449. }
  16450. }
  16451. i = high;
  16452. //console.log('b' , i, low, high, Date.now()- time);
  16453. if ( arcLengths[ i ] == targetArcLength ) {
  16454. var t = i / ( il - 1 );
  16455. return t;
  16456. }
  16457. // we could get finer grain at lengths, or use simple interpolatation between two points
  16458. var lengthBefore = arcLengths[ i ];
  16459. var lengthAfter = arcLengths[ i + 1 ];
  16460. var segmentLength = lengthAfter - lengthBefore;
  16461. // determine where we are between the 'before' and 'after' points
  16462. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16463. // add that fractional amount to t
  16464. var t = ( i + segmentFraction ) / ( il -1 );
  16465. return t;
  16466. };
  16467. // Returns a unit vector tangent at t
  16468. // In case any sub curve does not implement its tangent derivation,
  16469. // 2 points a small delta apart will be used to find its gradient
  16470. // which seems to give a reasonable approximation
  16471. THREE.Curve.prototype.getTangent = function( t ) {
  16472. var delta = 0.0001;
  16473. var t1 = t - delta;
  16474. var t2 = t + delta;
  16475. // Capping in case of danger
  16476. if ( t1 < 0 ) t1 = 0;
  16477. if ( t2 > 1 ) t2 = 1;
  16478. var pt1 = this.getPoint( t1 );
  16479. var pt2 = this.getPoint( t2 );
  16480. var vec = pt2.clone().sub(pt1);
  16481. return vec.normalize();
  16482. };
  16483. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16484. var t = this.getUtoTmapping( u );
  16485. return this.getTangent( t );
  16486. };
  16487. /**************************************************************
  16488. * Utils
  16489. **************************************************************/
  16490. THREE.Curve.Utils = {
  16491. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16492. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16493. },
  16494. // Puay Bing, thanks for helping with this derivative!
  16495. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16496. return -3 * p0 * (1 - t) * (1 - t) +
  16497. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16498. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16499. 3 * t * t * p3;
  16500. },
  16501. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16502. // To check if my formulas are correct
  16503. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16504. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16505. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16506. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16507. return h00 + h10 + h01 + h11;
  16508. },
  16509. // Catmull-Rom
  16510. interpolate: function( p0, p1, p2, p3, t ) {
  16511. var v0 = ( p2 - p0 ) * 0.5;
  16512. var v1 = ( p3 - p1 ) * 0.5;
  16513. var t2 = t * t;
  16514. var t3 = t * t2;
  16515. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16516. }
  16517. };
  16518. // TODO: Transformation for Curves?
  16519. /**************************************************************
  16520. * 3D Curves
  16521. **************************************************************/
  16522. // A Factory method for creating new curve subclasses
  16523. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16524. constructor.prototype = Object.create( THREE.Curve.prototype );
  16525. constructor.prototype.getPoint = getPointFunc;
  16526. return constructor;
  16527. };
  16528. /**
  16529. * @author zz85 / http://www.lab4games.net/zz85/blog
  16530. *
  16531. **/
  16532. /**************************************************************
  16533. * Curved Path - a curve path is simply a array of connected
  16534. * curves, but retains the api of a curve
  16535. **************************************************************/
  16536. THREE.CurvePath = function () {
  16537. this.curves = [];
  16538. this.bends = [];
  16539. this.autoClose = false; // Automatically closes the path
  16540. };
  16541. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16542. THREE.CurvePath.prototype.add = function ( curve ) {
  16543. this.curves.push( curve );
  16544. };
  16545. THREE.CurvePath.prototype.checkConnection = function() {
  16546. // TODO
  16547. // If the ending of curve is not connected to the starting
  16548. // or the next curve, then, this is not a real path
  16549. };
  16550. THREE.CurvePath.prototype.closePath = function() {
  16551. // TODO Test
  16552. // and verify for vector3 (needs to implement equals)
  16553. // Add a line curve if start and end of lines are not connected
  16554. var startPoint = this.curves[0].getPoint(0);
  16555. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16556. if (!startPoint.equals(endPoint)) {
  16557. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16558. }
  16559. };
  16560. // To get accurate point with reference to
  16561. // entire path distance at time t,
  16562. // following has to be done:
  16563. // 1. Length of each sub path have to be known
  16564. // 2. Locate and identify type of curve
  16565. // 3. Get t for the curve
  16566. // 4. Return curve.getPointAt(t')
  16567. THREE.CurvePath.prototype.getPoint = function( t ) {
  16568. var d = t * this.getLength();
  16569. var curveLengths = this.getCurveLengths();
  16570. var i = 0, diff, curve;
  16571. // To think about boundaries points.
  16572. while ( i < curveLengths.length ) {
  16573. if ( curveLengths[ i ] >= d ) {
  16574. diff = curveLengths[ i ] - d;
  16575. curve = this.curves[ i ];
  16576. var u = 1 - diff / curve.getLength();
  16577. return curve.getPointAt( u );
  16578. break;
  16579. }
  16580. i ++;
  16581. }
  16582. return null;
  16583. // loop where sum != 0, sum > d , sum+1 <d
  16584. };
  16585. /*
  16586. THREE.CurvePath.prototype.getTangent = function( t ) {
  16587. };*/
  16588. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16589. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16590. // getPoint() depends on getLength
  16591. THREE.CurvePath.prototype.getLength = function() {
  16592. var lens = this.getCurveLengths();
  16593. return lens[ lens.length - 1 ];
  16594. };
  16595. // Compute lengths and cache them
  16596. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16597. THREE.CurvePath.prototype.getCurveLengths = function() {
  16598. // We use cache values if curves and cache array are same length
  16599. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16600. return this.cacheLengths;
  16601. };
  16602. // Get length of subsurve
  16603. // Push sums into cached array
  16604. var lengths = [], sums = 0;
  16605. var i, il = this.curves.length;
  16606. for ( i = 0; i < il; i ++ ) {
  16607. sums += this.curves[ i ].getLength();
  16608. lengths.push( sums );
  16609. }
  16610. this.cacheLengths = lengths;
  16611. return lengths;
  16612. };
  16613. // Returns min and max coordinates
  16614. THREE.CurvePath.prototype.getBoundingBox = function () {
  16615. var points = this.getPoints();
  16616. var maxX, maxY, maxZ;
  16617. var minX, minY, minZ;
  16618. maxX = maxY = Number.NEGATIVE_INFINITY;
  16619. minX = minY = Number.POSITIVE_INFINITY;
  16620. var p, i, il, sum;
  16621. var v3 = points[0] instanceof THREE.Vector3;
  16622. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16623. for ( i = 0, il = points.length; i < il; i ++ ) {
  16624. p = points[ i ];
  16625. if ( p.x > maxX ) maxX = p.x;
  16626. else if ( p.x < minX ) minX = p.x;
  16627. if ( p.y > maxY ) maxY = p.y;
  16628. else if ( p.y < minY ) minY = p.y;
  16629. if ( v3 ) {
  16630. if ( p.z > maxZ ) maxZ = p.z;
  16631. else if ( p.z < minZ ) minZ = p.z;
  16632. }
  16633. sum.add( p );
  16634. }
  16635. var ret = {
  16636. minX: minX,
  16637. minY: minY,
  16638. maxX: maxX,
  16639. maxY: maxY
  16640. };
  16641. if ( v3 ) {
  16642. ret.maxZ = maxZ;
  16643. ret.minZ = minZ;
  16644. }
  16645. return ret;
  16646. };
  16647. /**************************************************************
  16648. * Create Geometries Helpers
  16649. **************************************************************/
  16650. /// Generate geometry from path points (for Line or Points objects)
  16651. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16652. var pts = this.getPoints( divisions, true );
  16653. return this.createGeometry( pts );
  16654. };
  16655. // Generate geometry from equidistance sampling along the path
  16656. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16657. var pts = this.getSpacedPoints( divisions, true );
  16658. return this.createGeometry( pts );
  16659. };
  16660. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16661. var geometry = new THREE.Geometry();
  16662. for ( var i = 0; i < points.length; i ++ ) {
  16663. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16664. }
  16665. return geometry;
  16666. };
  16667. /**************************************************************
  16668. * Bend / Wrap Helper Methods
  16669. **************************************************************/
  16670. // Wrap path / Bend modifiers?
  16671. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16672. this.bends.push( bendpath );
  16673. };
  16674. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16675. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16676. var i, il;
  16677. if ( !bends ) {
  16678. bends = this.bends;
  16679. }
  16680. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16681. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16682. }
  16683. return oldPts;
  16684. };
  16685. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16686. var oldPts = this.getSpacedPoints( segments );
  16687. var i, il;
  16688. if ( !bends ) {
  16689. bends = this.bends;
  16690. }
  16691. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16692. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16693. }
  16694. return oldPts;
  16695. };
  16696. // This returns getPoints() bend/wrapped around the contour of a path.
  16697. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16698. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16699. var bounds = this.getBoundingBox();
  16700. var i, il, p, oldX, oldY, xNorm;
  16701. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16702. p = oldPts[ i ];
  16703. oldX = p.x;
  16704. oldY = p.y;
  16705. xNorm = oldX / bounds.maxX;
  16706. // If using actual distance, for length > path, requires line extrusions
  16707. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16708. xNorm = path.getUtoTmapping( xNorm, oldX );
  16709. // check for out of bounds?
  16710. var pathPt = path.getPoint( xNorm );
  16711. var normal = path.getTangent( xNorm );
  16712. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  16713. p.x = pathPt.x + normal.x;
  16714. p.y = pathPt.y + normal.y;
  16715. }
  16716. return oldPts;
  16717. };
  16718. /**
  16719. * @author alteredq / http://alteredqualia.com/
  16720. */
  16721. THREE.Gyroscope = function () {
  16722. THREE.Object3D.call( this );
  16723. };
  16724. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16725. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16726. this.matrixAutoUpdate && this.updateMatrix();
  16727. // update matrixWorld
  16728. if ( this.matrixWorldNeedsUpdate || force ) {
  16729. if ( this.parent ) {
  16730. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16731. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16732. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16733. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16734. } else {
  16735. this.matrixWorld.copy( this.matrix );
  16736. }
  16737. this.matrixWorldNeedsUpdate = false;
  16738. force = true;
  16739. }
  16740. // update children
  16741. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16742. this.children[ i ].updateMatrixWorld( force );
  16743. }
  16744. };
  16745. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16746. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16747. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16748. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16749. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16750. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16751. /**
  16752. * @author zz85 / http://www.lab4games.net/zz85/blog
  16753. * Creates free form 2d path using series of points, lines or curves.
  16754. *
  16755. **/
  16756. THREE.Path = function ( points ) {
  16757. THREE.CurvePath.call(this);
  16758. this.actions = [];
  16759. if ( points ) {
  16760. this.fromPoints( points );
  16761. }
  16762. };
  16763. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16764. THREE.PathActions = {
  16765. MOVE_TO: 'moveTo',
  16766. LINE_TO: 'lineTo',
  16767. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16768. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16769. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16770. ARC: 'arc', // Circle
  16771. ELLIPSE: 'ellipse'
  16772. };
  16773. // TODO Clean up PATH API
  16774. // Create path using straight lines to connect all points
  16775. // - vectors: array of Vector2
  16776. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16777. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16778. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16779. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16780. };
  16781. };
  16782. // startPath() endPath()?
  16783. THREE.Path.prototype.moveTo = function ( x, y ) {
  16784. var args = Array.prototype.slice.call( arguments );
  16785. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16786. };
  16787. THREE.Path.prototype.lineTo = function ( x, y ) {
  16788. var args = Array.prototype.slice.call( arguments );
  16789. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16790. var x0 = lastargs[ lastargs.length - 2 ];
  16791. var y0 = lastargs[ lastargs.length - 1 ];
  16792. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16793. this.curves.push( curve );
  16794. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16795. };
  16796. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16797. var args = Array.prototype.slice.call( arguments );
  16798. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16799. var x0 = lastargs[ lastargs.length - 2 ];
  16800. var y0 = lastargs[ lastargs.length - 1 ];
  16801. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16802. new THREE.Vector2( aCPx, aCPy ),
  16803. new THREE.Vector2( aX, aY ) );
  16804. this.curves.push( curve );
  16805. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16806. };
  16807. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16808. aCP2x, aCP2y,
  16809. aX, aY ) {
  16810. var args = Array.prototype.slice.call( arguments );
  16811. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16812. var x0 = lastargs[ lastargs.length - 2 ];
  16813. var y0 = lastargs[ lastargs.length - 1 ];
  16814. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16815. new THREE.Vector2( aCP1x, aCP1y ),
  16816. new THREE.Vector2( aCP2x, aCP2y ),
  16817. new THREE.Vector2( aX, aY ) );
  16818. this.curves.push( curve );
  16819. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16820. };
  16821. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16822. var args = Array.prototype.slice.call( arguments );
  16823. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16824. var x0 = lastargs[ lastargs.length - 2 ];
  16825. var y0 = lastargs[ lastargs.length - 1 ];
  16826. //---
  16827. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16828. Array.prototype.push.apply( npts, pts );
  16829. var curve = new THREE.SplineCurve( npts );
  16830. this.curves.push( curve );
  16831. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16832. };
  16833. // FUTURE: Change the API or follow canvas API?
  16834. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16835. aStartAngle, aEndAngle, aClockwise ) {
  16836. var lastargs = this.actions[ this.actions.length - 1].args;
  16837. var x0 = lastargs[ lastargs.length - 2 ];
  16838. var y0 = lastargs[ lastargs.length - 1 ];
  16839. this.absarc(aX + x0, aY + y0, aRadius,
  16840. aStartAngle, aEndAngle, aClockwise );
  16841. };
  16842. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16843. aStartAngle, aEndAngle, aClockwise ) {
  16844. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16845. };
  16846. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16847. aStartAngle, aEndAngle, aClockwise ) {
  16848. var lastargs = this.actions[ this.actions.length - 1].args;
  16849. var x0 = lastargs[ lastargs.length - 2 ];
  16850. var y0 = lastargs[ lastargs.length - 1 ];
  16851. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16852. aStartAngle, aEndAngle, aClockwise );
  16853. };
  16854. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16855. aStartAngle, aEndAngle, aClockwise ) {
  16856. var args = Array.prototype.slice.call( arguments );
  16857. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16858. aStartAngle, aEndAngle, aClockwise );
  16859. this.curves.push( curve );
  16860. var lastPoint = curve.getPoint(1);
  16861. args.push(lastPoint.x);
  16862. args.push(lastPoint.y);
  16863. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16864. };
  16865. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16866. if ( ! divisions ) divisions = 40;
  16867. var points = [];
  16868. for ( var i = 0; i < divisions; i ++ ) {
  16869. points.push( this.getPoint( i / divisions ) );
  16870. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16871. }
  16872. // if ( closedPath ) {
  16873. //
  16874. // points.push( points[ 0 ] );
  16875. //
  16876. // }
  16877. return points;
  16878. };
  16879. /* Return an array of vectors based on contour of the path */
  16880. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16881. if (this.useSpacedPoints) {
  16882. console.log('tata');
  16883. return this.getSpacedPoints( divisions, closedPath );
  16884. }
  16885. divisions = divisions || 12;
  16886. var points = [];
  16887. var i, il, item, action, args;
  16888. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16889. laste, j,
  16890. t, tx, ty;
  16891. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16892. item = this.actions[ i ];
  16893. action = item.action;
  16894. args = item.args;
  16895. switch( action ) {
  16896. case THREE.PathActions.MOVE_TO:
  16897. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16898. break;
  16899. case THREE.PathActions.LINE_TO:
  16900. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16901. break;
  16902. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16903. cpx = args[ 2 ];
  16904. cpy = args[ 3 ];
  16905. cpx1 = args[ 0 ];
  16906. cpy1 = args[ 1 ];
  16907. if ( points.length > 0 ) {
  16908. laste = points[ points.length - 1 ];
  16909. cpx0 = laste.x;
  16910. cpy0 = laste.y;
  16911. } else {
  16912. laste = this.actions[ i - 1 ].args;
  16913. cpx0 = laste[ laste.length - 2 ];
  16914. cpy0 = laste[ laste.length - 1 ];
  16915. }
  16916. for ( j = 1; j <= divisions; j ++ ) {
  16917. t = j / divisions;
  16918. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16919. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16920. points.push( new THREE.Vector2( tx, ty ) );
  16921. }
  16922. break;
  16923. case THREE.PathActions.BEZIER_CURVE_TO:
  16924. cpx = args[ 4 ];
  16925. cpy = args[ 5 ];
  16926. cpx1 = args[ 0 ];
  16927. cpy1 = args[ 1 ];
  16928. cpx2 = args[ 2 ];
  16929. cpy2 = args[ 3 ];
  16930. if ( points.length > 0 ) {
  16931. laste = points[ points.length - 1 ];
  16932. cpx0 = laste.x;
  16933. cpy0 = laste.y;
  16934. } else {
  16935. laste = this.actions[ i - 1 ].args;
  16936. cpx0 = laste[ laste.length - 2 ];
  16937. cpy0 = laste[ laste.length - 1 ];
  16938. }
  16939. for ( j = 1; j <= divisions; j ++ ) {
  16940. t = j / divisions;
  16941. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16942. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16943. points.push( new THREE.Vector2( tx, ty ) );
  16944. }
  16945. break;
  16946. case THREE.PathActions.CSPLINE_THRU:
  16947. laste = this.actions[ i - 1 ].args;
  16948. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16949. var spts = [ last ];
  16950. var n = divisions * args[ 0 ].length;
  16951. spts = spts.concat( args[ 0 ] );
  16952. var spline = new THREE.SplineCurve( spts );
  16953. for ( j = 1; j <= n; j ++ ) {
  16954. points.push( spline.getPointAt( j / n ) ) ;
  16955. }
  16956. break;
  16957. case THREE.PathActions.ARC:
  16958. var aX = args[ 0 ], aY = args[ 1 ],
  16959. aRadius = args[ 2 ],
  16960. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16961. aClockwise = !!args[ 5 ];
  16962. var deltaAngle = aEndAngle - aStartAngle;
  16963. var angle;
  16964. var tdivisions = divisions * 2;
  16965. for ( j = 1; j <= tdivisions; j ++ ) {
  16966. t = j / tdivisions;
  16967. if ( ! aClockwise ) {
  16968. t = 1 - t;
  16969. }
  16970. angle = aStartAngle + t * deltaAngle;
  16971. tx = aX + aRadius * Math.cos( angle );
  16972. ty = aY + aRadius * Math.sin( angle );
  16973. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16974. points.push( new THREE.Vector2( tx, ty ) );
  16975. }
  16976. //console.log(points);
  16977. break;
  16978. case THREE.PathActions.ELLIPSE:
  16979. var aX = args[ 0 ], aY = args[ 1 ],
  16980. xRadius = args[ 2 ],
  16981. yRadius = args[ 3 ],
  16982. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16983. aClockwise = !!args[ 6 ];
  16984. var deltaAngle = aEndAngle - aStartAngle;
  16985. var angle;
  16986. var tdivisions = divisions * 2;
  16987. for ( j = 1; j <= tdivisions; j ++ ) {
  16988. t = j / tdivisions;
  16989. if ( ! aClockwise ) {
  16990. t = 1 - t;
  16991. }
  16992. angle = aStartAngle + t * deltaAngle;
  16993. tx = aX + xRadius * Math.cos( angle );
  16994. ty = aY + yRadius * Math.sin( angle );
  16995. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16996. points.push( new THREE.Vector2( tx, ty ) );
  16997. }
  16998. //console.log(points);
  16999. break;
  17000. } // end switch
  17001. }
  17002. // Normalize to remove the closing point by default.
  17003. var lastPoint = points[ points.length - 1];
  17004. var EPSILON = 0.0000000001;
  17005. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17006. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17007. points.splice( points.length - 1, 1);
  17008. if ( closedPath ) {
  17009. points.push( points[ 0 ] );
  17010. }
  17011. return points;
  17012. };
  17013. //
  17014. // Breaks path into shapes
  17015. //
  17016. // Assumptions (if parameter isCCW==true the opposite holds):
  17017. // - solid shapes are defined clockwise (CW)
  17018. // - holes are defined counterclockwise (CCW)
  17019. //
  17020. // If parameter noHoles==true:
  17021. // - all subPaths are regarded as solid shapes
  17022. // - definition order CW/CCW has no relevance
  17023. //
  17024. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17025. function extractSubpaths( inActions ) {
  17026. var i, il, item, action, args;
  17027. var subPaths = [], lastPath = new THREE.Path();
  17028. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17029. item = inActions[ i ];
  17030. args = item.args;
  17031. action = item.action;
  17032. if ( action == THREE.PathActions.MOVE_TO ) {
  17033. if ( lastPath.actions.length != 0 ) {
  17034. subPaths.push( lastPath );
  17035. lastPath = new THREE.Path();
  17036. }
  17037. }
  17038. lastPath[ action ].apply( lastPath, args );
  17039. }
  17040. if ( lastPath.actions.length != 0 ) {
  17041. subPaths.push( lastPath );
  17042. }
  17043. // console.log(subPaths);
  17044. return subPaths;
  17045. }
  17046. function toShapesNoHoles( inSubpaths ) {
  17047. var shapes = [];
  17048. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17049. var tmpPath = inSubpaths[ i ];
  17050. var tmpShape = new THREE.Shape();
  17051. tmpShape.actions = tmpPath.actions;
  17052. tmpShape.curves = tmpPath.curves;
  17053. shapes.push( tmpShape );
  17054. }
  17055. //console.log("shape", shapes);
  17056. return shapes;
  17057. };
  17058. function isPointInsidePolygon( inPt, inPolygon ) {
  17059. var EPSILON = 0.0000000001;
  17060. var polyLen = inPolygon.length;
  17061. // inPt on polygon contour => immediate success or
  17062. // toggling of inside/outside at every single! intersection point of an edge
  17063. // with the horizontal line through inPt, left of inPt
  17064. // not counting lowerY endpoints of edges and whole edges on that line
  17065. var inside = false;
  17066. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17067. var edgeLowPt = inPolygon[ p ];
  17068. var edgeHighPt = inPolygon[ q ];
  17069. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17070. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17071. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17072. if ( edgeDy < 0 ) {
  17073. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17074. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17075. }
  17076. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17077. if ( inPt.y == edgeLowPt.y ) {
  17078. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17079. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17080. } else {
  17081. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17082. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17083. if ( perpEdge < 0 ) continue;
  17084. inside = !inside; // true intersection left of inPt
  17085. }
  17086. } else { // parallel or colinear
  17087. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17088. // egde lies on the same horizontal line as inPt
  17089. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17090. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17091. // continue;
  17092. }
  17093. }
  17094. return inside;
  17095. }
  17096. var subPaths = extractSubpaths( this.actions );
  17097. if ( subPaths.length == 0 ) return [];
  17098. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17099. var solid, tmpPath, tmpShape, shapes = [];
  17100. if ( subPaths.length == 1) {
  17101. tmpPath = subPaths[0];
  17102. tmpShape = new THREE.Shape();
  17103. tmpShape.actions = tmpPath.actions;
  17104. tmpShape.curves = tmpPath.curves;
  17105. shapes.push( tmpShape );
  17106. return shapes;
  17107. }
  17108. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17109. holesFirst = isCCW ? !holesFirst : holesFirst;
  17110. // console.log("Holes first", holesFirst);
  17111. var betterShapeHoles = [];
  17112. var newShapes = [];
  17113. var newShapeHoles = [];
  17114. var mainIdx = 0;
  17115. var tmpPoints;
  17116. newShapes[mainIdx] = undefined;
  17117. newShapeHoles[mainIdx] = [];
  17118. var i, il;
  17119. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17120. tmpPath = subPaths[ i ];
  17121. tmpPoints = tmpPath.getPoints();
  17122. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17123. solid = isCCW ? !solid : solid;
  17124. if ( solid ) {
  17125. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17126. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17127. newShapes[mainIdx].s.actions = tmpPath.actions;
  17128. newShapes[mainIdx].s.curves = tmpPath.curves;
  17129. if ( holesFirst ) mainIdx++;
  17130. newShapeHoles[mainIdx] = [];
  17131. //console.log('cw', i);
  17132. } else {
  17133. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17134. //console.log('ccw', i);
  17135. }
  17136. }
  17137. // only Holes? -> probably all Shapes with wrong orientation
  17138. if ( !newShapes[0] ) return toShapesNoHoles( subPaths );
  17139. if ( newShapes.length > 1 ) {
  17140. var ambigious = false;
  17141. var toChange = [];
  17142. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17143. betterShapeHoles[sIdx] = [];
  17144. }
  17145. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17146. var sh = newShapes[sIdx];
  17147. var sho = newShapeHoles[sIdx];
  17148. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17149. var ho = sho[hIdx];
  17150. var hole_unassigned = true;
  17151. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17152. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17153. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17154. if ( hole_unassigned ) {
  17155. hole_unassigned = false;
  17156. betterShapeHoles[s2Idx].push( ho );
  17157. } else {
  17158. ambigious = true;
  17159. }
  17160. }
  17161. }
  17162. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17163. }
  17164. }
  17165. // console.log("ambigious: ", ambigious);
  17166. if ( toChange.length > 0 ) {
  17167. // console.log("to change: ", toChange);
  17168. if (! ambigious) newShapeHoles = betterShapeHoles;
  17169. }
  17170. }
  17171. var tmpHoles, j, jl;
  17172. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17173. tmpShape = newShapes[i].s;
  17174. shapes.push( tmpShape );
  17175. tmpHoles = newShapeHoles[i];
  17176. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17177. tmpShape.holes.push( tmpHoles[j].h );
  17178. }
  17179. }
  17180. //console.log("shape", shapes);
  17181. return shapes;
  17182. };
  17183. /**
  17184. * @author zz85 / http://www.lab4games.net/zz85/blog
  17185. * Defines a 2d shape plane using paths.
  17186. **/
  17187. // STEP 1 Create a path.
  17188. // STEP 2 Turn path into shape.
  17189. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17190. // STEP 3a - Extract points from each shape, turn to vertices
  17191. // STEP 3b - Triangulate each shape, add faces.
  17192. THREE.Shape = function () {
  17193. THREE.Path.apply( this, arguments );
  17194. this.holes = [];
  17195. };
  17196. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17197. // Convenience method to return ExtrudeGeometry
  17198. THREE.Shape.prototype.extrude = function ( options ) {
  17199. var extruded = new THREE.ExtrudeGeometry( this, options );
  17200. return extruded;
  17201. };
  17202. // Convenience method to return ShapeGeometry
  17203. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17204. var geometry = new THREE.ShapeGeometry( this, options );
  17205. return geometry;
  17206. };
  17207. // Get points of holes
  17208. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17209. var i, il = this.holes.length, holesPts = [];
  17210. for ( i = 0; i < il; i ++ ) {
  17211. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17212. }
  17213. return holesPts;
  17214. };
  17215. // Get points of holes (spaced by regular distance)
  17216. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17217. var i, il = this.holes.length, holesPts = [];
  17218. for ( i = 0; i < il; i ++ ) {
  17219. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17220. }
  17221. return holesPts;
  17222. };
  17223. // Get points of shape and holes (keypoints based on segments parameter)
  17224. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17225. return {
  17226. shape: this.getTransformedPoints( divisions ),
  17227. holes: this.getPointsHoles( divisions )
  17228. };
  17229. };
  17230. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17231. if (this.useSpacedPoints) {
  17232. return this.extractAllSpacedPoints(divisions);
  17233. }
  17234. return this.extractAllPoints(divisions);
  17235. };
  17236. //
  17237. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17238. //
  17239. // return {
  17240. //
  17241. // shape: this.transform( bend, divisions ),
  17242. // holes: this.getPointsHoles( divisions, bend )
  17243. //
  17244. // };
  17245. //
  17246. // };
  17247. // Get points of shape and holes (spaced by regular distance)
  17248. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17249. return {
  17250. shape: this.getTransformedSpacedPoints( divisions ),
  17251. holes: this.getSpacedPointsHoles( divisions )
  17252. };
  17253. };
  17254. /**************************************************************
  17255. * Utils
  17256. **************************************************************/
  17257. THREE.Shape.Utils = {
  17258. triangulateShape: function ( contour, holes ) {
  17259. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17260. // inOtherPt needs to be colinear to the inSegment
  17261. if ( inSegPt1.x != inSegPt2.x ) {
  17262. if ( inSegPt1.x < inSegPt2.x ) {
  17263. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17264. } else {
  17265. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17266. }
  17267. } else {
  17268. if ( inSegPt1.y < inSegPt2.y ) {
  17269. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17270. } else {
  17271. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17272. }
  17273. }
  17274. }
  17275. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17276. var EPSILON = 0.0000000001;
  17277. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17278. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17279. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17280. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17281. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17282. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17283. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17284. var perpSeg2;
  17285. if ( limit > 0 ) {
  17286. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17287. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17288. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17289. } else {
  17290. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17291. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17292. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17293. }
  17294. // i.e. to reduce rounding errors
  17295. // intersection at endpoint of segment#1?
  17296. if ( perpSeg2 == 0 ) {
  17297. if ( ( inExcludeAdjacentSegs ) &&
  17298. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17299. return [ inSeg1Pt1 ];
  17300. }
  17301. if ( perpSeg2 == limit ) {
  17302. if ( ( inExcludeAdjacentSegs ) &&
  17303. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17304. return [ inSeg1Pt2 ];
  17305. }
  17306. // intersection at endpoint of segment#2?
  17307. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17308. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17309. // return real intersection point
  17310. var factorSeg1 = perpSeg2 / limit;
  17311. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17312. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17313. } else { // parallel or colinear
  17314. if ( ( perpSeg1 != 0 ) ||
  17315. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17316. // they are collinear or degenerate
  17317. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17318. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17319. // both segments are points
  17320. if ( seg1Pt && seg2Pt ) {
  17321. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17322. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17323. return [ inSeg1Pt1 ]; // they are the same point
  17324. }
  17325. // segment#1 is a single point
  17326. if ( seg1Pt ) {
  17327. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17328. return [ inSeg1Pt1 ];
  17329. }
  17330. // segment#2 is a single point
  17331. if ( seg2Pt ) {
  17332. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17333. return [ inSeg2Pt1 ];
  17334. }
  17335. // they are collinear segments, which might overlap
  17336. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17337. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17338. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17339. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17340. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17341. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17342. } else {
  17343. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17344. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17345. }
  17346. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17347. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17348. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17349. } else {
  17350. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17351. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17352. }
  17353. } else { // the segments are on a vertical line
  17354. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17355. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17356. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17357. } else {
  17358. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17359. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17360. }
  17361. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17362. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17363. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17364. } else {
  17365. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17366. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17367. }
  17368. }
  17369. if ( seg1minVal <= seg2minVal ) {
  17370. if ( seg1maxVal < seg2minVal ) return [];
  17371. if ( seg1maxVal == seg2minVal ) {
  17372. if ( inExcludeAdjacentSegs ) return [];
  17373. return [ seg2min ];
  17374. }
  17375. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17376. return [ seg2min, seg2max ];
  17377. } else {
  17378. if ( seg1minVal > seg2maxVal ) return [];
  17379. if ( seg1minVal == seg2maxVal ) {
  17380. if ( inExcludeAdjacentSegs ) return [];
  17381. return [ seg1min ];
  17382. }
  17383. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17384. return [ seg1min, seg2max ];
  17385. }
  17386. }
  17387. }
  17388. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17389. // The order of legs is important
  17390. var EPSILON = 0.0000000001;
  17391. // translation of all points, so that Vertex is at (0,0)
  17392. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17393. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17394. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17395. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17396. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17397. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17398. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17399. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17400. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17401. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17402. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17403. } else { // main angle > 180 deg.
  17404. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17405. }
  17406. } else { // angle == 180 deg.
  17407. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17408. return ( from2otherAngle > 0 );
  17409. }
  17410. }
  17411. function removeHoles( contour, holes ) {
  17412. var shape = contour.concat(); // work on this shape
  17413. var hole;
  17414. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17415. // Check if hole point lies within angle around shape point
  17416. var lastShapeIdx = shape.length - 1;
  17417. var prevShapeIdx = inShapeIdx - 1;
  17418. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17419. var nextShapeIdx = inShapeIdx + 1;
  17420. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17421. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17422. if (! insideAngle ) {
  17423. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17424. return false;
  17425. }
  17426. // Check if shape point lies within angle around hole point
  17427. var lastHoleIdx = hole.length - 1;
  17428. var prevHoleIdx = inHoleIdx - 1;
  17429. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17430. var nextHoleIdx = inHoleIdx + 1;
  17431. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17432. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17433. if (! insideAngle ) {
  17434. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17435. return false;
  17436. }
  17437. return true;
  17438. }
  17439. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17440. // checks for intersections with shape edges
  17441. var sIdx, nextIdx, intersection;
  17442. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17443. nextIdx = sIdx+1; nextIdx %= shape.length;
  17444. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17445. if ( intersection.length > 0 ) return true;
  17446. }
  17447. return false;
  17448. }
  17449. var indepHoles = [];
  17450. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17451. // checks for intersections with hole edges
  17452. var ihIdx, chkHole,
  17453. hIdx, nextIdx, intersection;
  17454. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17455. chkHole = holes[indepHoles[ihIdx]];
  17456. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17457. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17458. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17459. if ( intersection.length > 0 ) return true;
  17460. }
  17461. }
  17462. return false;
  17463. }
  17464. var holeIndex, shapeIndex,
  17465. shapePt, holePt,
  17466. holeIdx, cutKey, failedCuts = [],
  17467. tmpShape1, tmpShape2,
  17468. tmpHole1, tmpHole2;
  17469. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17470. indepHoles.push( h );
  17471. }
  17472. var minShapeIndex = 0;
  17473. var counter = indepHoles.length * 2;
  17474. while ( indepHoles.length > 0 ) {
  17475. counter --;
  17476. if ( counter < 0 ) {
  17477. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17478. break;
  17479. }
  17480. // search for shape-vertex and hole-vertex,
  17481. // which can be connected without intersections
  17482. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex++ ) {
  17483. shapePt = shape[ shapeIndex ];
  17484. holeIndex = -1;
  17485. // search for hole which can be reached without intersections
  17486. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17487. holeIdx = indepHoles[h];
  17488. // prevent multiple checks
  17489. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17490. if ( failedCuts[cutKey] !== undefined ) continue;
  17491. hole = holes[holeIdx];
  17492. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17493. holePt = hole[ h2 ];
  17494. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17495. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17496. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17497. holeIndex = h2;
  17498. indepHoles.splice(h,1);
  17499. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17500. tmpShape2 = shape.slice( shapeIndex );
  17501. tmpHole1 = hole.slice( holeIndex );
  17502. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17503. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17504. minShapeIndex = shapeIndex;
  17505. // Debug only, to show the selected cuts
  17506. // glob_CutLines.push( [ shapePt, holePt ] );
  17507. break;
  17508. }
  17509. if ( holeIndex >= 0 ) break; // hole-vertex found
  17510. failedCuts[cutKey] = true; // remember failure
  17511. }
  17512. if ( holeIndex >= 0 ) break; // hole-vertex found
  17513. }
  17514. }
  17515. return shape; /* shape with no holes */
  17516. }
  17517. var i, il, f, face,
  17518. key, index,
  17519. allPointsMap = {};
  17520. // 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.
  17521. var allpoints = contour.concat();
  17522. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17523. Array.prototype.push.apply( allpoints, holes[h] );
  17524. }
  17525. //console.log( "allpoints",allpoints, allpoints.length );
  17526. // prepare all points map
  17527. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17528. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17529. if ( allPointsMap[ key ] !== undefined ) {
  17530. console.log( "Duplicate point", key );
  17531. }
  17532. allPointsMap[ key ] = i;
  17533. }
  17534. // remove holes by cutting paths to holes and adding them to the shape
  17535. var shapeWithoutHoles = removeHoles( contour, holes );
  17536. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17537. //console.log( "triangles",triangles, triangles.length );
  17538. // check all face vertices against all points map
  17539. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17540. face = triangles[ i ];
  17541. for ( f = 0; f < 3; f ++ ) {
  17542. key = face[ f ].x + ":" + face[ f ].y;
  17543. index = allPointsMap[ key ];
  17544. if ( index !== undefined ) {
  17545. face[ f ] = index;
  17546. }
  17547. }
  17548. }
  17549. return triangles.concat();
  17550. },
  17551. isClockWise: function ( pts ) {
  17552. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17553. },
  17554. // Bezier Curves formulas obtained from
  17555. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17556. // Quad Bezier Functions
  17557. b2p0: function ( t, p ) {
  17558. var k = 1 - t;
  17559. return k * k * p;
  17560. },
  17561. b2p1: function ( t, p ) {
  17562. return 2 * ( 1 - t ) * t * p;
  17563. },
  17564. b2p2: function ( t, p ) {
  17565. return t * t * p;
  17566. },
  17567. b2: function ( t, p0, p1, p2 ) {
  17568. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17569. },
  17570. // Cubic Bezier Functions
  17571. b3p0: function ( t, p ) {
  17572. var k = 1 - t;
  17573. return k * k * k * p;
  17574. },
  17575. b3p1: function ( t, p ) {
  17576. var k = 1 - t;
  17577. return 3 * k * k * t * p;
  17578. },
  17579. b3p2: function ( t, p ) {
  17580. var k = 1 - t;
  17581. return 3 * k * t * t * p;
  17582. },
  17583. b3p3: function ( t, p ) {
  17584. return t * t * t * p;
  17585. },
  17586. b3: function ( t, p0, p1, p2, p3 ) {
  17587. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17588. }
  17589. };
  17590. /**************************************************************
  17591. * Line
  17592. **************************************************************/
  17593. THREE.LineCurve = function ( v1, v2 ) {
  17594. this.v1 = v1;
  17595. this.v2 = v2;
  17596. };
  17597. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17598. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17599. var point = this.v2.clone().sub(this.v1);
  17600. point.multiplyScalar( t ).add( this.v1 );
  17601. return point;
  17602. };
  17603. // Line curve is linear, so we can overwrite default getPointAt
  17604. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17605. return this.getPoint( u );
  17606. };
  17607. THREE.LineCurve.prototype.getTangent = function( t ) {
  17608. var tangent = this.v2.clone().sub(this.v1);
  17609. return tangent.normalize();
  17610. };
  17611. /**************************************************************
  17612. * Quadratic Bezier curve
  17613. **************************************************************/
  17614. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17615. this.v0 = v0;
  17616. this.v1 = v1;
  17617. this.v2 = v2;
  17618. };
  17619. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17620. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17621. var tx, ty;
  17622. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17623. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17624. return new THREE.Vector2( tx, ty );
  17625. };
  17626. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17627. var tx, ty;
  17628. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17629. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17630. // returns unit vector
  17631. var tangent = new THREE.Vector2( tx, ty );
  17632. tangent.normalize();
  17633. return tangent;
  17634. };
  17635. /**************************************************************
  17636. * Cubic Bezier curve
  17637. **************************************************************/
  17638. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17639. this.v0 = v0;
  17640. this.v1 = v1;
  17641. this.v2 = v2;
  17642. this.v3 = v3;
  17643. };
  17644. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17645. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17646. var tx, ty;
  17647. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17648. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17649. return new THREE.Vector2( tx, ty );
  17650. };
  17651. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17652. var tx, ty;
  17653. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17654. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17655. var tangent = new THREE.Vector2( tx, ty );
  17656. tangent.normalize();
  17657. return tangent;
  17658. };
  17659. /**************************************************************
  17660. * Spline curve
  17661. **************************************************************/
  17662. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17663. this.points = (points == undefined) ? [] : points;
  17664. };
  17665. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17666. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17667. var v = new THREE.Vector2();
  17668. var c = [];
  17669. var points = this.points, point, intPoint, weight;
  17670. point = ( points.length - 1 ) * t;
  17671. intPoint = Math.floor( point );
  17672. weight = point - intPoint;
  17673. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17674. c[ 1 ] = intPoint;
  17675. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17676. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17677. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17678. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17679. return v;
  17680. };
  17681. /**************************************************************
  17682. * Ellipse curve
  17683. **************************************************************/
  17684. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17685. this.aX = aX;
  17686. this.aY = aY;
  17687. this.xRadius = xRadius;
  17688. this.yRadius = yRadius;
  17689. this.aStartAngle = aStartAngle;
  17690. this.aEndAngle = aEndAngle;
  17691. this.aClockwise = aClockwise;
  17692. };
  17693. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17694. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17695. var angle;
  17696. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17697. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17698. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17699. if ( this.aClockwise === true ) {
  17700. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17701. } else {
  17702. angle = this.aStartAngle + t * deltaAngle;
  17703. }
  17704. var tx = this.aX + this.xRadius * Math.cos( angle );
  17705. var ty = this.aY + this.yRadius * Math.sin( angle );
  17706. return new THREE.Vector2( tx, ty );
  17707. };
  17708. /**************************************************************
  17709. * Arc curve
  17710. **************************************************************/
  17711. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17712. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17713. };
  17714. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17715. /**************************************************************
  17716. * Line3D
  17717. **************************************************************/
  17718. THREE.LineCurve3 = THREE.Curve.create(
  17719. function ( v1, v2 ) {
  17720. this.v1 = v1;
  17721. this.v2 = v2;
  17722. },
  17723. function ( t ) {
  17724. var r = new THREE.Vector3();
  17725. r.subVectors( this.v2, this.v1 ); // diff
  17726. r.multiplyScalar( t );
  17727. r.add( this.v1 );
  17728. return r;
  17729. }
  17730. );
  17731. /**************************************************************
  17732. * Quadratic Bezier 3D curve
  17733. **************************************************************/
  17734. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17735. function ( v0, v1, v2 ) {
  17736. this.v0 = v0;
  17737. this.v1 = v1;
  17738. this.v2 = v2;
  17739. },
  17740. function ( t ) {
  17741. var tx, ty, tz;
  17742. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17743. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17744. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17745. return new THREE.Vector3( tx, ty, tz );
  17746. }
  17747. );
  17748. /**************************************************************
  17749. * Cubic Bezier 3D curve
  17750. **************************************************************/
  17751. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17752. function ( v0, v1, v2, v3 ) {
  17753. this.v0 = v0;
  17754. this.v1 = v1;
  17755. this.v2 = v2;
  17756. this.v3 = v3;
  17757. },
  17758. function ( t ) {
  17759. var tx, ty, tz;
  17760. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17761. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17762. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17763. return new THREE.Vector3( tx, ty, tz );
  17764. }
  17765. );
  17766. /**************************************************************
  17767. * Spline 3D curve
  17768. **************************************************************/
  17769. THREE.SplineCurve3 = THREE.Curve.create(
  17770. function ( points /* array of Vector3 */) {
  17771. this.points = (points == undefined) ? [] : points;
  17772. },
  17773. function ( t ) {
  17774. var v = new THREE.Vector3();
  17775. var c = [];
  17776. var points = this.points, point, intPoint, weight;
  17777. point = ( points.length - 1 ) * t;
  17778. intPoint = Math.floor( point );
  17779. weight = point - intPoint;
  17780. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17781. c[ 1 ] = intPoint;
  17782. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17783. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17784. var pt0 = points[ c[0] ],
  17785. pt1 = points[ c[1] ],
  17786. pt2 = points[ c[2] ],
  17787. pt3 = points[ c[3] ];
  17788. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17789. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17790. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17791. return v;
  17792. }
  17793. );
  17794. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17795. // var v = new THREE.Vector3();
  17796. // var c = [];
  17797. // var points = this.points, point, intPoint, weight;
  17798. // point = ( points.length - 1 ) * t;
  17799. // intPoint = Math.floor( point );
  17800. // weight = point - intPoint;
  17801. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17802. // c[ 1 ] = intPoint;
  17803. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17804. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17805. // var pt0 = points[ c[0] ],
  17806. // pt1 = points[ c[1] ],
  17807. // pt2 = points[ c[2] ],
  17808. // pt3 = points[ c[3] ];
  17809. // // t = weight;
  17810. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17811. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17812. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17813. // return v;
  17814. // }
  17815. /**************************************************************
  17816. * Closed Spline 3D curve
  17817. **************************************************************/
  17818. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17819. function ( points /* array of Vector3 */) {
  17820. this.points = (points == undefined) ? [] : points;
  17821. },
  17822. function ( t ) {
  17823. var v = new THREE.Vector3();
  17824. var c = [];
  17825. var points = this.points, point, intPoint, weight;
  17826. point = ( points.length - 0 ) * t;
  17827. // This needs to be from 0-length +1
  17828. intPoint = Math.floor( point );
  17829. weight = point - intPoint;
  17830. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17831. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17832. c[ 1 ] = ( intPoint ) % points.length;
  17833. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17834. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17835. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17836. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17837. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17838. return v;
  17839. }
  17840. );
  17841. /**
  17842. * @author mikael emtinger / http://gomo.se/
  17843. */
  17844. THREE.AnimationHandler = {
  17845. LINEAR: 0,
  17846. CATMULLROM: 1,
  17847. CATMULLROM_FORWARD: 2,
  17848. //
  17849. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17850. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17851. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17852. //
  17853. animations: [],
  17854. init: function ( data ) {
  17855. if ( data.initialized === true ) return;
  17856. // loop through all keys
  17857. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17858. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17859. // remove minus times
  17860. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17861. data.hierarchy[ h ].keys[ k ].time = 0;
  17862. }
  17863. // create quaternions
  17864. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17865. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17866. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17867. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17868. }
  17869. }
  17870. // prepare morph target keys
  17871. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17872. // get all used
  17873. var usedMorphTargets = {};
  17874. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17875. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17876. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17877. usedMorphTargets[ morphTargetName ] = -1;
  17878. }
  17879. }
  17880. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17881. // set all used on all frames
  17882. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17883. var influences = {};
  17884. for ( var morphTargetName in usedMorphTargets ) {
  17885. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17886. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17887. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17888. break;
  17889. }
  17890. }
  17891. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17892. influences[ morphTargetName ] = 0;
  17893. }
  17894. }
  17895. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17896. }
  17897. }
  17898. // remove all keys that are on the same time
  17899. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17900. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17901. data.hierarchy[ h ].keys.splice( k, 1 );
  17902. k --;
  17903. }
  17904. }
  17905. // set index
  17906. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17907. data.hierarchy[ h ].keys[ k ].index = k;
  17908. }
  17909. }
  17910. data.initialized = true;
  17911. return data;
  17912. },
  17913. parse: function ( root ) {
  17914. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17915. hierarchy.push( root );
  17916. for ( var c = 0; c < root.children.length; c++ )
  17917. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17918. };
  17919. // setup hierarchy
  17920. var hierarchy = [];
  17921. if ( root instanceof THREE.SkinnedMesh ) {
  17922. for ( var b = 0; b < root.skeleton.bones.length; b++ ) {
  17923. hierarchy.push( root.skeleton.bones[ b ] );
  17924. }
  17925. } else {
  17926. parseRecurseHierarchy( root, hierarchy );
  17927. }
  17928. return hierarchy;
  17929. },
  17930. play: function ( animation ) {
  17931. if ( this.animations.indexOf( animation ) === -1 ) {
  17932. this.animations.push( animation );
  17933. }
  17934. },
  17935. stop: function ( animation ) {
  17936. var index = this.animations.indexOf( animation );
  17937. if ( index !== -1 ) {
  17938. this.animations.splice( index, 1 );
  17939. }
  17940. },
  17941. update: function ( deltaTimeMS ) {
  17942. for ( var i = 0; i < this.animations.length; i ++ ) {
  17943. this.animations[ i ].update( deltaTimeMS );
  17944. }
  17945. }
  17946. };
  17947. /**
  17948. * @author mikael emtinger / http://gomo.se/
  17949. * @author mrdoob / http://mrdoob.com/
  17950. * @author alteredq / http://alteredqualia.com/
  17951. */
  17952. THREE.Animation = function ( root, data ) {
  17953. this.root = root;
  17954. this.data = THREE.AnimationHandler.init( data );
  17955. this.hierarchy = THREE.AnimationHandler.parse( root );
  17956. this.currentTime = 0;
  17957. this.timeScale = 1;
  17958. this.isPlaying = false;
  17959. this.loop = true;
  17960. this.weight = 0;
  17961. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17962. };
  17963. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  17964. THREE.Animation.prototype.play = function ( startTime, weight ) {
  17965. this.currentTime = startTime !== undefined ? startTime : 0;
  17966. this.weight = weight !== undefined ? weight: 1;
  17967. this.isPlaying = true;
  17968. this.reset();
  17969. THREE.AnimationHandler.play( this );
  17970. };
  17971. THREE.Animation.prototype.stop = function() {
  17972. this.isPlaying = false;
  17973. THREE.AnimationHandler.stop( this );
  17974. };
  17975. THREE.Animation.prototype.reset = function () {
  17976. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17977. var object = this.hierarchy[ h ];
  17978. object.matrixAutoUpdate = true;
  17979. if ( object.animationCache === undefined ) {
  17980. object.animationCache = {};
  17981. }
  17982. if ( object.animationCache[this.data.name] === undefined ) {
  17983. object.animationCache[this.data.name] = {};
  17984. object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  17985. object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  17986. object.animationCache[this.data.name].originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17987. }
  17988. var animationCache = object.animationCache[this.data.name];
  17989. // Get keys to match our current time
  17990. for ( var t = 0; t < 3; t ++ ) {
  17991. var type = this.keyTypes[ t ];
  17992. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17993. var nextKey = this.getNextKeyWith( type, h, 1 );
  17994. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17995. prevKey = nextKey;
  17996. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17997. }
  17998. animationCache.prevKey[ type ] = prevKey;
  17999. animationCache.nextKey[ type ] = nextKey;
  18000. }
  18001. }
  18002. };
  18003. THREE.Animation.prototype.update = (function(){
  18004. var points = [];
  18005. var target = new THREE.Vector3();
  18006. var newVector = new THREE.Vector3();
  18007. var newQuat = new THREE.Quaternion();
  18008. // Catmull-Rom spline
  18009. var interpolateCatmullRom = function ( points, scale ) {
  18010. var c = [], v3 = [],
  18011. point, intPoint, weight, w2, w3,
  18012. pa, pb, pc, pd;
  18013. point = ( points.length - 1 ) * scale;
  18014. intPoint = Math.floor( point );
  18015. weight = point - intPoint;
  18016. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18017. c[ 1 ] = intPoint;
  18018. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18019. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18020. pa = points[ c[ 0 ] ];
  18021. pb = points[ c[ 1 ] ];
  18022. pc = points[ c[ 2 ] ];
  18023. pd = points[ c[ 3 ] ];
  18024. w2 = weight * weight;
  18025. w3 = weight * w2;
  18026. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18027. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18028. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18029. return v3;
  18030. };
  18031. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18032. var v0 = ( p2 - p0 ) * 0.5,
  18033. v1 = ( p3 - p1 ) * 0.5;
  18034. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18035. };
  18036. return function ( delta ) {
  18037. if ( this.isPlaying === false ) return;
  18038. this.currentTime += delta * this.timeScale;
  18039. if ( this.weight === 0 )
  18040. return;
  18041. //
  18042. var vector;
  18043. var duration = this.data.length;
  18044. if ( this.loop === true && this.currentTime > duration ) {
  18045. this.currentTime %= duration;
  18046. this.reset();
  18047. } else if ( this.loop === false && this.currentTime > duration ) {
  18048. this.stop();
  18049. return;
  18050. }
  18051. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18052. var object = this.hierarchy[ h ];
  18053. var animationCache = object.animationCache[this.data.name];
  18054. // loop through pos/rot/scl
  18055. for ( var t = 0; t < 3; t ++ ) {
  18056. // get keys
  18057. var type = this.keyTypes[ t ];
  18058. var prevKey = animationCache.prevKey[ type ];
  18059. var nextKey = animationCache.nextKey[ type ];
  18060. if ( nextKey.time <= this.currentTime ) {
  18061. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18062. nextKey = this.getNextKeyWith( type, h, 1 );
  18063. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18064. prevKey = nextKey;
  18065. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18066. }
  18067. animationCache.prevKey[ type ] = prevKey;
  18068. animationCache.nextKey[ type ] = nextKey;
  18069. }
  18070. object.matrixAutoUpdate = true;
  18071. object.matrixWorldNeedsUpdate = true;
  18072. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18073. var prevXYZ = prevKey[ type ];
  18074. var nextXYZ = nextKey[ type ];
  18075. if ( scale < 0 ) scale = 0;
  18076. if ( scale > 1 ) scale = 1;
  18077. // interpolate
  18078. if ( type === "pos" ) {
  18079. vector = object.position;
  18080. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18081. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18082. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18083. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18084. // blend
  18085. if (object instanceof THREE.Bone) {
  18086. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18087. vector.lerp( newVector, proportionalWeight );
  18088. object.accumulatedPosWeight += this.weight;
  18089. } else
  18090. vector = newVector;
  18091. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18092. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18093. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18094. points[ 1 ] = prevXYZ;
  18095. points[ 2 ] = nextXYZ;
  18096. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18097. scale = scale * 0.33 + 0.33;
  18098. var currentPoint = interpolateCatmullRom( points, scale );
  18099. if ( object instanceof THREE.Bone ) {
  18100. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18101. object.accumulatedPosWeight += this.weight;
  18102. }
  18103. else
  18104. var proportionalWeight = 1;
  18105. // blend
  18106. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18107. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18108. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18109. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18110. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18111. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18112. target.sub( vector );
  18113. target.y = 0;
  18114. target.normalize();
  18115. var angle = Math.atan2( target.x, target.z );
  18116. object.rotation.set( 0, angle, 0 );
  18117. }
  18118. }
  18119. } else if ( type === "rot" ) {
  18120. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18121. // Avoid paying the cost of an additional slerp if we don't have to
  18122. if ( !( object instanceof THREE.Bone ) ) {
  18123. object.quaternion.copy(newQuat);
  18124. }
  18125. else if ( object.accumulatedRotWeight === 0) {
  18126. object.quaternion.copy(newQuat);
  18127. object.accumulatedRotWeight = this.weight;
  18128. }
  18129. else {
  18130. var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight );
  18131. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18132. object.accumulatedRotWeight += this.weight;
  18133. }
  18134. } else if ( type === "scl" ) {
  18135. vector = object.scale;
  18136. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18137. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18138. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18139. if ( object instanceof THREE.Bone ) {
  18140. var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight);
  18141. vector.lerp( newVector, proportionalWeight );
  18142. object.accumulatedSclWeight += this.weight;
  18143. } else
  18144. vector = newVector;
  18145. }
  18146. }
  18147. }
  18148. return true;
  18149. };
  18150. })();
  18151. // Get next key with
  18152. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18153. var keys = this.data.hierarchy[ h ].keys;
  18154. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18155. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18156. key = key < keys.length - 1 ? key : keys.length - 1;
  18157. } else {
  18158. key = key % keys.length;
  18159. }
  18160. for ( ; key < keys.length; key++ ) {
  18161. if ( keys[ key ][ type ] !== undefined ) {
  18162. return keys[ key ];
  18163. }
  18164. }
  18165. return this.data.hierarchy[ h ].keys[ 0 ];
  18166. };
  18167. // Get previous key with
  18168. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18169. var keys = this.data.hierarchy[ h ].keys;
  18170. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18171. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18172. key = key > 0 ? key : 0;
  18173. } else {
  18174. key = key >= 0 ? key : key + keys.length;
  18175. }
  18176. for ( ; key >= 0; key -- ) {
  18177. if ( keys[ key ][ type ] !== undefined ) {
  18178. return keys[ key ];
  18179. }
  18180. }
  18181. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18182. };
  18183. /**
  18184. * @author mikael emtinger / http://gomo.se/
  18185. * @author mrdoob / http://mrdoob.com/
  18186. * @author alteredq / http://alteredqualia.com/
  18187. * @author khang duong
  18188. * @author erik kitson
  18189. */
  18190. THREE.KeyFrameAnimation = function ( data ) {
  18191. this.root = data.node;
  18192. this.data = THREE.AnimationHandler.init( data );
  18193. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18194. this.currentTime = 0;
  18195. this.timeScale = 0.001;
  18196. this.isPlaying = false;
  18197. this.isPaused = true;
  18198. this.loop = true;
  18199. // initialize to first keyframes
  18200. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18201. var keys = this.data.hierarchy[h].keys,
  18202. sids = this.data.hierarchy[h].sids,
  18203. obj = this.hierarchy[h];
  18204. if ( keys.length && sids ) {
  18205. for ( var s = 0; s < sids.length; s++ ) {
  18206. var sid = sids[ s ],
  18207. next = this.getNextKeyWith( sid, h, 0 );
  18208. if ( next ) {
  18209. next.apply( sid );
  18210. }
  18211. }
  18212. obj.matrixAutoUpdate = false;
  18213. this.data.hierarchy[h].node.updateMatrix();
  18214. obj.matrixWorldNeedsUpdate = true;
  18215. }
  18216. }
  18217. };
  18218. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18219. this.currentTime = startTime !== undefined ? startTime : 0;
  18220. if ( this.isPlaying === false ) {
  18221. this.isPlaying = true;
  18222. // reset key cache
  18223. var h, hl = this.hierarchy.length,
  18224. object,
  18225. node;
  18226. for ( h = 0; h < hl; h++ ) {
  18227. object = this.hierarchy[ h ];
  18228. node = this.data.hierarchy[ h ];
  18229. if ( node.animationCache === undefined ) {
  18230. node.animationCache = {};
  18231. node.animationCache.prevKey = null;
  18232. node.animationCache.nextKey = null;
  18233. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18234. }
  18235. var keys = this.data.hierarchy[h].keys;
  18236. if (keys.length) {
  18237. node.animationCache.prevKey = keys[ 0 ];
  18238. node.animationCache.nextKey = keys[ 1 ];
  18239. this.startTime = Math.min( keys[0].time, this.startTime );
  18240. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18241. }
  18242. }
  18243. this.update( 0 );
  18244. }
  18245. this.isPaused = false;
  18246. THREE.AnimationHandler.play( this );
  18247. };
  18248. THREE.KeyFrameAnimation.prototype.stop = function() {
  18249. this.isPlaying = false;
  18250. this.isPaused = false;
  18251. THREE.AnimationHandler.stop( this );
  18252. // reset JIT matrix and remove cache
  18253. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18254. var obj = this.hierarchy[ h ];
  18255. var node = this.data.hierarchy[ h ];
  18256. if ( node.animationCache !== undefined ) {
  18257. var original = node.animationCache.originalMatrix;
  18258. if( obj instanceof THREE.Bone ) {
  18259. original.copy( obj.skinMatrix );
  18260. obj.skinMatrix = original;
  18261. } else {
  18262. original.copy( obj.matrix );
  18263. obj.matrix = original;
  18264. }
  18265. delete node.animationCache;
  18266. }
  18267. }
  18268. };
  18269. // Update
  18270. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18271. if ( this.isPlaying === false ) return;
  18272. this.currentTime += delta * this.timeScale;
  18273. //
  18274. var duration = this.data.length;
  18275. if ( this.loop === true && this.currentTime > duration ) {
  18276. this.currentTime %= duration;
  18277. }
  18278. this.currentTime = Math.min( this.currentTime, duration );
  18279. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18280. var object = this.hierarchy[ h ];
  18281. var node = this.data.hierarchy[ h ];
  18282. var keys = node.keys,
  18283. animationCache = node.animationCache;
  18284. if ( keys.length ) {
  18285. var prevKey = animationCache.prevKey;
  18286. var nextKey = animationCache.nextKey;
  18287. if ( nextKey.time <= this.currentTime ) {
  18288. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18289. prevKey = nextKey;
  18290. nextKey = keys[ prevKey.index + 1 ];
  18291. }
  18292. animationCache.prevKey = prevKey;
  18293. animationCache.nextKey = nextKey;
  18294. }
  18295. if ( nextKey.time >= this.currentTime ) {
  18296. prevKey.interpolate( nextKey, this.currentTime );
  18297. } else {
  18298. prevKey.interpolate( nextKey, nextKey.time );
  18299. }
  18300. this.data.hierarchy[ h ].node.updateMatrix();
  18301. object.matrixWorldNeedsUpdate = true;
  18302. }
  18303. }
  18304. };
  18305. // Get next key with
  18306. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18307. var keys = this.data.hierarchy[ h ].keys;
  18308. key = key % keys.length;
  18309. for ( ; key < keys.length; key++ ) {
  18310. if ( keys[ key ].hasTarget( sid ) ) {
  18311. return keys[ key ];
  18312. }
  18313. }
  18314. return keys[ 0 ];
  18315. };
  18316. // Get previous key with
  18317. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18318. var keys = this.data.hierarchy[ h ].keys;
  18319. key = key >= 0 ? key : key + keys.length;
  18320. for ( ; key >= 0; key-- ) {
  18321. if ( keys[ key ].hasTarget( sid ) ) {
  18322. return keys[ key ];
  18323. }
  18324. }
  18325. return keys[ keys.length - 1 ];
  18326. };
  18327. /**
  18328. * @author mrdoob / http://mrdoob.com
  18329. */
  18330. THREE.MorphAnimation = function ( mesh ) {
  18331. this.mesh = mesh;
  18332. this.frames = mesh.morphTargetInfluences.length;
  18333. this.currentTime = 0;
  18334. this.duration = 1000;
  18335. this.loop = true;
  18336. this.isPlaying = false;
  18337. };
  18338. THREE.MorphAnimation.prototype = {
  18339. play: function () {
  18340. this.isPlaying = true;
  18341. },
  18342. pause: function () {
  18343. this.isPlaying = false;
  18344. },
  18345. update: ( function () {
  18346. var lastFrame = 0;
  18347. var currentFrame = 0;
  18348. return function ( delta ) {
  18349. if ( this.isPlaying === false ) return;
  18350. this.currentTime += delta;
  18351. if ( this.loop === true && this.currentTime > this.duration ) {
  18352. this.currentTime %= this.duration;
  18353. }
  18354. this.currentTime = Math.min( this.currentTime, this.duration );
  18355. var interpolation = this.duration / this.frames;
  18356. var frame = Math.floor( this.currentTime / interpolation );
  18357. if ( frame != currentFrame ) {
  18358. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18359. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18360. this.mesh.morphTargetInfluences[ frame ] = 0;
  18361. lastFrame = currentFrame;
  18362. currentFrame = frame;
  18363. }
  18364. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18365. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18366. }
  18367. } )()
  18368. };
  18369. /**
  18370. * @author mrdoob / http://mrdoob.com/
  18371. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18372. */
  18373. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18374. THREE.Geometry.call( this );
  18375. this.parameters = {
  18376. width: width,
  18377. height: height,
  18378. depth: depth,
  18379. widthSegments: widthSegments,
  18380. heightSegments: heightSegments,
  18381. depthSegments: depthSegments
  18382. };
  18383. this.widthSegments = widthSegments || 1;
  18384. this.heightSegments = heightSegments || 1;
  18385. this.depthSegments = depthSegments || 1;
  18386. var scope = this;
  18387. var width_half = width / 2;
  18388. var height_half = height / 2;
  18389. var depth_half = depth / 2;
  18390. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18391. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18392. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18393. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18394. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18395. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18396. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18397. var w, ix, iy,
  18398. gridX = scope.widthSegments,
  18399. gridY = scope.heightSegments,
  18400. width_half = width / 2,
  18401. height_half = height / 2,
  18402. offset = scope.vertices.length;
  18403. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18404. w = 'z';
  18405. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18406. w = 'y';
  18407. gridY = scope.depthSegments;
  18408. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18409. w = 'x';
  18410. gridX = scope.depthSegments;
  18411. }
  18412. var gridX1 = gridX + 1,
  18413. gridY1 = gridY + 1,
  18414. segment_width = width / gridX,
  18415. segment_height = height / gridY,
  18416. normal = new THREE.Vector3();
  18417. normal[ w ] = depth > 0 ? 1 : - 1;
  18418. for ( iy = 0; iy < gridY1; iy ++ ) {
  18419. for ( ix = 0; ix < gridX1; ix ++ ) {
  18420. var vector = new THREE.Vector3();
  18421. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18422. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18423. vector[ w ] = depth;
  18424. scope.vertices.push( vector );
  18425. }
  18426. }
  18427. for ( iy = 0; iy < gridY; iy++ ) {
  18428. for ( ix = 0; ix < gridX; ix++ ) {
  18429. var a = ix + gridX1 * iy;
  18430. var b = ix + gridX1 * ( iy + 1 );
  18431. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18432. var d = ( ix + 1 ) + gridX1 * iy;
  18433. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18434. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18435. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18436. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18437. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18438. face.normal.copy( normal );
  18439. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18440. face.materialIndex = materialIndex;
  18441. scope.faces.push( face );
  18442. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18443. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18444. face.normal.copy( normal );
  18445. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18446. face.materialIndex = materialIndex;
  18447. scope.faces.push( face );
  18448. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18449. }
  18450. }
  18451. }
  18452. this.mergeVertices();
  18453. };
  18454. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18455. /**
  18456. * @author hughes
  18457. */
  18458. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18459. THREE.Geometry.call( this );
  18460. this.parameters = {
  18461. radius: radius,
  18462. segments: segments,
  18463. thetaStart: thetaStart,
  18464. thetaLength: thetaLength
  18465. };
  18466. radius = radius || 50;
  18467. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18468. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18469. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18470. var i, uvs = [],
  18471. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18472. this.vertices.push(center);
  18473. uvs.push( centerUV );
  18474. for ( i = 0; i <= segments; i ++ ) {
  18475. var vertex = new THREE.Vector3();
  18476. var segment = thetaStart + i / segments * thetaLength;
  18477. vertex.x = radius * Math.cos( segment );
  18478. vertex.y = radius * Math.sin( segment );
  18479. this.vertices.push( vertex );
  18480. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18481. }
  18482. var n = new THREE.Vector3( 0, 0, 1 );
  18483. for ( i = 1; i <= segments; i ++ ) {
  18484. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18485. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18486. }
  18487. this.computeFaceNormals();
  18488. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18489. };
  18490. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18491. /**
  18492. * @author mrdoob / http://mrdoob.com/
  18493. */
  18494. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18495. console.warn( 'THEE.CubeGeometry has been renamed to THREE.BoxGeometry.' );
  18496. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18497. };
  18498. /**
  18499. * @author mrdoob / http://mrdoob.com/
  18500. */
  18501. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18502. THREE.Geometry.call( this );
  18503. this.parameters = {
  18504. radiusTop: radiusTop,
  18505. radiusBottom: radiusBottom,
  18506. height: height,
  18507. radialSegments: radialSegments,
  18508. heightSegments: heightSegments,
  18509. openEnded: openEnded
  18510. };
  18511. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18512. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18513. height = height !== undefined ? height : 100;
  18514. radialSegments = radialSegments || 8;
  18515. heightSegments = heightSegments || 1;
  18516. openEnded = openEnded !== undefined ? openEnded : false;
  18517. var heightHalf = height / 2;
  18518. var x, y, vertices = [], uvs = [];
  18519. for ( y = 0; y <= heightSegments; y ++ ) {
  18520. var verticesRow = [];
  18521. var uvsRow = [];
  18522. var v = y / heightSegments;
  18523. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18524. for ( x = 0; x <= radialSegments; x ++ ) {
  18525. var u = x / radialSegments;
  18526. var vertex = new THREE.Vector3();
  18527. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18528. vertex.y = - v * height + heightHalf;
  18529. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18530. this.vertices.push( vertex );
  18531. verticesRow.push( this.vertices.length - 1 );
  18532. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18533. }
  18534. vertices.push( verticesRow );
  18535. uvs.push( uvsRow );
  18536. }
  18537. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18538. var na, nb;
  18539. for ( x = 0; x < radialSegments; x ++ ) {
  18540. if ( radiusTop !== 0 ) {
  18541. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18542. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18543. } else {
  18544. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18545. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18546. }
  18547. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18548. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18549. for ( y = 0; y < heightSegments; y ++ ) {
  18550. var v1 = vertices[ y ][ x ];
  18551. var v2 = vertices[ y + 1 ][ x ];
  18552. var v3 = vertices[ y + 1 ][ x + 1 ];
  18553. var v4 = vertices[ y ][ x + 1 ];
  18554. var n1 = na.clone();
  18555. var n2 = na.clone();
  18556. var n3 = nb.clone();
  18557. var n4 = nb.clone();
  18558. var uv1 = uvs[ y ][ x ].clone();
  18559. var uv2 = uvs[ y + 1 ][ x ].clone();
  18560. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18561. var uv4 = uvs[ y ][ x + 1 ].clone();
  18562. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18563. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18564. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18565. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18566. }
  18567. }
  18568. // top cap
  18569. if ( openEnded === false && radiusTop > 0 ) {
  18570. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18571. for ( x = 0; x < radialSegments; x ++ ) {
  18572. var v1 = vertices[ 0 ][ x ];
  18573. var v2 = vertices[ 0 ][ x + 1 ];
  18574. var v3 = this.vertices.length - 1;
  18575. var n1 = new THREE.Vector3( 0, 1, 0 );
  18576. var n2 = new THREE.Vector3( 0, 1, 0 );
  18577. var n3 = new THREE.Vector3( 0, 1, 0 );
  18578. var uv1 = uvs[ 0 ][ x ].clone();
  18579. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18580. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18581. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18582. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18583. }
  18584. }
  18585. // bottom cap
  18586. if ( openEnded === false && radiusBottom > 0 ) {
  18587. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18588. for ( x = 0; x < radialSegments; x ++ ) {
  18589. var v1 = vertices[ y ][ x + 1 ];
  18590. var v2 = vertices[ y ][ x ];
  18591. var v3 = this.vertices.length - 1;
  18592. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18593. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18594. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18595. var uv1 = uvs[ y ][ x + 1 ].clone();
  18596. var uv2 = uvs[ y ][ x ].clone();
  18597. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18598. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18599. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18600. }
  18601. }
  18602. this.computeFaceNormals();
  18603. }
  18604. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18605. /**
  18606. * @author zz85 / http://www.lab4games.net/zz85/blog
  18607. *
  18608. * Creates extruded geometry from a path shape.
  18609. *
  18610. * parameters = {
  18611. *
  18612. * curveSegments: <int>, // number of points on the curves
  18613. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18614. * amount: <int>, // Depth to extrude the shape
  18615. *
  18616. * bevelEnabled: <bool>, // turn on bevel
  18617. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18618. * bevelSize: <float>, // how far from shape outline is bevel
  18619. * bevelSegments: <int>, // number of bevel layers
  18620. *
  18621. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18622. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18623. *
  18624. * material: <int> // material index for front and back faces
  18625. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18626. * uvGenerator: <Object> // object that provides UV generator functions
  18627. *
  18628. * }
  18629. **/
  18630. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18631. if ( typeof( shapes ) === "undefined" ) {
  18632. shapes = [];
  18633. return;
  18634. }
  18635. THREE.Geometry.call( this );
  18636. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18637. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18638. this.addShapeList( shapes, options );
  18639. this.computeFaceNormals();
  18640. // can't really use automatic vertex normals
  18641. // as then front and back sides get smoothed too
  18642. // should do separate smoothing just for sides
  18643. //this.computeVertexNormals();
  18644. //console.log( "took", ( Date.now() - startTime ) );
  18645. };
  18646. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18647. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18648. var sl = shapes.length;
  18649. for ( var s = 0; s < sl; s ++ ) {
  18650. var shape = shapes[ s ];
  18651. this.addShape( shape, options );
  18652. }
  18653. };
  18654. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18655. var amount = options.amount !== undefined ? options.amount : 100;
  18656. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18657. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18658. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18659. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18660. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18661. var steps = options.steps !== undefined ? options.steps : 1;
  18662. var extrudePath = options.extrudePath;
  18663. var extrudePts, extrudeByPath = false;
  18664. var material = options.material;
  18665. var extrudeMaterial = options.extrudeMaterial;
  18666. // Use default WorldUVGenerator if no UV generators are specified.
  18667. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18668. var shapebb = this.shapebb;
  18669. //shapebb = shape.getBoundingBox();
  18670. var splineTube, binormal, normal, position2;
  18671. if ( extrudePath ) {
  18672. extrudePts = extrudePath.getSpacedPoints( steps );
  18673. extrudeByPath = true;
  18674. bevelEnabled = false; // bevels not supported for path extrusion
  18675. // SETUP TNB variables
  18676. // Reuse TNB from TubeGeomtry for now.
  18677. // TODO1 - have a .isClosed in spline?
  18678. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18679. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18680. binormal = new THREE.Vector3();
  18681. normal = new THREE.Vector3();
  18682. position2 = new THREE.Vector3();
  18683. }
  18684. // Safeguards if bevels are not enabled
  18685. if ( ! bevelEnabled ) {
  18686. bevelSegments = 0;
  18687. bevelThickness = 0;
  18688. bevelSize = 0;
  18689. }
  18690. // Variables initalization
  18691. var ahole, h, hl; // looping of holes
  18692. var scope = this;
  18693. var bevelPoints = [];
  18694. var shapesOffset = this.vertices.length;
  18695. var shapePoints = shape.extractPoints( curveSegments );
  18696. var vertices = shapePoints.shape;
  18697. var holes = shapePoints.holes;
  18698. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18699. if ( reverse ) {
  18700. vertices = vertices.reverse();
  18701. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18702. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18703. ahole = holes[ h ];
  18704. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18705. holes[ h ] = ahole.reverse();
  18706. }
  18707. }
  18708. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18709. }
  18710. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18711. /* Vertices */
  18712. var contour = vertices; // vertices has all points but contour has only points of circumference
  18713. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18714. ahole = holes[ h ];
  18715. vertices = vertices.concat( ahole );
  18716. }
  18717. function scalePt2 ( pt, vec, size ) {
  18718. if ( !vec ) console.log( "die" );
  18719. return vec.clone().multiplyScalar( size ).add( pt );
  18720. }
  18721. var b, bs, t, z,
  18722. vert, vlen = vertices.length,
  18723. face, flen = faces.length,
  18724. cont, clen = contour.length;
  18725. // Find directions for point movement
  18726. var RAD_TO_DEGREES = 180 / Math.PI;
  18727. function getBevelVec( inPt, inPrev, inNext ) {
  18728. var EPSILON = 0.0000000001;
  18729. var sign = THREE.Math.sign;
  18730. // computes for inPt the corresponding point inPt' on a new contour
  18731. // shiftet by 1 unit (length of normalized vector) to the left
  18732. // if we walk along contour clockwise, this new contour is outside the old one
  18733. //
  18734. // inPt' is the intersection of the two lines parallel to the two
  18735. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18736. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18737. // good reading for geometry algorithms (here: line-line intersection)
  18738. // http://geomalgorithms.com/a05-_intersect-1.html
  18739. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18740. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18741. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18742. // check for colinear edges
  18743. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18744. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18745. // length of vectors for normalizing
  18746. var v_prev_len = Math.sqrt( v_prev_lensq );
  18747. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18748. // shift adjacent points by unit vectors to the left
  18749. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18750. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18751. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18752. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18753. // scaling factor for v_prev to intersection point
  18754. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18755. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18756. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18757. // vector from inPt to intersection point
  18758. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18759. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18760. // Don't normalize!, otherwise sharp corners become ugly
  18761. // but prevent crazy spikes
  18762. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18763. if ( v_trans_lensq <= 2 ) {
  18764. return new THREE.Vector2( v_trans_x, v_trans_y );
  18765. } else {
  18766. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18767. }
  18768. } else { // handle special case of colinear edges
  18769. var direction_eq = false; // assumes: opposite
  18770. if ( v_prev_x > EPSILON ) {
  18771. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18772. } else {
  18773. if ( v_prev_x < -EPSILON ) {
  18774. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  18775. } else {
  18776. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  18777. }
  18778. }
  18779. if ( direction_eq ) {
  18780. // console.log("Warning: lines are a straight sequence");
  18781. v_trans_x = -v_prev_y;
  18782. v_trans_y = v_prev_x;
  18783. shrink_by = Math.sqrt( v_prev_lensq );
  18784. } else {
  18785. // console.log("Warning: lines are a straight spike");
  18786. v_trans_x = v_prev_x;
  18787. v_trans_y = v_prev_y;
  18788. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18789. }
  18790. }
  18791. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18792. }
  18793. var contourMovements = [];
  18794. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18795. if ( j === il ) j = 0;
  18796. if ( k === il ) k = 0;
  18797. // (j)---(i)---(k)
  18798. // console.log('i,j,k', i, j , k)
  18799. var pt_i = contour[ i ];
  18800. var pt_j = contour[ j ];
  18801. var pt_k = contour[ k ];
  18802. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18803. }
  18804. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18805. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18806. ahole = holes[ h ];
  18807. oneHoleMovements = [];
  18808. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18809. if ( j === il ) j = 0;
  18810. if ( k === il ) k = 0;
  18811. // (j)---(i)---(k)
  18812. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18813. }
  18814. holesMovements.push( oneHoleMovements );
  18815. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18816. }
  18817. // Loop bevelSegments, 1 for the front, 1 for the back
  18818. for ( b = 0; b < bevelSegments; b ++ ) {
  18819. //for ( b = bevelSegments; b > 0; b -- ) {
  18820. t = b / bevelSegments;
  18821. z = bevelThickness * ( 1 - t );
  18822. //z = bevelThickness * t;
  18823. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18824. //bs = bevelSize * t ; // linear
  18825. // contract shape
  18826. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18827. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18828. v( vert.x, vert.y, - z );
  18829. }
  18830. // expand holes
  18831. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18832. ahole = holes[ h ];
  18833. oneHoleMovements = holesMovements[ h ];
  18834. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18835. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18836. v( vert.x, vert.y, -z );
  18837. }
  18838. }
  18839. }
  18840. bs = bevelSize;
  18841. // Back facing vertices
  18842. for ( i = 0; i < vlen; i ++ ) {
  18843. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18844. if ( !extrudeByPath ) {
  18845. v( vert.x, vert.y, 0 );
  18846. } else {
  18847. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18848. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18849. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18850. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18851. v( position2.x, position2.y, position2.z );
  18852. }
  18853. }
  18854. // Add stepped vertices...
  18855. // Including front facing vertices
  18856. var s;
  18857. for ( s = 1; s <= steps; s ++ ) {
  18858. for ( i = 0; i < vlen; i ++ ) {
  18859. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18860. if ( !extrudeByPath ) {
  18861. v( vert.x, vert.y, amount / steps * s );
  18862. } else {
  18863. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18864. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18865. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18866. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18867. v( position2.x, position2.y, position2.z );
  18868. }
  18869. }
  18870. }
  18871. // Add bevel segments planes
  18872. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18873. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18874. t = b / bevelSegments;
  18875. z = bevelThickness * ( 1 - t );
  18876. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18877. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18878. // contract shape
  18879. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18880. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18881. v( vert.x, vert.y, amount + z );
  18882. }
  18883. // expand holes
  18884. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18885. ahole = holes[ h ];
  18886. oneHoleMovements = holesMovements[ h ];
  18887. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18888. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18889. if ( !extrudeByPath ) {
  18890. v( vert.x, vert.y, amount + z );
  18891. } else {
  18892. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18893. }
  18894. }
  18895. }
  18896. }
  18897. /* Faces */
  18898. // Top and bottom faces
  18899. buildLidFaces();
  18900. // Sides faces
  18901. buildSideFaces();
  18902. ///// Internal functions
  18903. function buildLidFaces() {
  18904. if ( bevelEnabled ) {
  18905. var layer = 0 ; // steps + 1
  18906. var offset = vlen * layer;
  18907. // Bottom faces
  18908. for ( i = 0; i < flen; i ++ ) {
  18909. face = faces[ i ];
  18910. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18911. }
  18912. layer = steps + bevelSegments * 2;
  18913. offset = vlen * layer;
  18914. // Top faces
  18915. for ( i = 0; i < flen; i ++ ) {
  18916. face = faces[ i ];
  18917. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18918. }
  18919. } else {
  18920. // Bottom faces
  18921. for ( i = 0; i < flen; i++ ) {
  18922. face = faces[ i ];
  18923. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18924. }
  18925. // Top faces
  18926. for ( i = 0; i < flen; i ++ ) {
  18927. face = faces[ i ];
  18928. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18929. }
  18930. }
  18931. }
  18932. // Create faces for the z-sides of the shape
  18933. function buildSideFaces() {
  18934. var layeroffset = 0;
  18935. sidewalls( contour, layeroffset );
  18936. layeroffset += contour.length;
  18937. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18938. ahole = holes[ h ];
  18939. sidewalls( ahole, layeroffset );
  18940. //, true
  18941. layeroffset += ahole.length;
  18942. }
  18943. }
  18944. function sidewalls( contour, layeroffset ) {
  18945. var j, k;
  18946. i = contour.length;
  18947. while ( --i >= 0 ) {
  18948. j = i;
  18949. k = i - 1;
  18950. if ( k < 0 ) k = contour.length - 1;
  18951. //console.log('b', i,j, i-1, k,vertices.length);
  18952. var s = 0, sl = steps + bevelSegments * 2;
  18953. for ( s = 0; s < sl; s ++ ) {
  18954. var slen1 = vlen * s;
  18955. var slen2 = vlen * ( s + 1 );
  18956. var a = layeroffset + j + slen1,
  18957. b = layeroffset + k + slen1,
  18958. c = layeroffset + k + slen2,
  18959. d = layeroffset + j + slen2;
  18960. f4( a, b, c, d, contour, s, sl, j, k );
  18961. }
  18962. }
  18963. }
  18964. function v( x, y, z ) {
  18965. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18966. }
  18967. function f3( a, b, c, isBottom ) {
  18968. a += shapesOffset;
  18969. b += shapesOffset;
  18970. c += shapesOffset;
  18971. // normal, color, material
  18972. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18973. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18974. scope.faceVertexUvs[ 0 ].push( uvs );
  18975. }
  18976. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18977. a += shapesOffset;
  18978. b += shapesOffset;
  18979. c += shapesOffset;
  18980. d += shapesOffset;
  18981. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  18982. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  18983. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18984. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18985. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18986. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18987. }
  18988. };
  18989. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18990. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18991. var ax = geometry.vertices[ indexA ].x,
  18992. ay = geometry.vertices[ indexA ].y,
  18993. bx = geometry.vertices[ indexB ].x,
  18994. by = geometry.vertices[ indexB ].y,
  18995. cx = geometry.vertices[ indexC ].x,
  18996. cy = geometry.vertices[ indexC ].y;
  18997. return [
  18998. new THREE.Vector2( ax, ay ),
  18999. new THREE.Vector2( bx, by ),
  19000. new THREE.Vector2( cx, cy )
  19001. ];
  19002. },
  19003. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19004. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19005. },
  19006. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19007. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19008. contourIndex1, contourIndex2 ) {
  19009. var ax = geometry.vertices[ indexA ].x,
  19010. ay = geometry.vertices[ indexA ].y,
  19011. az = geometry.vertices[ indexA ].z,
  19012. bx = geometry.vertices[ indexB ].x,
  19013. by = geometry.vertices[ indexB ].y,
  19014. bz = geometry.vertices[ indexB ].z,
  19015. cx = geometry.vertices[ indexC ].x,
  19016. cy = geometry.vertices[ indexC ].y,
  19017. cz = geometry.vertices[ indexC ].z,
  19018. dx = geometry.vertices[ indexD ].x,
  19019. dy = geometry.vertices[ indexD ].y,
  19020. dz = geometry.vertices[ indexD ].z;
  19021. if ( Math.abs( ay - by ) < 0.01 ) {
  19022. return [
  19023. new THREE.Vector2( ax, 1 - az ),
  19024. new THREE.Vector2( bx, 1 - bz ),
  19025. new THREE.Vector2( cx, 1 - cz ),
  19026. new THREE.Vector2( dx, 1 - dz )
  19027. ];
  19028. } else {
  19029. return [
  19030. new THREE.Vector2( ay, 1 - az ),
  19031. new THREE.Vector2( by, 1 - bz ),
  19032. new THREE.Vector2( cy, 1 - cz ),
  19033. new THREE.Vector2( dy, 1 - dz )
  19034. ];
  19035. }
  19036. }
  19037. };
  19038. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19039. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19040. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19041. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19042. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19043. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19044. /**
  19045. * @author jonobr1 / http://jonobr1.com
  19046. *
  19047. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19048. * ExtrudeGeometry.
  19049. *
  19050. * parameters = {
  19051. *
  19052. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19053. *
  19054. * material: <int> // material index for front and back faces
  19055. * uvGenerator: <Object> // object that provides UV generator functions
  19056. *
  19057. * }
  19058. **/
  19059. THREE.ShapeGeometry = function ( shapes, options ) {
  19060. THREE.Geometry.call( this );
  19061. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19062. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19063. this.addShapeList( shapes, options );
  19064. this.computeFaceNormals();
  19065. };
  19066. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19067. /**
  19068. * Add an array of shapes to THREE.ShapeGeometry.
  19069. */
  19070. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19071. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19072. this.addShape( shapes[ i ], options );
  19073. }
  19074. return this;
  19075. };
  19076. /**
  19077. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19078. */
  19079. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19080. if ( options === undefined ) options = {};
  19081. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19082. var material = options.material;
  19083. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19084. var shapebb = this.shapebb;
  19085. //
  19086. var i, l, hole, s;
  19087. var shapesOffset = this.vertices.length;
  19088. var shapePoints = shape.extractPoints( curveSegments );
  19089. var vertices = shapePoints.shape;
  19090. var holes = shapePoints.holes;
  19091. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19092. if ( reverse ) {
  19093. vertices = vertices.reverse();
  19094. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19095. for ( i = 0, l = holes.length; i < l; i++ ) {
  19096. hole = holes[ i ];
  19097. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19098. holes[ i ] = hole.reverse();
  19099. }
  19100. }
  19101. reverse = false;
  19102. }
  19103. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19104. // Vertices
  19105. var contour = vertices;
  19106. for ( i = 0, l = holes.length; i < l; i++ ) {
  19107. hole = holes[ i ];
  19108. vertices = vertices.concat( hole );
  19109. }
  19110. //
  19111. var vert, vlen = vertices.length;
  19112. var face, flen = faces.length;
  19113. var cont, clen = contour.length;
  19114. for ( i = 0; i < vlen; i++ ) {
  19115. vert = vertices[ i ];
  19116. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19117. }
  19118. for ( i = 0; i < flen; i++ ) {
  19119. face = faces[ i ];
  19120. var a = face[ 0 ] + shapesOffset;
  19121. var b = face[ 1 ] + shapesOffset;
  19122. var c = face[ 2 ] + shapesOffset;
  19123. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19124. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19125. }
  19126. };
  19127. /**
  19128. * @author astrodud / http://astrodud.isgreat.org/
  19129. * @author zz85 / https://github.com/zz85
  19130. * @author bhouston / http://exocortex.com
  19131. */
  19132. // points - to create a closed torus, one must use a set of points
  19133. // like so: [ a, b, c, d, a ], see first is the same as last.
  19134. // segments - the number of circumference segments to create
  19135. // phiStart - the starting radian
  19136. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19137. // 2*pi is a closed lathe, less than 2PI is a portion.
  19138. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19139. THREE.Geometry.call( this );
  19140. segments = segments || 12;
  19141. phiStart = phiStart || 0;
  19142. phiLength = phiLength || 2 * Math.PI;
  19143. var inversePointLength = 1.0 / ( points.length - 1 );
  19144. var inverseSegments = 1.0 / segments;
  19145. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19146. var phi = phiStart + i * inverseSegments * phiLength;
  19147. var c = Math.cos( phi ),
  19148. s = Math.sin( phi );
  19149. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19150. var pt = points[ j ];
  19151. var vertex = new THREE.Vector3();
  19152. vertex.x = c * pt.x - s * pt.y;
  19153. vertex.y = s * pt.x + c * pt.y;
  19154. vertex.z = pt.z;
  19155. this.vertices.push( vertex );
  19156. }
  19157. }
  19158. var np = points.length;
  19159. for ( var i = 0, il = segments; i < il; i ++ ) {
  19160. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19161. var base = j + np * i;
  19162. var a = base;
  19163. var b = base + np;
  19164. var c = base + 1 + np;
  19165. var d = base + 1;
  19166. var u0 = i * inverseSegments;
  19167. var v0 = j * inversePointLength;
  19168. var u1 = u0 + inverseSegments;
  19169. var v1 = v0 + inversePointLength;
  19170. this.faces.push( new THREE.Face3( a, b, d ) );
  19171. this.faceVertexUvs[ 0 ].push( [
  19172. new THREE.Vector2( u0, v0 ),
  19173. new THREE.Vector2( u1, v0 ),
  19174. new THREE.Vector2( u0, v1 )
  19175. ] );
  19176. this.faces.push( new THREE.Face3( b, c, d ) );
  19177. this.faceVertexUvs[ 0 ].push( [
  19178. new THREE.Vector2( u1, v0 ),
  19179. new THREE.Vector2( u1, v1 ),
  19180. new THREE.Vector2( u0, v1 )
  19181. ] );
  19182. }
  19183. }
  19184. this.mergeVertices();
  19185. this.computeFaceNormals();
  19186. this.computeVertexNormals();
  19187. };
  19188. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19189. /**
  19190. * @author mrdoob / http://mrdoob.com/
  19191. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19192. */
  19193. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19194. THREE.Geometry.call( this );
  19195. this.parameters = {
  19196. width: width,
  19197. height: height,
  19198. widthSegments: widthSegments,
  19199. heightSegments: heightSegments
  19200. };
  19201. var ix, iz;
  19202. var width_half = width / 2;
  19203. var height_half = height / 2;
  19204. var gridX = widthSegments || 1;
  19205. var gridZ = heightSegments || 1;
  19206. var gridX1 = gridX + 1;
  19207. var gridZ1 = gridZ + 1;
  19208. var segment_width = width / gridX;
  19209. var segment_height = height / gridZ;
  19210. var normal = new THREE.Vector3( 0, 0, 1 );
  19211. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19212. var y = iz * segment_height - height_half;
  19213. for ( ix = 0; ix < gridX1; ix ++ ) {
  19214. var x = ix * segment_width - width_half;
  19215. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19216. }
  19217. }
  19218. for ( iz = 0; iz < gridZ; iz ++ ) {
  19219. for ( ix = 0; ix < gridX; ix ++ ) {
  19220. var a = ix + gridX1 * iz;
  19221. var b = ix + gridX1 * ( iz + 1 );
  19222. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19223. var d = ( ix + 1 ) + gridX1 * iz;
  19224. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19225. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19226. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19227. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19228. var face = new THREE.Face3( a, b, d );
  19229. face.normal.copy( normal );
  19230. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19231. this.faces.push( face );
  19232. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19233. face = new THREE.Face3( b, c, d );
  19234. face.normal.copy( normal );
  19235. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19236. this.faces.push( face );
  19237. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19238. }
  19239. }
  19240. };
  19241. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19242. /**
  19243. * @author Kaleb Murphy
  19244. */
  19245. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19246. THREE.Geometry.call( this );
  19247. innerRadius = innerRadius || 0;
  19248. outerRadius = outerRadius || 50;
  19249. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19250. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19251. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19252. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19253. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19254. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19255. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19256. var vertex = new THREE.Vector3();
  19257. var segment = thetaStart + o / thetaSegments * thetaLength;
  19258. vertex.x = radius * Math.cos( segment );
  19259. vertex.y = radius * Math.sin( segment );
  19260. this.vertices.push( vertex );
  19261. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19262. }
  19263. radius += radiusStep;
  19264. }
  19265. var n = new THREE.Vector3( 0, 0, 1 );
  19266. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19267. var thetaSegment = i * thetaSegments;
  19268. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19269. var segment = o + thetaSegment;
  19270. var v1 = segment + i;
  19271. var v2 = segment + thetaSegments + i;
  19272. var v3 = segment + thetaSegments + 1 + i;
  19273. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19274. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19275. v1 = segment + i;
  19276. v2 = segment + thetaSegments + 1 + i;
  19277. v3 = segment + 1 + i;
  19278. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19279. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19280. }
  19281. }
  19282. this.computeFaceNormals();
  19283. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19284. };
  19285. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19286. /**
  19287. * @author mrdoob / http://mrdoob.com/
  19288. */
  19289. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19290. THREE.Geometry.call( this );
  19291. this.parameters = {
  19292. radius: radius,
  19293. widthSegments: widthSegments,
  19294. heightSegments: heightSegments,
  19295. phiStart: phiStart,
  19296. phiLength: phiLength,
  19297. thetaStart: thetaStart,
  19298. thetaLength: thetaLength
  19299. };
  19300. radius = radius || 50;
  19301. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19302. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19303. phiStart = phiStart !== undefined ? phiStart : 0;
  19304. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19305. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19306. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19307. var x, y, vertices = [], uvs = [];
  19308. for ( y = 0; y <= heightSegments; y ++ ) {
  19309. var verticesRow = [];
  19310. var uvsRow = [];
  19311. for ( x = 0; x <= widthSegments; x ++ ) {
  19312. var u = x / widthSegments;
  19313. var v = y / heightSegments;
  19314. var vertex = new THREE.Vector3();
  19315. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19316. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19317. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19318. this.vertices.push( vertex );
  19319. verticesRow.push( this.vertices.length - 1 );
  19320. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19321. }
  19322. vertices.push( verticesRow );
  19323. uvs.push( uvsRow );
  19324. }
  19325. for ( y = 0; y < heightSegments; y ++ ) {
  19326. for ( x = 0; x < widthSegments; x ++ ) {
  19327. var v1 = vertices[ y ][ x + 1 ];
  19328. var v2 = vertices[ y ][ x ];
  19329. var v3 = vertices[ y + 1 ][ x ];
  19330. var v4 = vertices[ y + 1 ][ x + 1 ];
  19331. var n1 = this.vertices[ v1 ].clone().normalize();
  19332. var n2 = this.vertices[ v2 ].clone().normalize();
  19333. var n3 = this.vertices[ v3 ].clone().normalize();
  19334. var n4 = this.vertices[ v4 ].clone().normalize();
  19335. var uv1 = uvs[ y ][ x + 1 ].clone();
  19336. var uv2 = uvs[ y ][ x ].clone();
  19337. var uv3 = uvs[ y + 1 ][ x ].clone();
  19338. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19339. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19340. uv1.x = ( uv1.x + uv2.x ) / 2;
  19341. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19342. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19343. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19344. uv3.x = ( uv3.x + uv4.x ) / 2;
  19345. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19346. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19347. } else {
  19348. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19349. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19350. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19351. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19352. }
  19353. }
  19354. }
  19355. this.computeFaceNormals();
  19356. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19357. };
  19358. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19359. /**
  19360. * @author zz85 / http://www.lab4games.net/zz85/blog
  19361. * @author alteredq / http://alteredqualia.com/
  19362. *
  19363. * For creating 3D text geometry in three.js
  19364. *
  19365. * Text = 3D Text
  19366. *
  19367. * parameters = {
  19368. * size: <float>, // size of the text
  19369. * height: <float>, // thickness to extrude text
  19370. * curveSegments: <int>, // number of points on the curves
  19371. *
  19372. * font: <string>, // font name
  19373. * weight: <string>, // font weight (normal, bold)
  19374. * style: <string>, // font style (normal, italics)
  19375. *
  19376. * bevelEnabled: <bool>, // turn on bevel
  19377. * bevelThickness: <float>, // how deep into text bevel goes
  19378. * bevelSize: <float>, // how far from text outline is bevel
  19379. * }
  19380. *
  19381. */
  19382. /* Usage Examples
  19383. // TextGeometry wrapper
  19384. var text3d = new TextGeometry( text, options );
  19385. // Complete manner
  19386. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19387. var text3d = new ExtrudeGeometry( textShapes, options );
  19388. */
  19389. THREE.TextGeometry = function ( text, parameters ) {
  19390. parameters = parameters || {};
  19391. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19392. // translate parameters to ExtrudeGeometry API
  19393. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19394. // defaults
  19395. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19396. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19397. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19398. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19399. };
  19400. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19401. /**
  19402. * @author oosmoxiecode
  19403. * @author mrdoob / http://mrdoob.com/
  19404. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19405. */
  19406. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19407. THREE.Geometry.call( this );
  19408. this.parameters = {
  19409. radius: radius,
  19410. tube: tube,
  19411. radialSegments: radialSegments,
  19412. tubularSegments: tubularSegments,
  19413. arc: arc
  19414. };
  19415. radius = radius || 100;
  19416. tube = tube || 40;
  19417. radialSegments = radialSegments || 8;
  19418. tubularSegments = tubularSegments || 6;
  19419. arc = arc || Math.PI * 2;
  19420. var center = new THREE.Vector3(), uvs = [], normals = [];
  19421. for ( var j = 0; j <= radialSegments; j ++ ) {
  19422. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19423. var u = i / tubularSegments * arc;
  19424. var v = j / radialSegments * Math.PI * 2;
  19425. center.x = radius * Math.cos( u );
  19426. center.y = radius * Math.sin( u );
  19427. var vertex = new THREE.Vector3();
  19428. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19429. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19430. vertex.z = tube * Math.sin( v );
  19431. this.vertices.push( vertex );
  19432. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19433. normals.push( vertex.clone().sub( center ).normalize() );
  19434. }
  19435. }
  19436. for ( var j = 1; j <= radialSegments; j ++ ) {
  19437. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19438. var a = ( tubularSegments + 1 ) * j + i - 1;
  19439. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19440. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19441. var d = ( tubularSegments + 1 ) * j + i;
  19442. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19443. this.faces.push( face );
  19444. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19445. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19446. this.faces.push( face );
  19447. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19448. }
  19449. }
  19450. this.computeFaceNormals();
  19451. };
  19452. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19453. /**
  19454. * @author oosmoxiecode
  19455. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19456. */
  19457. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19458. THREE.Geometry.call( this );
  19459. this.parameters = {
  19460. radius: radius,
  19461. tube: tube,
  19462. radialSegments: radialSegments,
  19463. tubularSegments: tubularSegments,
  19464. p: p,
  19465. q: q,
  19466. heightScale: heightScale
  19467. };
  19468. radius = radius || 100;
  19469. tube = tube || 40;
  19470. radialSegments = radialSegments || 64;
  19471. tubularSegments = tubularSegments || 8;
  19472. p = p || 2;
  19473. q = q || 3;
  19474. heightScale = heightScale || 1;
  19475. var grid = new Array( radialSegments );
  19476. var tang = new THREE.Vector3();
  19477. var n = new THREE.Vector3();
  19478. var bitan = new THREE.Vector3();
  19479. for ( var i = 0; i < radialSegments; ++ i ) {
  19480. grid[ i ] = new Array( tubularSegments );
  19481. var u = i / radialSegments * 2 * p * Math.PI;
  19482. var p1 = getPos( u, q, p, radius, heightScale );
  19483. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19484. tang.subVectors( p2, p1 );
  19485. n.addVectors( p2, p1 );
  19486. bitan.crossVectors( tang, n );
  19487. n.crossVectors( bitan, tang );
  19488. bitan.normalize();
  19489. n.normalize();
  19490. for ( var j = 0; j < tubularSegments; ++ j ) {
  19491. var v = j / tubularSegments * 2 * Math.PI;
  19492. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19493. var cy = tube * Math.sin( v );
  19494. var pos = new THREE.Vector3();
  19495. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19496. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19497. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19498. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19499. }
  19500. }
  19501. for ( var i = 0; i < radialSegments; ++ i ) {
  19502. for ( var j = 0; j < tubularSegments; ++ j ) {
  19503. var ip = ( i + 1 ) % radialSegments;
  19504. var jp = ( j + 1 ) % tubularSegments;
  19505. var a = grid[ i ][ j ];
  19506. var b = grid[ ip ][ j ];
  19507. var c = grid[ ip ][ jp ];
  19508. var d = grid[ i ][ jp ];
  19509. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19510. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19511. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19512. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19513. this.faces.push( new THREE.Face3( a, b, d ) );
  19514. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19515. this.faces.push( new THREE.Face3( b, c, d ) );
  19516. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19517. }
  19518. }
  19519. this.computeFaceNormals();
  19520. this.computeVertexNormals();
  19521. function getPos( u, in_q, in_p, radius, heightScale ) {
  19522. var cu = Math.cos( u );
  19523. var su = Math.sin( u );
  19524. var quOverP = in_q / in_p * u;
  19525. var cs = Math.cos( quOverP );
  19526. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19527. var ty = radius * ( 2 + cs ) * su * 0.5;
  19528. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19529. return new THREE.Vector3( tx, ty, tz );
  19530. }
  19531. };
  19532. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19533. /**
  19534. * @author WestLangley / https://github.com/WestLangley
  19535. * @author zz85 / https://github.com/zz85
  19536. * @author miningold / https://github.com/miningold
  19537. *
  19538. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19539. *
  19540. * Creates a tube which extrudes along a 3d spline
  19541. *
  19542. * Uses parallel transport frames as described in
  19543. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19544. */
  19545. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  19546. THREE.Geometry.call( this );
  19547. this.parameters = {
  19548. path: path,
  19549. segments: segments,
  19550. radius: radius,
  19551. radialSegments: radialSegments,
  19552. closed: closed
  19553. };
  19554. segments = segments || 64;
  19555. radius = radius || 1;
  19556. radialSegments = radialSegments || 8;
  19557. closed = closed || false;
  19558. var grid = [];
  19559. var scope = this,
  19560. tangent,
  19561. normal,
  19562. binormal,
  19563. numpoints = segments + 1,
  19564. x, y, z,
  19565. tx, ty, tz,
  19566. u, v,
  19567. cx, cy,
  19568. pos, pos2 = new THREE.Vector3(),
  19569. i, j,
  19570. ip, jp,
  19571. a, b, c, d,
  19572. uva, uvb, uvc, uvd;
  19573. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19574. tangents = frames.tangents,
  19575. normals = frames.normals,
  19576. binormals = frames.binormals;
  19577. // proxy internals
  19578. this.tangents = tangents;
  19579. this.normals = normals;
  19580. this.binormals = binormals;
  19581. function vert( x, y, z ) {
  19582. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19583. }
  19584. // consruct the grid
  19585. for ( i = 0; i < numpoints; i++ ) {
  19586. grid[ i ] = [];
  19587. u = i / ( numpoints - 1 );
  19588. pos = path.getPointAt( u );
  19589. tangent = tangents[ i ];
  19590. normal = normals[ i ];
  19591. binormal = binormals[ i ];
  19592. for ( j = 0; j < radialSegments; j++ ) {
  19593. v = j / radialSegments * 2 * Math.PI;
  19594. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19595. cy = radius * Math.sin( v );
  19596. pos2.copy( pos );
  19597. pos2.x += cx * normal.x + cy * binormal.x;
  19598. pos2.y += cx * normal.y + cy * binormal.y;
  19599. pos2.z += cx * normal.z + cy * binormal.z;
  19600. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19601. }
  19602. }
  19603. // construct the mesh
  19604. for ( i = 0; i < segments; i++ ) {
  19605. for ( j = 0; j < radialSegments; j++ ) {
  19606. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19607. jp = (j + 1) % radialSegments;
  19608. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19609. b = grid[ ip ][ j ];
  19610. c = grid[ ip ][ jp ];
  19611. d = grid[ i ][ jp ];
  19612. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19613. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19614. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19615. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19616. this.faces.push( new THREE.Face3( a, b, d ) );
  19617. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19618. this.faces.push( new THREE.Face3( b, c, d ) );
  19619. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19620. }
  19621. }
  19622. this.computeFaceNormals();
  19623. this.computeVertexNormals();
  19624. };
  19625. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19626. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19627. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19628. var tangent = new THREE.Vector3(),
  19629. normal = new THREE.Vector3(),
  19630. binormal = new THREE.Vector3(),
  19631. tangents = [],
  19632. normals = [],
  19633. binormals = [],
  19634. vec = new THREE.Vector3(),
  19635. mat = new THREE.Matrix4(),
  19636. numpoints = segments + 1,
  19637. theta,
  19638. epsilon = 0.0001,
  19639. smallest,
  19640. tx, ty, tz,
  19641. i, u, v;
  19642. // expose internals
  19643. this.tangents = tangents;
  19644. this.normals = normals;
  19645. this.binormals = binormals;
  19646. // compute the tangent vectors for each segment on the path
  19647. for ( i = 0; i < numpoints; i++ ) {
  19648. u = i / ( numpoints - 1 );
  19649. tangents[ i ] = path.getTangentAt( u );
  19650. tangents[ i ].normalize();
  19651. }
  19652. initialNormal3();
  19653. function initialNormal1(lastBinormal) {
  19654. // fixed start binormal. Has dangers of 0 vectors
  19655. normals[ 0 ] = new THREE.Vector3();
  19656. binormals[ 0 ] = new THREE.Vector3();
  19657. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19658. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19659. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19660. }
  19661. function initialNormal2() {
  19662. // This uses the Frenet-Serret formula for deriving binormal
  19663. var t2 = path.getTangentAt( epsilon );
  19664. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19665. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19666. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19667. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19668. }
  19669. function initialNormal3() {
  19670. // select an initial normal vector perpenicular to the first tangent vector,
  19671. // and in the direction of the smallest tangent xyz component
  19672. normals[ 0 ] = new THREE.Vector3();
  19673. binormals[ 0 ] = new THREE.Vector3();
  19674. smallest = Number.MAX_VALUE;
  19675. tx = Math.abs( tangents[ 0 ].x );
  19676. ty = Math.abs( tangents[ 0 ].y );
  19677. tz = Math.abs( tangents[ 0 ].z );
  19678. if ( tx <= smallest ) {
  19679. smallest = tx;
  19680. normal.set( 1, 0, 0 );
  19681. }
  19682. if ( ty <= smallest ) {
  19683. smallest = ty;
  19684. normal.set( 0, 1, 0 );
  19685. }
  19686. if ( tz <= smallest ) {
  19687. normal.set( 0, 0, 1 );
  19688. }
  19689. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19690. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19691. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19692. }
  19693. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19694. for ( i = 1; i < numpoints; i++ ) {
  19695. normals[ i ] = normals[ i-1 ].clone();
  19696. binormals[ i ] = binormals[ i-1 ].clone();
  19697. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19698. if ( vec.length() > epsilon ) {
  19699. vec.normalize();
  19700. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19701. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19702. }
  19703. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19704. }
  19705. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19706. if ( closed ) {
  19707. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19708. theta /= ( numpoints - 1 );
  19709. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19710. theta = -theta;
  19711. }
  19712. for ( i = 1; i < numpoints; i++ ) {
  19713. // twist a little...
  19714. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19715. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19716. }
  19717. }
  19718. };
  19719. /**
  19720. * @author clockworkgeek / https://github.com/clockworkgeek
  19721. * @author timothypratley / https://github.com/timothypratley
  19722. * @author WestLangley / http://github.com/WestLangley
  19723. */
  19724. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19725. THREE.Geometry.call( this );
  19726. radius = radius || 1;
  19727. detail = detail || 0;
  19728. var that = this;
  19729. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19730. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19731. }
  19732. var midpoints = [], p = this.vertices;
  19733. var faces = [];
  19734. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19735. var v1 = p[ indices[ i ] ];
  19736. var v2 = p[ indices[ i + 1 ] ];
  19737. var v3 = p[ indices[ i + 2 ] ];
  19738. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19739. }
  19740. var centroid = new THREE.Vector3();
  19741. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19742. subdivide( faces[ i ], detail );
  19743. }
  19744. // Handle case when face straddles the seam
  19745. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19746. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19747. var x0 = uvs[ 0 ].x;
  19748. var x1 = uvs[ 1 ].x;
  19749. var x2 = uvs[ 2 ].x;
  19750. var max = Math.max( x0, Math.max( x1, x2 ) );
  19751. var min = Math.min( x0, Math.min( x1, x2 ) );
  19752. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19753. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19754. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19755. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19756. }
  19757. }
  19758. // Apply radius
  19759. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19760. this.vertices[ i ].multiplyScalar( radius );
  19761. }
  19762. // Merge vertices
  19763. this.mergeVertices();
  19764. this.computeFaceNormals();
  19765. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19766. // Project vector onto sphere's surface
  19767. function prepare( vector ) {
  19768. var vertex = vector.normalize().clone();
  19769. vertex.index = that.vertices.push( vertex ) - 1;
  19770. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19771. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19772. var v = inclination( vector ) / Math.PI + 0.5;
  19773. vertex.uv = new THREE.Vector2( u, 1 - v );
  19774. return vertex;
  19775. }
  19776. // Approximate a curved face with recursively sub-divided triangles.
  19777. function make( v1, v2, v3 ) {
  19778. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19779. that.faces.push( face );
  19780. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19781. var azi = azimuth( centroid );
  19782. that.faceVertexUvs[ 0 ].push( [
  19783. correctUV( v1.uv, v1, azi ),
  19784. correctUV( v2.uv, v2, azi ),
  19785. correctUV( v3.uv, v3, azi )
  19786. ] );
  19787. }
  19788. // Analytically subdivide a face to the required detail level.
  19789. function subdivide( face, detail ) {
  19790. var cols = Math.pow(2, detail);
  19791. var cells = Math.pow(4, detail);
  19792. var a = prepare( that.vertices[ face.a ] );
  19793. var b = prepare( that.vertices[ face.b ] );
  19794. var c = prepare( that.vertices[ face.c ] );
  19795. var v = [];
  19796. // Construct all of the vertices for this subdivision.
  19797. for ( var i = 0 ; i <= cols; i ++ ) {
  19798. v[ i ] = [];
  19799. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19800. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19801. var rows = cols - i;
  19802. for ( var j = 0; j <= rows; j ++) {
  19803. if ( j == 0 && i == cols ) {
  19804. v[ i ][ j ] = aj;
  19805. } else {
  19806. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19807. }
  19808. }
  19809. }
  19810. // Construct all of the faces.
  19811. for ( var i = 0; i < cols ; i ++ ) {
  19812. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19813. var k = Math.floor( j / 2 );
  19814. if ( j % 2 == 0 ) {
  19815. make(
  19816. v[ i ][ k + 1],
  19817. v[ i + 1 ][ k ],
  19818. v[ i ][ k ]
  19819. );
  19820. } else {
  19821. make(
  19822. v[ i ][ k + 1 ],
  19823. v[ i + 1][ k + 1],
  19824. v[ i + 1 ][ k ]
  19825. );
  19826. }
  19827. }
  19828. }
  19829. }
  19830. // Angle around the Y axis, counter-clockwise when looking from above.
  19831. function azimuth( vector ) {
  19832. return Math.atan2( vector.z, -vector.x );
  19833. }
  19834. // Angle above the XZ plane.
  19835. function inclination( vector ) {
  19836. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19837. }
  19838. // Texture fixing helper. Spheres have some odd behaviours.
  19839. function correctUV( uv, vector, azimuth ) {
  19840. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19841. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19842. return uv.clone();
  19843. }
  19844. };
  19845. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19846. /**
  19847. * @author timothypratley / https://github.com/timothypratley
  19848. */
  19849. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19850. this.parameters = {
  19851. radius: radius,
  19852. detail: detail
  19853. };
  19854. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19855. var vertices = [
  19856. -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  19857. 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
  19858. t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
  19859. ];
  19860. var indices = [
  19861. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19862. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19863. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19864. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19865. ];
  19866. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19867. };
  19868. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19869. /**
  19870. * @author timothypratley / https://github.com/timothypratley
  19871. */
  19872. THREE.OctahedronGeometry = function ( radius, detail ) {
  19873. this.parameters = {
  19874. radius: radius,
  19875. detail: detail
  19876. };
  19877. var vertices = [
  19878. 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1
  19879. ];
  19880. var indices = [
  19881. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19882. ];
  19883. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19884. };
  19885. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19886. /**
  19887. * @author timothypratley / https://github.com/timothypratley
  19888. */
  19889. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19890. var vertices = [
  19891. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  19892. ];
  19893. var indices = [
  19894. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19895. ];
  19896. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19897. };
  19898. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19899. /**
  19900. * @author zz85 / https://github.com/zz85
  19901. * Parametric Surfaces Geometry
  19902. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19903. *
  19904. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19905. *
  19906. */
  19907. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19908. THREE.Geometry.call( this );
  19909. var verts = this.vertices;
  19910. var faces = this.faces;
  19911. var uvs = this.faceVertexUvs[ 0 ];
  19912. var i, il, j, p;
  19913. var u, v;
  19914. var stackCount = stacks + 1;
  19915. var sliceCount = slices + 1;
  19916. for ( i = 0; i <= stacks; i ++ ) {
  19917. v = i / stacks;
  19918. for ( j = 0; j <= slices; j ++ ) {
  19919. u = j / slices;
  19920. p = func( u, v );
  19921. verts.push( p );
  19922. }
  19923. }
  19924. var a, b, c, d;
  19925. var uva, uvb, uvc, uvd;
  19926. for ( i = 0; i < stacks; i ++ ) {
  19927. for ( j = 0; j < slices; j ++ ) {
  19928. a = i * sliceCount + j;
  19929. b = i * sliceCount + j + 1;
  19930. c = (i + 1) * sliceCount + j + 1;
  19931. d = (i + 1) * sliceCount + j;
  19932. uva = new THREE.Vector2( j / slices, i / stacks );
  19933. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19934. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19935. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19936. faces.push( new THREE.Face3( a, b, d ) );
  19937. uvs.push( [ uva, uvb, uvd ] );
  19938. faces.push( new THREE.Face3( b, c, d ) );
  19939. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  19940. }
  19941. }
  19942. // console.log(this);
  19943. // magic bullet
  19944. // var diff = this.mergeVertices();
  19945. // console.log('removed ', diff, ' vertices by merging');
  19946. this.computeFaceNormals();
  19947. this.computeVertexNormals();
  19948. };
  19949. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19950. /**
  19951. * @author sroucheray / http://sroucheray.org/
  19952. * @author mrdoob / http://mrdoob.com/
  19953. */
  19954. THREE.AxisHelper = function ( size ) {
  19955. size = size || 1;
  19956. var vertices = new Float32Array( [
  19957. 0, 0, 0, size, 0, 0,
  19958. 0, 0, 0, 0, size, 0,
  19959. 0, 0, 0, 0, 0, size
  19960. ] );
  19961. var colors = new Float32Array( [
  19962. 1, 0, 0, 1, 0.6, 0,
  19963. 0, 1, 0, 0.6, 1, 0,
  19964. 0, 0, 1, 0, 0.6, 1
  19965. ] );
  19966. var geometry = new THREE.BufferGeometry();
  19967. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19968. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  19969. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19970. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19971. };
  19972. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19973. /**
  19974. * @author WestLangley / http://github.com/WestLangley
  19975. * @author zz85 / http://github.com/zz85
  19976. * @author bhouston / http://exocortex.com
  19977. *
  19978. * Creates an arrow for visualizing directions
  19979. *
  19980. * Parameters:
  19981. * dir - Vector3
  19982. * origin - Vector3
  19983. * length - Number
  19984. * color - color in hex value
  19985. * headLength - Number
  19986. * headWidth - Number
  19987. */
  19988. THREE.ArrowHelper = ( function () {
  19989. var lineGeometry = new THREE.Geometry();
  19990. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  19991. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  19992. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  19993. return function ( dir, origin, length, color, headLength, headWidth ) {
  19994. // dir is assumed to be normalized
  19995. THREE.Object3D.call( this );
  19996. if ( color === undefined ) color = 0xffff00;
  19997. if ( length === undefined ) length = 1;
  19998. if ( headLength === undefined ) headLength = 0.2 * length;
  19999. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20000. this.position.copy( origin );
  20001. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20002. this.line.matrixAutoUpdate = false;
  20003. this.add( this.line );
  20004. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20005. this.cone.matrixAutoUpdate = false;
  20006. this.add( this.cone );
  20007. this.setDirection( dir );
  20008. this.setLength( length, headLength, headWidth );
  20009. }
  20010. }() );
  20011. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20012. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20013. var axis = new THREE.Vector3();
  20014. var radians;
  20015. return function ( dir ) {
  20016. // dir is assumed to be normalized
  20017. if ( dir.y > 0.99999 ) {
  20018. this.quaternion.set( 0, 0, 0, 1 );
  20019. } else if ( dir.y < - 0.99999 ) {
  20020. this.quaternion.set( 1, 0, 0, 0 );
  20021. } else {
  20022. axis.set( dir.z, 0, - dir.x ).normalize();
  20023. radians = Math.acos( dir.y );
  20024. this.quaternion.setFromAxisAngle( axis, radians );
  20025. }
  20026. };
  20027. }() );
  20028. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20029. if ( headLength === undefined ) headLength = 0.2 * length;
  20030. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20031. this.line.scale.set( 1, length, 1 );
  20032. this.line.updateMatrix();
  20033. this.cone.scale.set( headWidth, headLength, headWidth );
  20034. this.cone.position.y = length;
  20035. this.cone.updateMatrix();
  20036. };
  20037. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20038. this.line.material.color.set( color );
  20039. this.cone.material.color.set( color );
  20040. };
  20041. /**
  20042. * @author mrdoob / http://mrdoob.com/
  20043. */
  20044. THREE.BoxHelper = function ( object ) {
  20045. // 5____4
  20046. // 1/___0/|
  20047. // | 6__|_7
  20048. // 2/___3/
  20049. var vertices = [
  20050. new THREE.Vector3( 1, 1, 1 ),
  20051. new THREE.Vector3( - 1, 1, 1 ),
  20052. new THREE.Vector3( - 1, - 1, 1 ),
  20053. new THREE.Vector3( 1, - 1, 1 ),
  20054. new THREE.Vector3( 1, 1, - 1 ),
  20055. new THREE.Vector3( - 1, 1, - 1 ),
  20056. new THREE.Vector3( - 1, - 1, - 1 ),
  20057. new THREE.Vector3( 1, - 1, - 1 )
  20058. ];
  20059. this.vertices = vertices;
  20060. // TODO: Wouldn't be nice if Line had .segments?
  20061. var geometry = new THREE.Geometry();
  20062. geometry.vertices.push(
  20063. vertices[ 0 ], vertices[ 1 ],
  20064. vertices[ 1 ], vertices[ 2 ],
  20065. vertices[ 2 ], vertices[ 3 ],
  20066. vertices[ 3 ], vertices[ 0 ],
  20067. vertices[ 4 ], vertices[ 5 ],
  20068. vertices[ 5 ], vertices[ 6 ],
  20069. vertices[ 6 ], vertices[ 7 ],
  20070. vertices[ 7 ], vertices[ 4 ],
  20071. vertices[ 0 ], vertices[ 4 ],
  20072. vertices[ 1 ], vertices[ 5 ],
  20073. vertices[ 2 ], vertices[ 6 ],
  20074. vertices[ 3 ], vertices[ 7 ]
  20075. );
  20076. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20077. if ( object !== undefined ) {
  20078. this.update( object );
  20079. }
  20080. };
  20081. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20082. THREE.BoxHelper.prototype.update = function ( object ) {
  20083. var geometry = object.geometry;
  20084. if ( geometry.boundingBox === null ) {
  20085. geometry.computeBoundingBox();
  20086. }
  20087. var min = geometry.boundingBox.min;
  20088. var max = geometry.boundingBox.max;
  20089. var vertices = this.vertices;
  20090. vertices[ 0 ].set( max.x, max.y, max.z );
  20091. vertices[ 1 ].set( min.x, max.y, max.z );
  20092. vertices[ 2 ].set( min.x, min.y, max.z );
  20093. vertices[ 3 ].set( max.x, min.y, max.z );
  20094. vertices[ 4 ].set( max.x, max.y, min.z );
  20095. vertices[ 5 ].set( min.x, max.y, min.z );
  20096. vertices[ 6 ].set( min.x, min.y, min.z );
  20097. vertices[ 7 ].set( max.x, min.y, min.z );
  20098. this.geometry.computeBoundingSphere();
  20099. this.geometry.verticesNeedUpdate = true;
  20100. this.matrixAutoUpdate = false;
  20101. this.matrixWorld = object.matrixWorld;
  20102. };
  20103. /**
  20104. * @author WestLangley / http://github.com/WestLangley
  20105. */
  20106. // a helper to show the world-axis-aligned bounding box for an object
  20107. THREE.BoundingBoxHelper = function ( object, hex ) {
  20108. var color = ( hex !== undefined ) ? hex : 0x888888;
  20109. this.object = object;
  20110. this.box = new THREE.Box3();
  20111. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20112. };
  20113. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20114. THREE.BoundingBoxHelper.prototype.update = function () {
  20115. this.box.setFromObject( this.object );
  20116. this.box.size( this.scale );
  20117. this.box.center( this.position );
  20118. };
  20119. /**
  20120. * @author alteredq / http://alteredqualia.com/
  20121. *
  20122. * - shows frustum, line of sight and up of the camera
  20123. * - suitable for fast updates
  20124. * - based on frustum visualization in lightgl.js shadowmap example
  20125. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20126. */
  20127. THREE.CameraHelper = function ( camera ) {
  20128. var geometry = new THREE.Geometry();
  20129. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20130. var pointMap = {};
  20131. // colors
  20132. var hexFrustum = 0xffaa00;
  20133. var hexCone = 0xff0000;
  20134. var hexUp = 0x00aaff;
  20135. var hexTarget = 0xffffff;
  20136. var hexCross = 0x333333;
  20137. // near
  20138. addLine( "n1", "n2", hexFrustum );
  20139. addLine( "n2", "n4", hexFrustum );
  20140. addLine( "n4", "n3", hexFrustum );
  20141. addLine( "n3", "n1", hexFrustum );
  20142. // far
  20143. addLine( "f1", "f2", hexFrustum );
  20144. addLine( "f2", "f4", hexFrustum );
  20145. addLine( "f4", "f3", hexFrustum );
  20146. addLine( "f3", "f1", hexFrustum );
  20147. // sides
  20148. addLine( "n1", "f1", hexFrustum );
  20149. addLine( "n2", "f2", hexFrustum );
  20150. addLine( "n3", "f3", hexFrustum );
  20151. addLine( "n4", "f4", hexFrustum );
  20152. // cone
  20153. addLine( "p", "n1", hexCone );
  20154. addLine( "p", "n2", hexCone );
  20155. addLine( "p", "n3", hexCone );
  20156. addLine( "p", "n4", hexCone );
  20157. // up
  20158. addLine( "u1", "u2", hexUp );
  20159. addLine( "u2", "u3", hexUp );
  20160. addLine( "u3", "u1", hexUp );
  20161. // target
  20162. addLine( "c", "t", hexTarget );
  20163. addLine( "p", "c", hexCross );
  20164. // cross
  20165. addLine( "cn1", "cn2", hexCross );
  20166. addLine( "cn3", "cn4", hexCross );
  20167. addLine( "cf1", "cf2", hexCross );
  20168. addLine( "cf3", "cf4", hexCross );
  20169. function addLine( a, b, hex ) {
  20170. addPoint( a, hex );
  20171. addPoint( b, hex );
  20172. }
  20173. function addPoint( id, hex ) {
  20174. geometry.vertices.push( new THREE.Vector3() );
  20175. geometry.colors.push( new THREE.Color( hex ) );
  20176. if ( pointMap[ id ] === undefined ) {
  20177. pointMap[ id ] = [];
  20178. }
  20179. pointMap[ id ].push( geometry.vertices.length - 1 );
  20180. }
  20181. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20182. this.camera = camera;
  20183. this.matrixWorld = camera.matrixWorld;
  20184. this.matrixAutoUpdate = false;
  20185. this.pointMap = pointMap;
  20186. this.update();
  20187. };
  20188. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20189. THREE.CameraHelper.prototype.update = function () {
  20190. var vector = new THREE.Vector3();
  20191. var camera = new THREE.Camera();
  20192. var projector = new THREE.Projector();
  20193. return function () {
  20194. var scope = this;
  20195. var w = 1, h = 1;
  20196. // we need just camera projection matrix
  20197. // world matrix must be identity
  20198. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20199. // center / target
  20200. setPoint( "c", 0, 0, -1 );
  20201. setPoint( "t", 0, 0, 1 );
  20202. // near
  20203. setPoint( "n1", -w, -h, -1 );
  20204. setPoint( "n2", w, -h, -1 );
  20205. setPoint( "n3", -w, h, -1 );
  20206. setPoint( "n4", w, h, -1 );
  20207. // far
  20208. setPoint( "f1", -w, -h, 1 );
  20209. setPoint( "f2", w, -h, 1 );
  20210. setPoint( "f3", -w, h, 1 );
  20211. setPoint( "f4", w, h, 1 );
  20212. // up
  20213. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20214. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20215. setPoint( "u3", 0, h * 2, -1 );
  20216. // cross
  20217. setPoint( "cf1", -w, 0, 1 );
  20218. setPoint( "cf2", w, 0, 1 );
  20219. setPoint( "cf3", 0, -h, 1 );
  20220. setPoint( "cf4", 0, h, 1 );
  20221. setPoint( "cn1", -w, 0, -1 );
  20222. setPoint( "cn2", w, 0, -1 );
  20223. setPoint( "cn3", 0, -h, -1 );
  20224. setPoint( "cn4", 0, h, -1 );
  20225. function setPoint( point, x, y, z ) {
  20226. vector.set( x, y, z );
  20227. projector.unprojectVector( vector, camera );
  20228. var points = scope.pointMap[ point ];
  20229. if ( points !== undefined ) {
  20230. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20231. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20232. }
  20233. }
  20234. }
  20235. this.geometry.verticesNeedUpdate = true;
  20236. };
  20237. }();
  20238. /**
  20239. * @author alteredq / http://alteredqualia.com/
  20240. * @author mrdoob / http://mrdoob.com/
  20241. * @author WestLangley / http://github.com/WestLangley
  20242. */
  20243. THREE.DirectionalLightHelper = function ( light, size ) {
  20244. THREE.Object3D.call( this );
  20245. this.light = light;
  20246. this.light.updateMatrixWorld();
  20247. this.matrixWorld = light.matrixWorld;
  20248. this.matrixAutoUpdate = false;
  20249. size = size || 1;
  20250. var geometry = new THREE.Geometry();
  20251. geometry.vertices.push(
  20252. new THREE.Vector3( - size, size, 0 ),
  20253. new THREE.Vector3( size, size, 0 ),
  20254. new THREE.Vector3( size, - size, 0 ),
  20255. new THREE.Vector3( - size, - size, 0 ),
  20256. new THREE.Vector3( - size, size, 0 )
  20257. );
  20258. var material = new THREE.LineBasicMaterial( { fog: false } );
  20259. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20260. this.lightPlane = new THREE.Line( geometry, material );
  20261. this.add( this.lightPlane );
  20262. geometry = new THREE.Geometry();
  20263. geometry.vertices.push(
  20264. new THREE.Vector3(),
  20265. new THREE.Vector3()
  20266. );
  20267. material = new THREE.LineBasicMaterial( { fog: false } );
  20268. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20269. this.targetLine = new THREE.Line( geometry, material );
  20270. this.add( this.targetLine );
  20271. this.update();
  20272. };
  20273. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20274. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20275. this.lightPlane.geometry.dispose();
  20276. this.lightPlane.material.dispose();
  20277. this.targetLine.geometry.dispose();
  20278. this.targetLine.material.dispose();
  20279. };
  20280. THREE.DirectionalLightHelper.prototype.update = function () {
  20281. var v1 = new THREE.Vector3();
  20282. var v2 = new THREE.Vector3();
  20283. var v3 = new THREE.Vector3();
  20284. return function () {
  20285. v1.setFromMatrixPosition( this.light.matrixWorld );
  20286. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20287. v3.subVectors( v2, v1 );
  20288. this.lightPlane.lookAt( v3 );
  20289. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20290. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20291. this.targetLine.geometry.verticesNeedUpdate = true;
  20292. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20293. }
  20294. }();
  20295. /**
  20296. * @author WestLangley / http://github.com/WestLangley
  20297. */
  20298. THREE.EdgesHelper = function ( object, hex ) {
  20299. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20300. var edge = [ 0, 0 ], hash = {};
  20301. var sortFunction = function ( a, b ) { return a - b };
  20302. var keys = [ 'a', 'b', 'c' ];
  20303. var geometry = new THREE.BufferGeometry();
  20304. var geometry2 = object.geometry.clone();
  20305. geometry2.mergeVertices();
  20306. geometry2.computeFaceNormals();
  20307. var vertices = geometry2.vertices;
  20308. var faces = geometry2.faces;
  20309. var numEdges = 0;
  20310. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20311. var face = faces[ i ];
  20312. for ( var j = 0; j < 3; j ++ ) {
  20313. edge[ 0 ] = face[ keys[ j ] ];
  20314. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20315. edge.sort( sortFunction );
  20316. var key = edge.toString();
  20317. if ( hash[ key ] === undefined ) {
  20318. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20319. numEdges ++;
  20320. } else {
  20321. hash[ key ].face2 = i;
  20322. }
  20323. }
  20324. }
  20325. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  20326. var coords = geometry.attributes.position.array;
  20327. var index = 0;
  20328. for ( var key in hash ) {
  20329. var h = hash[ key ];
  20330. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20331. var vertex = vertices[ h.vert1 ];
  20332. coords[ index ++ ] = vertex.x;
  20333. coords[ index ++ ] = vertex.y;
  20334. coords[ index ++ ] = vertex.z;
  20335. vertex = vertices[ h.vert2 ];
  20336. coords[ index ++ ] = vertex.x;
  20337. coords[ index ++ ] = vertex.y;
  20338. coords[ index ++ ] = vertex.z;
  20339. }
  20340. }
  20341. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20342. this.matrixAutoUpdate = false;
  20343. this.matrixWorld = object.matrixWorld;
  20344. };
  20345. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20346. /**
  20347. * @author mrdoob / http://mrdoob.com/
  20348. * @author WestLangley / http://github.com/WestLangley
  20349. */
  20350. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20351. this.object = object;
  20352. this.size = ( size !== undefined ) ? size : 1;
  20353. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20354. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20355. var geometry = new THREE.Geometry();
  20356. var faces = this.object.geometry.faces;
  20357. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20358. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20359. }
  20360. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20361. this.matrixAutoUpdate = false;
  20362. this.normalMatrix = new THREE.Matrix3();
  20363. this.update();
  20364. };
  20365. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20366. THREE.FaceNormalsHelper.prototype.update = function () {
  20367. var vertices = this.geometry.vertices;
  20368. var object = this.object;
  20369. var objectVertices = object.geometry.vertices;
  20370. var objectFaces = object.geometry.faces;
  20371. var objectWorldMatrix = object.matrixWorld;
  20372. object.updateMatrixWorld( true );
  20373. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20374. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20375. var face = objectFaces[ i ];
  20376. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20377. .add( objectVertices[ face.b ] )
  20378. .add( objectVertices[ face.c ] )
  20379. .divideScalar( 3 )
  20380. .applyMatrix4( objectWorldMatrix );
  20381. vertices[ i2 + 1 ].copy( face.normal )
  20382. .applyMatrix3( this.normalMatrix )
  20383. .normalize()
  20384. .multiplyScalar( this.size )
  20385. .add( vertices[ i2 ] );
  20386. }
  20387. this.geometry.verticesNeedUpdate = true;
  20388. return this;
  20389. };
  20390. /**
  20391. * @author mrdoob / http://mrdoob.com/
  20392. */
  20393. THREE.GridHelper = function ( size, step ) {
  20394. var geometry = new THREE.Geometry();
  20395. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20396. this.color1 = new THREE.Color( 0x444444 );
  20397. this.color2 = new THREE.Color( 0x888888 );
  20398. for ( var i = - size; i <= size; i += step ) {
  20399. geometry.vertices.push(
  20400. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20401. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20402. );
  20403. var color = i === 0 ? this.color1 : this.color2;
  20404. geometry.colors.push( color, color, color, color );
  20405. }
  20406. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20407. };
  20408. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20409. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20410. this.color1.set( colorCenterLine );
  20411. this.color2.set( colorGrid );
  20412. this.geometry.colorsNeedUpdate = true;
  20413. }
  20414. /**
  20415. * @author alteredq / http://alteredqualia.com/
  20416. * @author mrdoob / http://mrdoob.com/
  20417. */
  20418. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20419. THREE.Object3D.call( this );
  20420. this.light = light;
  20421. this.light.updateMatrixWorld();
  20422. this.matrixWorld = light.matrixWorld;
  20423. this.matrixAutoUpdate = false;
  20424. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20425. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20426. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20427. for ( var i = 0, il = 8; i < il; i ++ ) {
  20428. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20429. }
  20430. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20431. this.lightSphere = new THREE.Mesh( geometry, material );
  20432. this.add( this.lightSphere );
  20433. this.update();
  20434. };
  20435. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20436. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20437. this.lightSphere.geometry.dispose();
  20438. this.lightSphere.material.dispose();
  20439. };
  20440. THREE.HemisphereLightHelper.prototype.update = function () {
  20441. var vector = new THREE.Vector3();
  20442. return function () {
  20443. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20444. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20445. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20446. this.lightSphere.geometry.colorsNeedUpdate = true;
  20447. }
  20448. }();
  20449. /**
  20450. * @author alteredq / http://alteredqualia.com/
  20451. * @author mrdoob / http://mrdoob.com/
  20452. */
  20453. THREE.PointLightHelper = function ( light, sphereSize ) {
  20454. this.light = light;
  20455. this.light.updateMatrixWorld();
  20456. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20457. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20458. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20459. THREE.Mesh.call( this, geometry, material );
  20460. this.matrixWorld = this.light.matrixWorld;
  20461. this.matrixAutoUpdate = false;
  20462. /*
  20463. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20464. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20465. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20466. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20467. var d = light.distance;
  20468. if ( d === 0.0 ) {
  20469. this.lightDistance.visible = false;
  20470. } else {
  20471. this.lightDistance.scale.set( d, d, d );
  20472. }
  20473. this.add( this.lightDistance );
  20474. */
  20475. };
  20476. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20477. THREE.PointLightHelper.prototype.dispose = function () {
  20478. this.geometry.dispose();
  20479. this.material.dispose();
  20480. };
  20481. THREE.PointLightHelper.prototype.update = function () {
  20482. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20483. /*
  20484. var d = this.light.distance;
  20485. if ( d === 0.0 ) {
  20486. this.lightDistance.visible = false;
  20487. } else {
  20488. this.lightDistance.visible = true;
  20489. this.lightDistance.scale.set( d, d, d );
  20490. }
  20491. */
  20492. };
  20493. /**
  20494. * @author Sean Griffin / http://twitter.com/sgrif
  20495. * @author Michael Guerrero / http://realitymeltdown.com
  20496. * @author mrdoob / http://mrdoob.com/
  20497. */
  20498. THREE.SkeletonHelper = function ( object ) {
  20499. var skeleton = object.skeleton;
  20500. var geometry = new THREE.Geometry();
  20501. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  20502. var bone = skeleton.bones[ i ];
  20503. if ( bone.parent instanceof THREE.Bone ) {
  20504. geometry.vertices.push( new THREE.Vector3() );
  20505. geometry.vertices.push( new THREE.Vector3() );
  20506. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20507. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20508. }
  20509. }
  20510. var material = new THREE.LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, transparent: true } );
  20511. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20512. this.skeleton = skeleton;
  20513. this.matrixWorld = object.matrixWorld;
  20514. this.matrixAutoUpdate = false;
  20515. this.update();
  20516. };
  20517. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20518. THREE.SkeletonHelper.prototype.update = function () {
  20519. var geometry = this.geometry;
  20520. var j = 0;
  20521. for ( var i = 0; i < this.skeleton.bones.length; i ++ ) {
  20522. var bone = this.skeleton.bones[ i ];
  20523. if ( bone.parent instanceof THREE.Bone ) {
  20524. geometry.vertices[ j ].setFromMatrixPosition( bone.skinMatrix );
  20525. geometry.vertices[ j + 1 ].setFromMatrixPosition( bone.parent.skinMatrix );
  20526. j += 2;
  20527. }
  20528. }
  20529. geometry.verticesNeedUpdate = true;
  20530. geometry.computeBoundingSphere();
  20531. };
  20532. /**
  20533. * @author alteredq / http://alteredqualia.com/
  20534. * @author mrdoob / http://mrdoob.com/
  20535. * @author WestLangley / http://github.com/WestLangley
  20536. */
  20537. THREE.SpotLightHelper = function ( light ) {
  20538. THREE.Object3D.call( this );
  20539. this.light = light;
  20540. this.light.updateMatrixWorld();
  20541. this.matrixWorld = light.matrixWorld;
  20542. this.matrixAutoUpdate = false;
  20543. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20544. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20545. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20546. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20547. this.cone = new THREE.Mesh( geometry, material );
  20548. this.add( this.cone );
  20549. this.update();
  20550. };
  20551. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20552. THREE.SpotLightHelper.prototype.dispose = function () {
  20553. this.cone.geometry.dispose();
  20554. this.cone.material.dispose();
  20555. };
  20556. THREE.SpotLightHelper.prototype.update = function () {
  20557. var vector = new THREE.Vector3();
  20558. var vector2 = new THREE.Vector3();
  20559. return function () {
  20560. var coneLength = this.light.distance ? this.light.distance : 10000;
  20561. var coneWidth = coneLength * Math.tan( this.light.angle );
  20562. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20563. vector.setFromMatrixPosition( this.light.matrixWorld );
  20564. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20565. this.cone.lookAt( vector2.sub( vector ) );
  20566. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20567. };
  20568. }();
  20569. /**
  20570. * @author mrdoob / http://mrdoob.com/
  20571. * @author WestLangley / http://github.com/WestLangley
  20572. */
  20573. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20574. this.object = object;
  20575. this.size = ( size !== undefined ) ? size : 1;
  20576. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20577. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20578. var geometry = new THREE.Geometry();
  20579. var vertices = object.geometry.vertices;
  20580. var faces = object.geometry.faces;
  20581. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20582. var face = faces[ i ];
  20583. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20584. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20585. }
  20586. }
  20587. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20588. this.matrixAutoUpdate = false;
  20589. this.normalMatrix = new THREE.Matrix3();
  20590. this.update();
  20591. };
  20592. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20593. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20594. var v1 = new THREE.Vector3();
  20595. return function( object ) {
  20596. var keys = [ 'a', 'b', 'c', 'd' ];
  20597. this.object.updateMatrixWorld( true );
  20598. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20599. var vertices = this.geometry.vertices;
  20600. var verts = this.object.geometry.vertices;
  20601. var faces = this.object.geometry.faces;
  20602. var worldMatrix = this.object.matrixWorld;
  20603. var idx = 0;
  20604. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20605. var face = faces[ i ];
  20606. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20607. var vertexId = face[ keys[ j ] ];
  20608. var vertex = verts[ vertexId ];
  20609. var normal = face.vertexNormals[ j ];
  20610. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20611. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20612. v1.add( vertices[ idx ] );
  20613. idx = idx + 1;
  20614. vertices[ idx ].copy( v1 );
  20615. idx = idx + 1;
  20616. }
  20617. }
  20618. this.geometry.verticesNeedUpdate = true;
  20619. return this;
  20620. }
  20621. }());
  20622. /**
  20623. * @author mrdoob / http://mrdoob.com/
  20624. * @author WestLangley / http://github.com/WestLangley
  20625. */
  20626. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20627. this.object = object;
  20628. this.size = ( size !== undefined ) ? size : 1;
  20629. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20630. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20631. var geometry = new THREE.Geometry();
  20632. var vertices = object.geometry.vertices;
  20633. var faces = object.geometry.faces;
  20634. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20635. var face = faces[ i ];
  20636. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20637. geometry.vertices.push( new THREE.Vector3() );
  20638. geometry.vertices.push( new THREE.Vector3() );
  20639. }
  20640. }
  20641. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20642. this.matrixAutoUpdate = false;
  20643. this.update();
  20644. };
  20645. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20646. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20647. var v1 = new THREE.Vector3();
  20648. return function( object ) {
  20649. var keys = [ 'a', 'b', 'c', 'd' ];
  20650. this.object.updateMatrixWorld( true );
  20651. var vertices = this.geometry.vertices;
  20652. var verts = this.object.geometry.vertices;
  20653. var faces = this.object.geometry.faces;
  20654. var worldMatrix = this.object.matrixWorld;
  20655. var idx = 0;
  20656. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20657. var face = faces[ i ];
  20658. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20659. var vertexId = face[ keys[ j ] ];
  20660. var vertex = verts[ vertexId ];
  20661. var tangent = face.vertexTangents[ j ];
  20662. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20663. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20664. v1.add( vertices[ idx ] );
  20665. idx = idx + 1;
  20666. vertices[ idx ].copy( v1 );
  20667. idx = idx + 1;
  20668. }
  20669. }
  20670. this.geometry.verticesNeedUpdate = true;
  20671. return this;
  20672. }
  20673. }());
  20674. /**
  20675. * @author mrdoob / http://mrdoob.com/
  20676. */
  20677. THREE.WireframeHelper = function ( object, hex ) {
  20678. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20679. var edge = [ 0, 0 ], hash = {};
  20680. var sortFunction = function ( a, b ) { return a - b };
  20681. var keys = [ 'a', 'b', 'c' ];
  20682. var geometry = new THREE.BufferGeometry();
  20683. if ( object.geometry instanceof THREE.Geometry ) {
  20684. var vertices = object.geometry.vertices;
  20685. var faces = object.geometry.faces;
  20686. var numEdges = 0;
  20687. // allocate maximal size
  20688. var edges = new Uint32Array( 6 * faces.length );
  20689. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20690. var face = faces[ i ];
  20691. for ( var j = 0; j < 3; j ++ ) {
  20692. edge[ 0 ] = face[ keys[ j ] ];
  20693. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20694. edge.sort( sortFunction );
  20695. var key = edge.toString();
  20696. if ( hash[ key ] === undefined ) {
  20697. edges[ 2 * numEdges ] = edge[ 0 ];
  20698. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20699. hash[ key ] = true;
  20700. numEdges ++;
  20701. }
  20702. }
  20703. }
  20704. var coords = new Float32Array( numEdges * 2 * 3 );
  20705. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20706. for ( var j = 0; j < 2; j ++ ) {
  20707. var vertex = vertices[ edges [ 2 * i + j] ];
  20708. var index = 6 * i + 3 * j;
  20709. coords[ index + 0 ] = vertex.x;
  20710. coords[ index + 1 ] = vertex.y;
  20711. coords[ index + 2 ] = vertex.z;
  20712. }
  20713. }
  20714. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20715. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20716. var vertices = object.geometry.attributes.position.array;
  20717. var indices = object.geometry.attributes.index.array;
  20718. var offsets = object.geometry.offsets;
  20719. var numEdges = 0;
  20720. // allocate maximal size
  20721. var edges = new Uint32Array( 2 * indices.length );
  20722. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  20723. var start = offsets[ o ].start;
  20724. var count = offsets[ o ].count;
  20725. var index = offsets[ o ].index;
  20726. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20727. for ( var j = 0; j < 3; j ++ ) {
  20728. edge[ 0 ] = index + indices[ i + j ];
  20729. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20730. edge.sort( sortFunction );
  20731. var key = edge.toString();
  20732. if ( hash[ key ] === undefined ) {
  20733. edges[ 2 * numEdges ] = edge[ 0 ];
  20734. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20735. hash[ key ] = true;
  20736. numEdges ++;
  20737. }
  20738. }
  20739. }
  20740. }
  20741. var coords = new Float32Array( numEdges * 2 * 3 );
  20742. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20743. for ( var j = 0; j < 2; j ++ ) {
  20744. var index = 6 * i + 3 * j;
  20745. var index2 = 3 * edges[ 2 * i + j];
  20746. coords[ index + 0 ] = vertices[ index2 ];
  20747. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20748. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20749. }
  20750. }
  20751. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20752. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  20753. var vertices = object.geometry.attributes.position.array;
  20754. var numEdges = vertices.length / 3;
  20755. var numTris = numEdges / 3;
  20756. var coords = new Float32Array( numEdges * 2 * 3 );
  20757. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20758. for ( var j = 0; j < 3; j ++ ) {
  20759. var index = 18 * i + 6 * j;
  20760. var index1 = 9 * i + 3 * j;
  20761. coords[ index + 0 ] = vertices[ index1 ];
  20762. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20763. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20764. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20765. coords[ index + 3 ] = vertices[ index2 ];
  20766. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20767. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20768. }
  20769. }
  20770. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20771. }
  20772. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20773. this.matrixAutoUpdate = false;
  20774. this.matrixWorld = object.matrixWorld;
  20775. };
  20776. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20777. /**
  20778. * @author alteredq / http://alteredqualia.com/
  20779. */
  20780. THREE.ImmediateRenderObject = function () {
  20781. THREE.Object3D.call( this );
  20782. this.render = function ( renderCallback ) { };
  20783. };
  20784. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20785. /**
  20786. * @author mikael emtinger / http://gomo.se/
  20787. * @author alteredq / http://alteredqualia.com/
  20788. */
  20789. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20790. THREE.Object3D.call( this );
  20791. this.lensFlares = [];
  20792. this.positionScreen = new THREE.Vector3();
  20793. this.customUpdateCallback = undefined;
  20794. if( texture !== undefined ) {
  20795. this.add( texture, size, distance, blending, color );
  20796. }
  20797. };
  20798. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20799. /*
  20800. * Add: adds another flare
  20801. */
  20802. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20803. if( size === undefined ) size = -1;
  20804. if( distance === undefined ) distance = 0;
  20805. if( opacity === undefined ) opacity = 1;
  20806. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20807. if( blending === undefined ) blending = THREE.NormalBlending;
  20808. distance = Math.min( distance, Math.max( 0, distance ) );
  20809. this.lensFlares.push( { texture: texture, // THREE.Texture
  20810. size: size, // size in pixels (-1 = use texture.width)
  20811. distance: distance, // distance (0-1) from light source (0=at light source)
  20812. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20813. scale: 1, // scale
  20814. rotation: 1, // rotation
  20815. opacity: opacity, // opacity
  20816. color: color, // color
  20817. blending: blending } ); // blending
  20818. };
  20819. /*
  20820. * Update lens flares update positions on all flares based on the screen position
  20821. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20822. */
  20823. THREE.LensFlare.prototype.updateLensFlares = function () {
  20824. var f, fl = this.lensFlares.length;
  20825. var flare;
  20826. var vecX = -this.positionScreen.x * 2;
  20827. var vecY = -this.positionScreen.y * 2;
  20828. for( f = 0; f < fl; f ++ ) {
  20829. flare = this.lensFlares[ f ];
  20830. flare.x = this.positionScreen.x + vecX * flare.distance;
  20831. flare.y = this.positionScreen.y + vecY * flare.distance;
  20832. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20833. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20834. }
  20835. };
  20836. /**
  20837. * @author alteredq / http://alteredqualia.com/
  20838. */
  20839. THREE.MorphBlendMesh = function( geometry, material ) {
  20840. THREE.Mesh.call( this, geometry, material );
  20841. this.animationsMap = {};
  20842. this.animationsList = [];
  20843. // prepare default animation
  20844. // (all frames played together in 1 second)
  20845. var numFrames = this.geometry.morphTargets.length;
  20846. var name = "__default";
  20847. var startFrame = 0;
  20848. var endFrame = numFrames - 1;
  20849. var fps = numFrames / 1;
  20850. this.createAnimation( name, startFrame, endFrame, fps );
  20851. this.setAnimationWeight( name, 1 );
  20852. };
  20853. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20854. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20855. var animation = {
  20856. startFrame: start,
  20857. endFrame: end,
  20858. length: end - start + 1,
  20859. fps: fps,
  20860. duration: ( end - start ) / fps,
  20861. lastFrame: 0,
  20862. currentFrame: 0,
  20863. active: false,
  20864. time: 0,
  20865. direction: 1,
  20866. weight: 1,
  20867. directionBackwards: false,
  20868. mirroredLoop: false
  20869. };
  20870. this.animationsMap[ name ] = animation;
  20871. this.animationsList.push( animation );
  20872. };
  20873. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20874. var pattern = /([a-z]+)_?(\d+)/;
  20875. var firstAnimation, frameRanges = {};
  20876. var geometry = this.geometry;
  20877. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20878. var morph = geometry.morphTargets[ i ];
  20879. var chunks = morph.name.match( pattern );
  20880. if ( chunks && chunks.length > 1 ) {
  20881. var name = chunks[ 1 ];
  20882. var num = chunks[ 2 ];
  20883. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20884. var range = frameRanges[ name ];
  20885. if ( i < range.start ) range.start = i;
  20886. if ( i > range.end ) range.end = i;
  20887. if ( ! firstAnimation ) firstAnimation = name;
  20888. }
  20889. }
  20890. for ( var name in frameRanges ) {
  20891. var range = frameRanges[ name ];
  20892. this.createAnimation( name, range.start, range.end, fps );
  20893. }
  20894. this.firstAnimation = firstAnimation;
  20895. };
  20896. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20897. var animation = this.animationsMap[ name ];
  20898. if ( animation ) {
  20899. animation.direction = 1;
  20900. animation.directionBackwards = false;
  20901. }
  20902. };
  20903. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20904. var animation = this.animationsMap[ name ];
  20905. if ( animation ) {
  20906. animation.direction = -1;
  20907. animation.directionBackwards = true;
  20908. }
  20909. };
  20910. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20911. var animation = this.animationsMap[ name ];
  20912. if ( animation ) {
  20913. animation.fps = fps;
  20914. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20915. }
  20916. };
  20917. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20918. var animation = this.animationsMap[ name ];
  20919. if ( animation ) {
  20920. animation.duration = duration;
  20921. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20922. }
  20923. };
  20924. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20925. var animation = this.animationsMap[ name ];
  20926. if ( animation ) {
  20927. animation.weight = weight;
  20928. }
  20929. };
  20930. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20931. var animation = this.animationsMap[ name ];
  20932. if ( animation ) {
  20933. animation.time = time;
  20934. }
  20935. };
  20936. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20937. var time = 0;
  20938. var animation = this.animationsMap[ name ];
  20939. if ( animation ) {
  20940. time = animation.time;
  20941. }
  20942. return time;
  20943. };
  20944. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20945. var duration = -1;
  20946. var animation = this.animationsMap[ name ];
  20947. if ( animation ) {
  20948. duration = animation.duration;
  20949. }
  20950. return duration;
  20951. };
  20952. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20953. var animation = this.animationsMap[ name ];
  20954. if ( animation ) {
  20955. animation.time = 0;
  20956. animation.active = true;
  20957. } else {
  20958. console.warn( "animation[" + name + "] undefined" );
  20959. }
  20960. };
  20961. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20962. var animation = this.animationsMap[ name ];
  20963. if ( animation ) {
  20964. animation.active = false;
  20965. }
  20966. };
  20967. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20968. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20969. var animation = this.animationsList[ i ];
  20970. if ( ! animation.active ) continue;
  20971. var frameTime = animation.duration / animation.length;
  20972. animation.time += animation.direction * delta;
  20973. if ( animation.mirroredLoop ) {
  20974. if ( animation.time > animation.duration || animation.time < 0 ) {
  20975. animation.direction *= -1;
  20976. if ( animation.time > animation.duration ) {
  20977. animation.time = animation.duration;
  20978. animation.directionBackwards = true;
  20979. }
  20980. if ( animation.time < 0 ) {
  20981. animation.time = 0;
  20982. animation.directionBackwards = false;
  20983. }
  20984. }
  20985. } else {
  20986. animation.time = animation.time % animation.duration;
  20987. if ( animation.time < 0 ) animation.time += animation.duration;
  20988. }
  20989. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20990. var weight = animation.weight;
  20991. if ( keyframe !== animation.currentFrame ) {
  20992. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20993. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20994. this.morphTargetInfluences[ keyframe ] = 0;
  20995. animation.lastFrame = animation.currentFrame;
  20996. animation.currentFrame = keyframe;
  20997. }
  20998. var mix = ( animation.time % frameTime ) / frameTime;
  20999. if ( animation.directionBackwards ) mix = 1 - mix;
  21000. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21001. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21002. }
  21003. };
  21004. /**
  21005. * @author mikael emtinger / http://gomo.se/
  21006. * @author alteredq / http://alteredqualia.com/
  21007. */
  21008. THREE.LensFlarePlugin = function () {
  21009. var _gl, _renderer, _precision, _lensFlare = {};
  21010. this.init = function ( renderer ) {
  21011. _gl = renderer.context;
  21012. _renderer = renderer;
  21013. _precision = renderer.getPrecision();
  21014. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21015. _lensFlare.faces = new Uint16Array( 6 );
  21016. var i = 0;
  21017. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21018. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21019. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21020. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21021. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21022. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21023. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21024. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21025. i = 0;
  21026. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21027. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21028. // buffers
  21029. _lensFlare.vertexBuffer = _gl.createBuffer();
  21030. _lensFlare.elementBuffer = _gl.createBuffer();
  21031. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21032. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21033. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21034. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21035. // textures
  21036. _lensFlare.tempTexture = _gl.createTexture();
  21037. _lensFlare.occlusionTexture = _gl.createTexture();
  21038. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21039. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21040. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21041. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21042. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21043. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21044. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21045. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21046. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21047. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21048. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21049. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21050. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21051. _lensFlare.hasVertexTexture = false;
  21052. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21053. } else {
  21054. _lensFlare.hasVertexTexture = true;
  21055. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21056. }
  21057. _lensFlare.attributes = {};
  21058. _lensFlare.uniforms = {};
  21059. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21060. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21061. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21062. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21063. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21064. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21065. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21066. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21067. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21068. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21069. };
  21070. /*
  21071. * Render lens flares
  21072. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21073. * reads these back and calculates occlusion.
  21074. * Then _lensFlare.update_lensFlares() is called to re-position and
  21075. * update transparency of flares. Then they are rendered.
  21076. *
  21077. */
  21078. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21079. var flares = scene.__webglFlares,
  21080. nFlares = flares.length;
  21081. if ( ! nFlares ) return;
  21082. var tempPosition = new THREE.Vector3();
  21083. var invAspect = viewportHeight / viewportWidth,
  21084. halfViewportWidth = viewportWidth * 0.5,
  21085. halfViewportHeight = viewportHeight * 0.5;
  21086. var size = 16 / viewportHeight,
  21087. scale = new THREE.Vector2( size * invAspect, size );
  21088. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21089. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21090. var uniforms = _lensFlare.uniforms,
  21091. attributes = _lensFlare.attributes;
  21092. // set _lensFlare program and reset blending
  21093. _gl.useProgram( _lensFlare.program );
  21094. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21095. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21096. // loop through all lens flares to update their occlusion and positions
  21097. // setup gl and common used attribs/unforms
  21098. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21099. _gl.uniform1i( uniforms.map, 1 );
  21100. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21101. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21102. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21103. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21104. _gl.disable( _gl.CULL_FACE );
  21105. _gl.depthMask( false );
  21106. var i, j, jl, flare, sprite;
  21107. for ( i = 0; i < nFlares; i ++ ) {
  21108. size = 16 / viewportHeight;
  21109. scale.set( size * invAspect, size );
  21110. // calc object screen position
  21111. flare = flares[ i ];
  21112. if ( flare.visible === false ) continue;
  21113. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21114. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21115. tempPosition.applyProjection( camera.projectionMatrix );
  21116. // setup arrays for gl programs
  21117. screenPosition.copy( tempPosition )
  21118. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21119. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21120. // screen cull
  21121. if ( _lensFlare.hasVertexTexture || (
  21122. screenPositionPixels.x > 0 &&
  21123. screenPositionPixels.x < viewportWidth &&
  21124. screenPositionPixels.y > 0 &&
  21125. screenPositionPixels.y < viewportHeight ) ) {
  21126. // save current RGB to temp texture
  21127. _gl.activeTexture( _gl.TEXTURE1 );
  21128. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21129. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21130. // render pink quad
  21131. _gl.uniform1i( uniforms.renderType, 0 );
  21132. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21133. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21134. _gl.disable( _gl.BLEND );
  21135. _gl.enable( _gl.DEPTH_TEST );
  21136. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21137. // copy result to occlusionMap
  21138. _gl.activeTexture( _gl.TEXTURE0 );
  21139. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21140. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21141. // restore graphics
  21142. _gl.uniform1i( uniforms.renderType, 1 );
  21143. _gl.disable( _gl.DEPTH_TEST );
  21144. _gl.activeTexture( _gl.TEXTURE1 );
  21145. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21146. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21147. // update object positions
  21148. flare.positionScreen.copy( screenPosition )
  21149. if ( flare.customUpdateCallback ) {
  21150. flare.customUpdateCallback( flare );
  21151. } else {
  21152. flare.updateLensFlares();
  21153. }
  21154. // render flares
  21155. _gl.uniform1i( uniforms.renderType, 2 );
  21156. _gl.enable( _gl.BLEND );
  21157. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21158. sprite = flare.lensFlares[ j ];
  21159. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21160. screenPosition.x = sprite.x;
  21161. screenPosition.y = sprite.y;
  21162. screenPosition.z = sprite.z;
  21163. size = sprite.size * sprite.scale / viewportHeight;
  21164. scale.x = size * invAspect;
  21165. scale.y = size;
  21166. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21167. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21168. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21169. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21170. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21171. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21172. _renderer.setTexture( sprite.texture, 1 );
  21173. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21174. }
  21175. }
  21176. }
  21177. }
  21178. // restore gl
  21179. _gl.enable( _gl.CULL_FACE );
  21180. _gl.enable( _gl.DEPTH_TEST );
  21181. _gl.depthMask( true );
  21182. };
  21183. function createProgram ( shader, precision ) {
  21184. var program = _gl.createProgram();
  21185. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21186. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21187. var prefix = "precision " + precision + " float;\n";
  21188. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21189. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21190. _gl.compileShader( fragmentShader );
  21191. _gl.compileShader( vertexShader );
  21192. _gl.attachShader( program, fragmentShader );
  21193. _gl.attachShader( program, vertexShader );
  21194. _gl.linkProgram( program );
  21195. return program;
  21196. };
  21197. };
  21198. /**
  21199. * @author alteredq / http://alteredqualia.com/
  21200. */
  21201. THREE.ShadowMapPlugin = function () {
  21202. var _gl,
  21203. _renderer,
  21204. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21205. _frustum = new THREE.Frustum(),
  21206. _projScreenMatrix = new THREE.Matrix4(),
  21207. _min = new THREE.Vector3(),
  21208. _max = new THREE.Vector3(),
  21209. _matrixPosition = new THREE.Vector3();
  21210. this.init = function ( renderer ) {
  21211. _gl = renderer.context;
  21212. _renderer = renderer;
  21213. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21214. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21215. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21216. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21217. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21218. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21219. _depthMaterial._shadowPass = true;
  21220. _depthMaterialMorph._shadowPass = true;
  21221. _depthMaterialSkin._shadowPass = true;
  21222. _depthMaterialMorphSkin._shadowPass = true;
  21223. };
  21224. this.render = function ( scene, camera ) {
  21225. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21226. this.update( scene, camera );
  21227. };
  21228. this.update = function ( scene, camera ) {
  21229. var i, il, j, jl, n,
  21230. shadowMap, shadowMatrix, shadowCamera,
  21231. program, buffer, material,
  21232. webglObject, object, light,
  21233. renderList,
  21234. lights = [],
  21235. k = 0,
  21236. fog = null;
  21237. // set GL state for depth map
  21238. _gl.clearColor( 1, 1, 1, 1 );
  21239. _gl.disable( _gl.BLEND );
  21240. _gl.enable( _gl.CULL_FACE );
  21241. _gl.frontFace( _gl.CCW );
  21242. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21243. _gl.cullFace( _gl.FRONT );
  21244. } else {
  21245. _gl.cullFace( _gl.BACK );
  21246. }
  21247. _renderer.setDepthTest( true );
  21248. // preprocess lights
  21249. // - skip lights that are not casting shadows
  21250. // - create virtual lights for cascaded shadow maps
  21251. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21252. light = scene.__lights[ i ];
  21253. if ( ! light.castShadow ) continue;
  21254. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21255. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21256. var virtualLight;
  21257. if ( ! light.shadowCascadeArray[ n ] ) {
  21258. virtualLight = createVirtualLight( light, n );
  21259. virtualLight.originalCamera = camera;
  21260. var gyro = new THREE.Gyroscope();
  21261. gyro.position.copy( light.shadowCascadeOffset );
  21262. gyro.add( virtualLight );
  21263. gyro.add( virtualLight.target );
  21264. camera.add( gyro );
  21265. light.shadowCascadeArray[ n ] = virtualLight;
  21266. console.log( "Created virtualLight", virtualLight );
  21267. } else {
  21268. virtualLight = light.shadowCascadeArray[ n ];
  21269. }
  21270. updateVirtualLight( light, n );
  21271. lights[ k ] = virtualLight;
  21272. k ++;
  21273. }
  21274. } else {
  21275. lights[ k ] = light;
  21276. k ++;
  21277. }
  21278. }
  21279. // render depth map
  21280. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21281. light = lights[ i ];
  21282. if ( ! light.shadowMap ) {
  21283. var shadowFilter = THREE.LinearFilter;
  21284. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21285. shadowFilter = THREE.NearestFilter;
  21286. }
  21287. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21288. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21289. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21290. light.shadowMatrix = new THREE.Matrix4();
  21291. }
  21292. if ( ! light.shadowCamera ) {
  21293. if ( light instanceof THREE.SpotLight ) {
  21294. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21295. } else if ( light instanceof THREE.DirectionalLight ) {
  21296. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21297. } else {
  21298. console.error( "Unsupported light type for shadow" );
  21299. continue;
  21300. }
  21301. scene.add( light.shadowCamera );
  21302. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21303. }
  21304. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21305. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21306. light.shadowCamera.add( light.cameraHelper );
  21307. }
  21308. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21309. updateShadowCamera( camera, light );
  21310. }
  21311. shadowMap = light.shadowMap;
  21312. shadowMatrix = light.shadowMatrix;
  21313. shadowCamera = light.shadowCamera;
  21314. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21315. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21316. shadowCamera.lookAt( _matrixPosition );
  21317. shadowCamera.updateMatrixWorld();
  21318. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21319. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21320. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21321. // compute shadow matrix
  21322. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21323. 0.0, 0.5, 0.0, 0.5,
  21324. 0.0, 0.0, 0.5, 0.5,
  21325. 0.0, 0.0, 0.0, 1.0 );
  21326. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21327. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21328. // update camera matrices and frustum
  21329. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21330. _frustum.setFromMatrix( _projScreenMatrix );
  21331. // render shadow map
  21332. _renderer.setRenderTarget( shadowMap );
  21333. _renderer.clear();
  21334. // set object matrices & frustum culling
  21335. renderList = scene.__webglObjects;
  21336. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21337. webglObject = renderList[ j ];
  21338. object = webglObject.object;
  21339. webglObject.render = false;
  21340. if ( object.visible && object.castShadow ) {
  21341. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  21342. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21343. webglObject.render = true;
  21344. }
  21345. }
  21346. }
  21347. // render regular objects
  21348. var objectMaterial, useMorphing, useSkinning;
  21349. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21350. webglObject = renderList[ j ];
  21351. if ( webglObject.render ) {
  21352. object = webglObject.object;
  21353. buffer = webglObject.buffer;
  21354. // culling is overriden globally for all objects
  21355. // while rendering depth map
  21356. // need to deal with MeshFaceMaterial somehow
  21357. // in that case just use the first of material.materials for now
  21358. // (proper solution would require to break objects by materials
  21359. // similarly to regular rendering and then set corresponding
  21360. // depth materials per each chunk instead of just once per object)
  21361. objectMaterial = getObjectMaterial( object );
  21362. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21363. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21364. if ( object.customDepthMaterial ) {
  21365. material = object.customDepthMaterial;
  21366. } else if ( useSkinning ) {
  21367. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21368. } else if ( useMorphing ) {
  21369. material = _depthMaterialMorph;
  21370. } else {
  21371. material = _depthMaterial;
  21372. }
  21373. _renderer.setMaterialFaces( objectMaterial );
  21374. if ( buffer instanceof THREE.BufferGeometry ) {
  21375. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21376. } else {
  21377. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21378. }
  21379. }
  21380. }
  21381. // set matrices and render immediate objects
  21382. renderList = scene.__webglObjectsImmediate;
  21383. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21384. webglObject = renderList[ j ];
  21385. object = webglObject.object;
  21386. if ( object.visible && object.castShadow ) {
  21387. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21388. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21389. }
  21390. }
  21391. }
  21392. // restore GL state
  21393. var clearColor = _renderer.getClearColor(),
  21394. clearAlpha = _renderer.getClearAlpha();
  21395. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21396. _gl.enable( _gl.BLEND );
  21397. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21398. _gl.cullFace( _gl.BACK );
  21399. }
  21400. };
  21401. function createVirtualLight( light, cascade ) {
  21402. var virtualLight = new THREE.DirectionalLight();
  21403. virtualLight.isVirtual = true;
  21404. virtualLight.onlyShadow = true;
  21405. virtualLight.castShadow = true;
  21406. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21407. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21408. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21409. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21410. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21411. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21412. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21413. virtualLight.shadowDarkness = light.shadowDarkness;
  21414. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21415. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21416. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21417. virtualLight.pointsWorld = [];
  21418. virtualLight.pointsFrustum = [];
  21419. var pointsWorld = virtualLight.pointsWorld,
  21420. pointsFrustum = virtualLight.pointsFrustum;
  21421. for ( var i = 0; i < 8; i ++ ) {
  21422. pointsWorld[ i ] = new THREE.Vector3();
  21423. pointsFrustum[ i ] = new THREE.Vector3();
  21424. }
  21425. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21426. var farZ = light.shadowCascadeFarZ[ cascade ];
  21427. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21428. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21429. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21430. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21431. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21432. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21433. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21434. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21435. return virtualLight;
  21436. }
  21437. // Synchronize virtual light with the original light
  21438. function updateVirtualLight( light, cascade ) {
  21439. var virtualLight = light.shadowCascadeArray[ cascade ];
  21440. virtualLight.position.copy( light.position );
  21441. virtualLight.target.position.copy( light.target.position );
  21442. virtualLight.lookAt( virtualLight.target );
  21443. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21444. virtualLight.shadowDarkness = light.shadowDarkness;
  21445. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21446. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21447. var farZ = light.shadowCascadeFarZ[ cascade ];
  21448. var pointsFrustum = virtualLight.pointsFrustum;
  21449. pointsFrustum[ 0 ].z = nearZ;
  21450. pointsFrustum[ 1 ].z = nearZ;
  21451. pointsFrustum[ 2 ].z = nearZ;
  21452. pointsFrustum[ 3 ].z = nearZ;
  21453. pointsFrustum[ 4 ].z = farZ;
  21454. pointsFrustum[ 5 ].z = farZ;
  21455. pointsFrustum[ 6 ].z = farZ;
  21456. pointsFrustum[ 7 ].z = farZ;
  21457. }
  21458. // Fit shadow camera's ortho frustum to camera frustum
  21459. function updateShadowCamera( camera, light ) {
  21460. var shadowCamera = light.shadowCamera,
  21461. pointsFrustum = light.pointsFrustum,
  21462. pointsWorld = light.pointsWorld;
  21463. _min.set( Infinity, Infinity, Infinity );
  21464. _max.set( -Infinity, -Infinity, -Infinity );
  21465. for ( var i = 0; i < 8; i ++ ) {
  21466. var p = pointsWorld[ i ];
  21467. p.copy( pointsFrustum[ i ] );
  21468. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21469. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21470. if ( p.x < _min.x ) _min.x = p.x;
  21471. if ( p.x > _max.x ) _max.x = p.x;
  21472. if ( p.y < _min.y ) _min.y = p.y;
  21473. if ( p.y > _max.y ) _max.y = p.y;
  21474. if ( p.z < _min.z ) _min.z = p.z;
  21475. if ( p.z > _max.z ) _max.z = p.z;
  21476. }
  21477. shadowCamera.left = _min.x;
  21478. shadowCamera.right = _max.x;
  21479. shadowCamera.top = _max.y;
  21480. shadowCamera.bottom = _min.y;
  21481. // can't really fit near/far
  21482. //shadowCamera.near = _min.z;
  21483. //shadowCamera.far = _max.z;
  21484. shadowCamera.updateProjectionMatrix();
  21485. }
  21486. // For the moment just ignore objects that have multiple materials with different animation methods
  21487. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21488. function getObjectMaterial( object ) {
  21489. return object.material instanceof THREE.MeshFaceMaterial
  21490. ? object.material.materials[ 0 ]
  21491. : object.material;
  21492. };
  21493. };
  21494. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21495. /**
  21496. * @author mikael emtinger / http://gomo.se/
  21497. * @author alteredq / http://alteredqualia.com/
  21498. */
  21499. THREE.SpritePlugin = function () {
  21500. var _gl, _renderer, _texture;
  21501. var vertices, faces, vertexBuffer, elementBuffer;
  21502. var program, attributes, uniforms;
  21503. this.init = function ( renderer ) {
  21504. _gl = renderer.context;
  21505. _renderer = renderer;
  21506. vertices = new Float32Array( [
  21507. - 0.5, - 0.5, 0, 0,
  21508. 0.5, - 0.5, 1, 0,
  21509. 0.5, 0.5, 1, 1,
  21510. - 0.5, 0.5, 0, 1
  21511. ] );
  21512. faces = new Uint16Array( [
  21513. 0, 1, 2,
  21514. 0, 2, 3
  21515. ] );
  21516. vertexBuffer = _gl.createBuffer();
  21517. elementBuffer = _gl.createBuffer();
  21518. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21519. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21520. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21521. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21522. program = createProgram();
  21523. attributes = {
  21524. position: _gl.getAttribLocation ( program, 'position' ),
  21525. uv: _gl.getAttribLocation ( program, 'uv' )
  21526. };
  21527. uniforms = {
  21528. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21529. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21530. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21531. scale: _gl.getUniformLocation( program, 'scale' ),
  21532. color: _gl.getUniformLocation( program, 'color' ),
  21533. map: _gl.getUniformLocation( program, 'map' ),
  21534. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21535. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21536. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21537. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21538. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21539. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21540. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21541. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21542. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21543. };
  21544. var canvas = document.createElement( 'canvas' );
  21545. canvas.width = 8;
  21546. canvas.height = 8;
  21547. var context = canvas.getContext( '2d' );
  21548. context.fillStyle = '#ffffff';
  21549. context.fillRect( 0, 0, canvas.width, canvas.height );
  21550. _texture = new THREE.Texture( canvas );
  21551. _texture.needsUpdate = true;
  21552. };
  21553. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21554. var sprites = scene.__webglSprites,
  21555. nSprites = sprites.length;
  21556. if ( ! nSprites ) return;
  21557. // setup gl
  21558. _gl.useProgram( program );
  21559. _gl.enableVertexAttribArray( attributes.position );
  21560. _gl.enableVertexAttribArray( attributes.uv );
  21561. _gl.disable( _gl.CULL_FACE );
  21562. _gl.enable( _gl.BLEND );
  21563. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21564. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21565. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21566. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21567. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21568. _gl.activeTexture( _gl.TEXTURE0 );
  21569. _gl.uniform1i( uniforms.map, 0 );
  21570. var oldFogType = 0;
  21571. var sceneFogType = 0;
  21572. var fog = scene.fog;
  21573. if ( fog ) {
  21574. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21575. if ( fog instanceof THREE.Fog ) {
  21576. _gl.uniform1f( uniforms.fogNear, fog.near );
  21577. _gl.uniform1f( uniforms.fogFar, fog.far );
  21578. _gl.uniform1i( uniforms.fogType, 1 );
  21579. oldFogType = 1;
  21580. sceneFogType = 1;
  21581. } else if ( fog instanceof THREE.FogExp2 ) {
  21582. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21583. _gl.uniform1i( uniforms.fogType, 2 );
  21584. oldFogType = 2;
  21585. sceneFogType = 2;
  21586. }
  21587. } else {
  21588. _gl.uniform1i( uniforms.fogType, 0 );
  21589. oldFogType = 0;
  21590. sceneFogType = 0;
  21591. }
  21592. // update positions and sort
  21593. var i, sprite, material, fogType, scale = [];
  21594. for( i = 0; i < nSprites; i ++ ) {
  21595. sprite = sprites[ i ];
  21596. material = sprite.material;
  21597. if ( sprite.visible === false ) continue;
  21598. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21599. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21600. }
  21601. sprites.sort( painterSortStable );
  21602. // render all sprites
  21603. for( i = 0; i < nSprites; i ++ ) {
  21604. sprite = sprites[ i ];
  21605. if ( sprite.visible === false ) continue;
  21606. material = sprite.material;
  21607. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21608. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21609. scale[ 0 ] = sprite.scale.x;
  21610. scale[ 1 ] = sprite.scale.y;
  21611. if ( scene.fog && material.fog ) {
  21612. fogType = sceneFogType;
  21613. } else {
  21614. fogType = 0;
  21615. }
  21616. if ( oldFogType !== fogType ) {
  21617. _gl.uniform1i( uniforms.fogType, fogType );
  21618. oldFogType = fogType;
  21619. }
  21620. if ( material.map !== null ) {
  21621. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  21622. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  21623. } else {
  21624. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  21625. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  21626. }
  21627. _gl.uniform1f( uniforms.opacity, material.opacity );
  21628. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21629. _gl.uniform1f( uniforms.rotation, material.rotation );
  21630. _gl.uniform2fv( uniforms.scale, scale );
  21631. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21632. _renderer.setDepthTest( material.depthTest );
  21633. _renderer.setDepthWrite( material.depthWrite );
  21634. if ( material.map && material.map.image && material.map.image.width ) {
  21635. _renderer.setTexture( material.map, 0 );
  21636. } else {
  21637. _renderer.setTexture( _texture, 0 );
  21638. }
  21639. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21640. }
  21641. // restore gl
  21642. _gl.enable( _gl.CULL_FACE );
  21643. };
  21644. function createProgram () {
  21645. var program = _gl.createProgram();
  21646. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21647. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21648. _gl.shaderSource( vertexShader, [
  21649. 'precision ' + _renderer.getPrecision() + ' float;',
  21650. 'uniform mat4 modelViewMatrix;',
  21651. 'uniform mat4 projectionMatrix;',
  21652. 'uniform float rotation;',
  21653. 'uniform vec2 scale;',
  21654. 'uniform vec2 uvOffset;',
  21655. 'uniform vec2 uvScale;',
  21656. 'attribute vec2 position;',
  21657. 'attribute vec2 uv;',
  21658. 'varying vec2 vUV;',
  21659. 'void main() {',
  21660. 'vUV = uvOffset + uv * uvScale;',
  21661. 'vec2 alignedPosition = position * scale;',
  21662. 'vec2 rotatedPosition;',
  21663. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21664. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21665. 'vec4 finalPosition;',
  21666. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21667. 'finalPosition.xy += rotatedPosition;',
  21668. 'finalPosition = projectionMatrix * finalPosition;',
  21669. 'gl_Position = finalPosition;',
  21670. '}'
  21671. ].join( '\n' ) );
  21672. _gl.shaderSource( fragmentShader, [
  21673. 'precision ' + _renderer.getPrecision() + ' float;',
  21674. 'uniform vec3 color;',
  21675. 'uniform sampler2D map;',
  21676. 'uniform float opacity;',
  21677. 'uniform int fogType;',
  21678. 'uniform vec3 fogColor;',
  21679. 'uniform float fogDensity;',
  21680. 'uniform float fogNear;',
  21681. 'uniform float fogFar;',
  21682. 'uniform float alphaTest;',
  21683. 'varying vec2 vUV;',
  21684. 'void main() {',
  21685. 'vec4 texture = texture2D( map, vUV );',
  21686. 'if ( texture.a < alphaTest ) discard;',
  21687. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21688. 'if ( fogType > 0 ) {',
  21689. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21690. 'float fogFactor = 0.0;',
  21691. 'if ( fogType == 1 ) {',
  21692. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21693. '} else {',
  21694. 'const float LOG2 = 1.442695;',
  21695. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21696. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21697. '}',
  21698. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21699. '}',
  21700. '}'
  21701. ].join( '\n' ) );
  21702. _gl.compileShader( vertexShader );
  21703. _gl.compileShader( fragmentShader );
  21704. _gl.attachShader( program, vertexShader );
  21705. _gl.attachShader( program, fragmentShader );
  21706. _gl.linkProgram( program );
  21707. return program;
  21708. };
  21709. function painterSortStable ( a, b ) {
  21710. if ( a.z !== b.z ) {
  21711. return b.z - a.z;
  21712. } else {
  21713. return b.id - a.id;
  21714. }
  21715. };
  21716. };
  21717. /**
  21718. * @author alteredq / http://alteredqualia.com/
  21719. */
  21720. THREE.DepthPassPlugin = function () {
  21721. this.enabled = false;
  21722. this.renderTarget = null;
  21723. var _gl,
  21724. _renderer,
  21725. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21726. _frustum = new THREE.Frustum(),
  21727. _projScreenMatrix = new THREE.Matrix4();
  21728. this.init = function ( renderer ) {
  21729. _gl = renderer.context;
  21730. _renderer = renderer;
  21731. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21732. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21733. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21734. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21735. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21736. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21737. _depthMaterial._shadowPass = true;
  21738. _depthMaterialMorph._shadowPass = true;
  21739. _depthMaterialSkin._shadowPass = true;
  21740. _depthMaterialMorphSkin._shadowPass = true;
  21741. };
  21742. this.render = function ( scene, camera ) {
  21743. if ( ! this.enabled ) return;
  21744. this.update( scene, camera );
  21745. };
  21746. this.update = function ( scene, camera ) {
  21747. var i, il, j, jl, n,
  21748. program, buffer, material,
  21749. webglObject, object, light,
  21750. renderList,
  21751. fog = null;
  21752. // set GL state for depth map
  21753. _gl.clearColor( 1, 1, 1, 1 );
  21754. _gl.disable( _gl.BLEND );
  21755. _renderer.setDepthTest( true );
  21756. // update scene
  21757. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21758. // update camera matrices and frustum
  21759. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21760. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21761. _frustum.setFromMatrix( _projScreenMatrix );
  21762. // render depth map
  21763. _renderer.setRenderTarget( this.renderTarget );
  21764. _renderer.clear();
  21765. // set object matrices & frustum culling
  21766. renderList = scene.__webglObjects;
  21767. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21768. webglObject = renderList[ j ];
  21769. object = webglObject.object;
  21770. webglObject.render = false;
  21771. if ( object.visible ) {
  21772. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  21773. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21774. webglObject.render = true;
  21775. }
  21776. }
  21777. }
  21778. // render regular objects
  21779. var objectMaterial, useMorphing, useSkinning;
  21780. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21781. webglObject = renderList[ j ];
  21782. if ( webglObject.render ) {
  21783. object = webglObject.object;
  21784. buffer = webglObject.buffer;
  21785. // todo: create proper depth material for particles
  21786. if ( object instanceof THREE.PointCloud && !object.customDepthMaterial ) continue;
  21787. objectMaterial = getObjectMaterial( object );
  21788. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21789. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21790. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21791. if ( object.customDepthMaterial ) {
  21792. material = object.customDepthMaterial;
  21793. } else if ( useSkinning ) {
  21794. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21795. } else if ( useMorphing ) {
  21796. material = _depthMaterialMorph;
  21797. } else {
  21798. material = _depthMaterial;
  21799. }
  21800. if ( buffer instanceof THREE.BufferGeometry ) {
  21801. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21802. } else {
  21803. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21804. }
  21805. }
  21806. }
  21807. // set matrices and render immediate objects
  21808. renderList = scene.__webglObjectsImmediate;
  21809. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21810. webglObject = renderList[ j ];
  21811. object = webglObject.object;
  21812. if ( object.visible ) {
  21813. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21814. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21815. }
  21816. }
  21817. // restore GL state
  21818. var clearColor = _renderer.getClearColor(),
  21819. clearAlpha = _renderer.getClearAlpha();
  21820. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21821. _gl.enable( _gl.BLEND );
  21822. };
  21823. // For the moment just ignore objects that have multiple materials with different animation methods
  21824. // Only the first material will be taken into account for deciding which depth material to use
  21825. function getObjectMaterial( object ) {
  21826. return object.material instanceof THREE.MeshFaceMaterial
  21827. ? object.material.materials[ 0 ]
  21828. : object.material;
  21829. };
  21830. };
  21831. /**
  21832. * @author mikael emtinger / http://gomo.se/
  21833. */
  21834. THREE.ShaderFlares = {
  21835. 'lensFlareVertexTexture': {
  21836. vertexShader: [
  21837. "uniform lowp int renderType;",
  21838. "uniform vec3 screenPosition;",
  21839. "uniform vec2 scale;",
  21840. "uniform float rotation;",
  21841. "uniform sampler2D occlusionMap;",
  21842. "attribute vec2 position;",
  21843. "attribute vec2 uv;",
  21844. "varying vec2 vUV;",
  21845. "varying float vVisibility;",
  21846. "void main() {",
  21847. "vUV = uv;",
  21848. "vec2 pos = position;",
  21849. "if( renderType == 2 ) {",
  21850. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21851. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21852. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21853. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21854. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21855. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21856. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21857. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21858. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21859. "vVisibility = visibility.r / 9.0;",
  21860. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21861. "vVisibility *= visibility.b / 9.0;",
  21862. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21863. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21864. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21865. "}",
  21866. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21867. "}"
  21868. ].join( "\n" ),
  21869. fragmentShader: [
  21870. "uniform lowp int renderType;",
  21871. "uniform sampler2D map;",
  21872. "uniform float opacity;",
  21873. "uniform vec3 color;",
  21874. "varying vec2 vUV;",
  21875. "varying float vVisibility;",
  21876. "void main() {",
  21877. // pink square
  21878. "if( renderType == 0 ) {",
  21879. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21880. // restore
  21881. "} else if( renderType == 1 ) {",
  21882. "gl_FragColor = texture2D( map, vUV );",
  21883. // flare
  21884. "} else {",
  21885. "vec4 texture = texture2D( map, vUV );",
  21886. "texture.a *= opacity * vVisibility;",
  21887. "gl_FragColor = texture;",
  21888. "gl_FragColor.rgb *= color;",
  21889. "}",
  21890. "}"
  21891. ].join( "\n" )
  21892. },
  21893. 'lensFlare': {
  21894. vertexShader: [
  21895. "uniform lowp int renderType;",
  21896. "uniform vec3 screenPosition;",
  21897. "uniform vec2 scale;",
  21898. "uniform float rotation;",
  21899. "attribute vec2 position;",
  21900. "attribute vec2 uv;",
  21901. "varying vec2 vUV;",
  21902. "void main() {",
  21903. "vUV = uv;",
  21904. "vec2 pos = position;",
  21905. "if( renderType == 2 ) {",
  21906. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21907. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21908. "}",
  21909. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21910. "}"
  21911. ].join( "\n" ),
  21912. fragmentShader: [
  21913. "precision mediump float;",
  21914. "uniform lowp int renderType;",
  21915. "uniform sampler2D map;",
  21916. "uniform sampler2D occlusionMap;",
  21917. "uniform float opacity;",
  21918. "uniform vec3 color;",
  21919. "varying vec2 vUV;",
  21920. "void main() {",
  21921. // pink square
  21922. "if( renderType == 0 ) {",
  21923. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21924. // restore
  21925. "} else if( renderType == 1 ) {",
  21926. "gl_FragColor = texture2D( map, vUV );",
  21927. // flare
  21928. "} else {",
  21929. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21930. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21931. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21932. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21933. "visibility = ( 1.0 - visibility / 4.0 );",
  21934. "vec4 texture = texture2D( map, vUV );",
  21935. "texture.a *= opacity * visibility;",
  21936. "gl_FragColor = texture;",
  21937. "gl_FragColor.rgb *= color;",
  21938. "}",
  21939. "}"
  21940. ].join( "\n" )
  21941. }
  21942. };