three.js 807 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '68dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  15. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  16. // requestAnimationFrame polyfill by Erik Möller
  17. // fixes from Paul Irish and Tino Zijdel
  18. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  19. ( function () {
  20. var lastTime = 0;
  21. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  22. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  23. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  24. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  25. }
  26. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  27. self.requestAnimationFrame = function ( callback ) {
  28. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  29. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  30. lastTime = currTime + timeToCall;
  31. return id;
  32. };
  33. }
  34. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  35. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  36. }
  37. }() );
  38. // GL STATE CONSTANTS
  39. THREE.CullFaceNone = 0;
  40. THREE.CullFaceBack = 1;
  41. THREE.CullFaceFront = 2;
  42. THREE.CullFaceFrontBack = 3;
  43. THREE.FrontFaceDirectionCW = 0;
  44. THREE.FrontFaceDirectionCCW = 1;
  45. // SHADOWING TYPES
  46. THREE.BasicShadowMap = 0;
  47. THREE.PCFShadowMap = 1;
  48. THREE.PCFSoftShadowMap = 2;
  49. // MATERIAL CONSTANTS
  50. // side
  51. THREE.FrontSide = 0;
  52. THREE.BackSide = 1;
  53. THREE.DoubleSide = 2;
  54. // shading
  55. THREE.NoShading = 0;
  56. THREE.FlatShading = 1;
  57. THREE.SmoothShading = 2;
  58. // colors
  59. THREE.NoColors = 0;
  60. THREE.FaceColors = 1;
  61. THREE.VertexColors = 2;
  62. // blending modes
  63. THREE.NoBlending = 0;
  64. THREE.NormalBlending = 1;
  65. THREE.AdditiveBlending = 2;
  66. THREE.SubtractiveBlending = 3;
  67. THREE.MultiplyBlending = 4;
  68. THREE.CustomBlending = 5;
  69. // custom blending equations
  70. // (numbers start from 100 not to clash with other
  71. // mappings to OpenGL constants defined in Texture.js)
  72. THREE.AddEquation = 100;
  73. THREE.SubtractEquation = 101;
  74. THREE.ReverseSubtractEquation = 102;
  75. // custom blending destination factors
  76. THREE.ZeroFactor = 200;
  77. THREE.OneFactor = 201;
  78. THREE.SrcColorFactor = 202;
  79. THREE.OneMinusSrcColorFactor = 203;
  80. THREE.SrcAlphaFactor = 204;
  81. THREE.OneMinusSrcAlphaFactor = 205;
  82. THREE.DstAlphaFactor = 206;
  83. THREE.OneMinusDstAlphaFactor = 207;
  84. // custom blending source factors
  85. //THREE.ZeroFactor = 200;
  86. //THREE.OneFactor = 201;
  87. //THREE.SrcAlphaFactor = 204;
  88. //THREE.OneMinusSrcAlphaFactor = 205;
  89. //THREE.DstAlphaFactor = 206;
  90. //THREE.OneMinusDstAlphaFactor = 207;
  91. THREE.DstColorFactor = 208;
  92. THREE.OneMinusDstColorFactor = 209;
  93. THREE.SrcAlphaSaturateFactor = 210;
  94. // TEXTURE CONSTANTS
  95. THREE.MultiplyOperation = 0;
  96. THREE.MixOperation = 1;
  97. THREE.AddOperation = 2;
  98. // Mapping modes
  99. THREE.UVMapping = function () {};
  100. THREE.CubeReflectionMapping = function () {};
  101. THREE.CubeRefractionMapping = function () {};
  102. THREE.SphericalReflectionMapping = function () {};
  103. THREE.SphericalRefractionMapping = function () {};
  104. // Wrapping modes
  105. THREE.RepeatWrapping = 1000;
  106. THREE.ClampToEdgeWrapping = 1001;
  107. THREE.MirroredRepeatWrapping = 1002;
  108. // Filters
  109. THREE.NearestFilter = 1003;
  110. THREE.NearestMipMapNearestFilter = 1004;
  111. THREE.NearestMipMapLinearFilter = 1005;
  112. THREE.LinearFilter = 1006;
  113. THREE.LinearMipMapNearestFilter = 1007;
  114. THREE.LinearMipMapLinearFilter = 1008;
  115. // Data types
  116. THREE.UnsignedByteType = 1009;
  117. THREE.ByteType = 1010;
  118. THREE.ShortType = 1011;
  119. THREE.UnsignedShortType = 1012;
  120. THREE.IntType = 1013;
  121. THREE.UnsignedIntType = 1014;
  122. THREE.FloatType = 1015;
  123. // Pixel types
  124. //THREE.UnsignedByteType = 1009;
  125. THREE.UnsignedShort4444Type = 1016;
  126. THREE.UnsignedShort5551Type = 1017;
  127. THREE.UnsignedShort565Type = 1018;
  128. // Pixel formats
  129. THREE.AlphaFormat = 1019;
  130. THREE.RGBFormat = 1020;
  131. THREE.RGBAFormat = 1021;
  132. THREE.LuminanceFormat = 1022;
  133. THREE.LuminanceAlphaFormat = 1023;
  134. // Compressed texture formats
  135. THREE.RGB_S3TC_DXT1_Format = 2001;
  136. THREE.RGBA_S3TC_DXT1_Format = 2002;
  137. THREE.RGBA_S3TC_DXT3_Format = 2003;
  138. THREE.RGBA_S3TC_DXT5_Format = 2004;
  139. /*
  140. // Potential future PVRTC compressed texture formats
  141. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  142. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  143. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  144. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  145. */
  146. /**
  147. * @author mrdoob / http://mrdoob.com/
  148. */
  149. THREE.Color = function ( color ) {
  150. if ( arguments.length === 3 ) {
  151. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  152. }
  153. return this.set( color )
  154. };
  155. THREE.Color.prototype = {
  156. constructor: THREE.Color,
  157. r: 1, g: 1, b: 1,
  158. set: function ( value ) {
  159. if ( value instanceof THREE.Color ) {
  160. this.copy( value );
  161. } else if ( typeof value === 'number' ) {
  162. this.setHex( value );
  163. } else if ( typeof value === 'string' ) {
  164. this.setStyle( value );
  165. }
  166. return this;
  167. },
  168. setHex: function ( hex ) {
  169. hex = Math.floor( hex );
  170. this.r = ( hex >> 16 & 255 ) / 255;
  171. this.g = ( hex >> 8 & 255 ) / 255;
  172. this.b = ( hex & 255 ) / 255;
  173. return this;
  174. },
  175. setRGB: function ( r, g, b ) {
  176. this.r = r;
  177. this.g = g;
  178. this.b = b;
  179. return this;
  180. },
  181. setHSL: function ( h, s, l ) {
  182. // h,s,l ranges are in 0.0 - 1.0
  183. if ( s === 0 ) {
  184. this.r = this.g = this.b = l;
  185. } else {
  186. var hue2rgb = function ( p, q, t ) {
  187. if ( t < 0 ) t += 1;
  188. if ( t > 1 ) t -= 1;
  189. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  190. if ( t < 1 / 2 ) return q;
  191. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  192. return p;
  193. };
  194. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  195. var q = ( 2 * l ) - p;
  196. this.r = hue2rgb( q, p, h + 1 / 3 );
  197. this.g = hue2rgb( q, p, h );
  198. this.b = hue2rgb( q, p, h - 1 / 3 );
  199. }
  200. return this;
  201. },
  202. setStyle: function ( style ) {
  203. // rgb(255,0,0)
  204. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  205. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  206. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  207. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  208. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  209. return this;
  210. }
  211. // rgb(100%,0%,0%)
  212. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  213. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  214. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  215. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  216. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  217. return this;
  218. }
  219. // #ff0000
  220. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  221. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  222. this.setHex( parseInt( color[ 1 ], 16 ) );
  223. return this;
  224. }
  225. // #f00
  226. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  227. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  228. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  229. return this;
  230. }
  231. // red
  232. if ( /^(\w+)$/i.test( style ) ) {
  233. this.setHex( THREE.ColorKeywords[ style ] );
  234. return this;
  235. }
  236. },
  237. copy: function ( color ) {
  238. this.r = color.r;
  239. this.g = color.g;
  240. this.b = color.b;
  241. return this;
  242. },
  243. copyGammaToLinear: function ( color ) {
  244. this.r = color.r * color.r;
  245. this.g = color.g * color.g;
  246. this.b = color.b * color.b;
  247. return this;
  248. },
  249. copyLinearToGamma: function ( color ) {
  250. this.r = Math.sqrt( color.r );
  251. this.g = Math.sqrt( color.g );
  252. this.b = Math.sqrt( color.b );
  253. return this;
  254. },
  255. convertGammaToLinear: function () {
  256. var r = this.r, g = this.g, b = this.b;
  257. this.r = r * r;
  258. this.g = g * g;
  259. this.b = b * b;
  260. return this;
  261. },
  262. convertLinearToGamma: function () {
  263. this.r = Math.sqrt( this.r );
  264. this.g = Math.sqrt( this.g );
  265. this.b = Math.sqrt( this.b );
  266. return this;
  267. },
  268. getHex: function () {
  269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  270. },
  271. getHexString: function () {
  272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  273. },
  274. getHSL: function ( optionalTarget ) {
  275. // h,s,l ranges are in 0.0 - 1.0
  276. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  277. var r = this.r, g = this.g, b = this.b;
  278. var max = Math.max( r, g, b );
  279. var min = Math.min( r, g, b );
  280. var hue, saturation;
  281. var lightness = ( min + max ) / 2.0;
  282. if ( min === max ) {
  283. hue = 0;
  284. saturation = 0;
  285. } else {
  286. var delta = max - min;
  287. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  288. switch ( max ) {
  289. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  290. case g: hue = ( b - r ) / delta + 2; break;
  291. case b: hue = ( r - g ) / delta + 4; break;
  292. }
  293. hue /= 6;
  294. }
  295. hsl.h = hue;
  296. hsl.s = saturation;
  297. hsl.l = lightness;
  298. return hsl;
  299. },
  300. getStyle: function () {
  301. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  302. },
  303. offsetHSL: function ( h, s, l ) {
  304. var hsl = this.getHSL();
  305. hsl.h += h; hsl.s += s; hsl.l += l;
  306. this.setHSL( hsl.h, hsl.s, hsl.l );
  307. return this;
  308. },
  309. add: function ( color ) {
  310. this.r += color.r;
  311. this.g += color.g;
  312. this.b += color.b;
  313. return this;
  314. },
  315. addColors: function ( color1, color2 ) {
  316. this.r = color1.r + color2.r;
  317. this.g = color1.g + color2.g;
  318. this.b = color1.b + color2.b;
  319. return this;
  320. },
  321. addScalar: function ( s ) {
  322. this.r += s;
  323. this.g += s;
  324. this.b += s;
  325. return this;
  326. },
  327. multiply: function ( color ) {
  328. this.r *= color.r;
  329. this.g *= color.g;
  330. this.b *= color.b;
  331. return this;
  332. },
  333. multiplyScalar: function ( s ) {
  334. this.r *= s;
  335. this.g *= s;
  336. this.b *= s;
  337. return this;
  338. },
  339. lerp: function ( color, alpha ) {
  340. this.r += ( color.r - this.r ) * alpha;
  341. this.g += ( color.g - this.g ) * alpha;
  342. this.b += ( color.b - this.b ) * alpha;
  343. return this;
  344. },
  345. equals: function ( c ) {
  346. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  347. },
  348. fromArray: function ( array ) {
  349. this.r = array[ 0 ];
  350. this.g = array[ 1 ];
  351. this.b = array[ 2 ];
  352. return this;
  353. },
  354. toArray: function () {
  355. return [ this.r, this.g, this.b ];
  356. },
  357. clone: function () {
  358. return new THREE.Color().setRGB( this.r, this.g, this.b );
  359. }
  360. };
  361. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  362. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  363. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  364. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  365. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  366. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  367. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  368. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  369. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  370. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  371. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  372. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  373. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  374. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  375. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  376. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  377. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  378. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  379. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  380. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  381. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  382. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  383. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  384. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  385. /**
  386. * @author mikael emtinger / http://gomo.se/
  387. * @author alteredq / http://alteredqualia.com/
  388. * @author WestLangley / http://github.com/WestLangley
  389. * @author bhouston / http://exocortex.com
  390. */
  391. THREE.Quaternion = function ( x, y, z, w ) {
  392. this._x = x || 0;
  393. this._y = y || 0;
  394. this._z = z || 0;
  395. this._w = ( w !== undefined ) ? w : 1;
  396. };
  397. THREE.Quaternion.prototype = {
  398. constructor: THREE.Quaternion,
  399. _x: 0,_y: 0, _z: 0, _w: 0,
  400. get x () {
  401. return this._x;
  402. },
  403. set x ( value ) {
  404. this._x = value;
  405. this.onChangeCallback();
  406. },
  407. get y () {
  408. return this._y;
  409. },
  410. set y ( value ) {
  411. this._y = value;
  412. this.onChangeCallback();
  413. },
  414. get z () {
  415. return this._z;
  416. },
  417. set z ( value ) {
  418. this._z = value;
  419. this.onChangeCallback();
  420. },
  421. get w () {
  422. return this._w;
  423. },
  424. set w ( value ) {
  425. this._w = value;
  426. this.onChangeCallback();
  427. },
  428. set: function ( x, y, z, w ) {
  429. this._x = x;
  430. this._y = y;
  431. this._z = z;
  432. this._w = w;
  433. this.onChangeCallback();
  434. return this;
  435. },
  436. copy: function ( quaternion ) {
  437. this._x = quaternion._x;
  438. this._y = quaternion._y;
  439. this._z = quaternion._z;
  440. this._w = quaternion._w;
  441. this.onChangeCallback();
  442. return this;
  443. },
  444. setFromEuler: function ( euler, update ) {
  445. if ( euler instanceof THREE.Euler === false ) {
  446. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  447. }
  448. // http://www.mathworks.com/matlabcentral/fileexchange/
  449. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  450. // content/SpinCalc.m
  451. var c1 = Math.cos( euler._x / 2 );
  452. var c2 = Math.cos( euler._y / 2 );
  453. var c3 = Math.cos( euler._z / 2 );
  454. var s1 = Math.sin( euler._x / 2 );
  455. var s2 = Math.sin( euler._y / 2 );
  456. var s3 = Math.sin( euler._z / 2 );
  457. if ( euler.order === 'XYZ' ) {
  458. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  459. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  460. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  461. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  462. } else if ( euler.order === 'YXZ' ) {
  463. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  464. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  465. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  466. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  467. } else if ( euler.order === 'ZXY' ) {
  468. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  469. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  470. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  471. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  472. } else if ( euler.order === 'ZYX' ) {
  473. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  474. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  475. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  476. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  477. } else if ( euler.order === 'YZX' ) {
  478. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  479. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  480. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  481. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  482. } else if ( euler.order === 'XZY' ) {
  483. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  484. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  485. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  486. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  487. }
  488. if ( update !== false ) this.onChangeCallback();
  489. return this;
  490. },
  491. setFromAxisAngle: function ( axis, angle ) {
  492. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  493. // assumes axis is normalized
  494. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  495. this._x = axis.x * s;
  496. this._y = axis.y * s;
  497. this._z = axis.z * s;
  498. this._w = Math.cos( halfAngle );
  499. this.onChangeCallback();
  500. return this;
  501. },
  502. setFromRotationMatrix: function ( m ) {
  503. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  504. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  505. var te = m.elements,
  506. m11 = te[0], m12 = te[4], m13 = te[8],
  507. m21 = te[1], m22 = te[5], m23 = te[9],
  508. m31 = te[2], m32 = te[6], m33 = te[10],
  509. trace = m11 + m22 + m33,
  510. s;
  511. if ( trace > 0 ) {
  512. s = 0.5 / Math.sqrt( trace + 1.0 );
  513. this._w = 0.25 / s;
  514. this._x = ( m32 - m23 ) * s;
  515. this._y = ( m13 - m31 ) * s;
  516. this._z = ( m21 - m12 ) * s;
  517. } else if ( m11 > m22 && m11 > m33 ) {
  518. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  519. this._w = (m32 - m23 ) / s;
  520. this._x = 0.25 * s;
  521. this._y = (m12 + m21 ) / s;
  522. this._z = (m13 + m31 ) / s;
  523. } else if ( m22 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  525. this._w = (m13 - m31 ) / s;
  526. this._x = (m12 + m21 ) / s;
  527. this._y = 0.25 * s;
  528. this._z = (m23 + m32 ) / s;
  529. } else {
  530. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  531. this._w = ( m21 - m12 ) / s;
  532. this._x = ( m13 + m31 ) / s;
  533. this._y = ( m23 + m32 ) / s;
  534. this._z = 0.25 * s;
  535. }
  536. this.onChangeCallback();
  537. return this;
  538. },
  539. setFromUnitVectors: function () {
  540. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  541. // assumes direction vectors vFrom and vTo are normalized
  542. var v1, r;
  543. var EPS = 0.000001;
  544. return function( vFrom, vTo ) {
  545. if ( v1 === undefined ) v1 = new THREE.Vector3();
  546. r = vFrom.dot( vTo ) + 1;
  547. if ( r < EPS ) {
  548. r = 0;
  549. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  550. v1.set( - vFrom.y, vFrom.x, 0 );
  551. } else {
  552. v1.set( 0, - vFrom.z, vFrom.y );
  553. }
  554. } else {
  555. v1.crossVectors( vFrom, vTo );
  556. }
  557. this._x = v1.x;
  558. this._y = v1.y;
  559. this._z = v1.z;
  560. this._w = r;
  561. this.normalize();
  562. return this;
  563. }
  564. }(),
  565. inverse: function () {
  566. this.conjugate().normalize();
  567. return this;
  568. },
  569. conjugate: function () {
  570. this._x *= -1;
  571. this._y *= -1;
  572. this._z *= -1;
  573. this.onChangeCallback();
  574. return this;
  575. },
  576. lengthSq: function () {
  577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  578. },
  579. length: function () {
  580. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  581. },
  582. normalize: function () {
  583. var l = this.length();
  584. if ( l === 0 ) {
  585. this._x = 0;
  586. this._y = 0;
  587. this._z = 0;
  588. this._w = 1;
  589. } else {
  590. l = 1 / l;
  591. this._x = this._x * l;
  592. this._y = this._y * l;
  593. this._z = this._z * l;
  594. this._w = this._w * l;
  595. }
  596. this.onChangeCallback();
  597. return this;
  598. },
  599. multiply: function ( q, p ) {
  600. if ( p !== undefined ) {
  601. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  602. return this.multiplyQuaternions( q, p );
  603. }
  604. return this.multiplyQuaternions( this, q );
  605. },
  606. multiplyQuaternions: function ( a, b ) {
  607. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  608. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  609. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  610. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  611. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  612. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  613. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  614. this.onChangeCallback();
  615. return this;
  616. },
  617. multiplyVector3: function ( vector ) {
  618. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  619. return vector.applyQuaternion( this );
  620. },
  621. slerp: function ( qb, t ) {
  622. var x = this._x, y = this._y, z = this._z, w = this._w;
  623. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  624. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  625. if ( cosHalfTheta < 0 ) {
  626. this._w = -qb._w;
  627. this._x = -qb._x;
  628. this._y = -qb._y;
  629. this._z = -qb._z;
  630. cosHalfTheta = -cosHalfTheta;
  631. } else {
  632. this.copy( qb );
  633. }
  634. if ( cosHalfTheta >= 1.0 ) {
  635. this._w = w;
  636. this._x = x;
  637. this._y = y;
  638. this._z = z;
  639. return this;
  640. }
  641. var halfTheta = Math.acos( cosHalfTheta );
  642. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  643. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  644. this._w = 0.5 * ( w + this._w );
  645. this._x = 0.5 * ( x + this._x );
  646. this._y = 0.5 * ( y + this._y );
  647. this._z = 0.5 * ( z + this._z );
  648. return this;
  649. }
  650. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  651. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  652. this._w = ( w * ratioA + this._w * ratioB );
  653. this._x = ( x * ratioA + this._x * ratioB );
  654. this._y = ( y * ratioA + this._y * ratioB );
  655. this._z = ( z * ratioA + this._z * ratioB );
  656. this.onChangeCallback();
  657. return this;
  658. },
  659. equals: function ( quaternion ) {
  660. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  661. },
  662. fromArray: function ( array ) {
  663. this._x = array[ 0 ];
  664. this._y = array[ 1 ];
  665. this._z = array[ 2 ];
  666. this._w = array[ 3 ];
  667. this.onChangeCallback();
  668. return this;
  669. },
  670. toArray: function () {
  671. return [ this._x, this._y, this._z, this._w ];
  672. },
  673. onChange: function ( callback ) {
  674. this.onChangeCallback = callback;
  675. return this;
  676. },
  677. onChangeCallback: function () {},
  678. clone: function () {
  679. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  680. }
  681. };
  682. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  683. return qm.copy( qa ).slerp( qb, t );
  684. }
  685. /**
  686. * @author mrdoob / http://mrdoob.com/
  687. * @author philogb / http://blog.thejit.org/
  688. * @author egraether / http://egraether.com/
  689. * @author zz85 / http://www.lab4games.net/zz85/blog
  690. */
  691. THREE.Vector2 = function ( x, y ) {
  692. this.x = x || 0;
  693. this.y = y || 0;
  694. };
  695. THREE.Vector2.prototype = {
  696. constructor: THREE.Vector2,
  697. set: function ( x, y ) {
  698. this.x = x;
  699. this.y = y;
  700. return this;
  701. },
  702. setX: function ( x ) {
  703. this.x = x;
  704. return this;
  705. },
  706. setY: function ( y ) {
  707. this.y = y;
  708. return this;
  709. },
  710. setComponent: function ( index, value ) {
  711. switch ( index ) {
  712. case 0: this.x = value; break;
  713. case 1: this.y = value; break;
  714. default: throw new Error( "index is out of range: " + index );
  715. }
  716. },
  717. getComponent: function ( index ) {
  718. switch ( index ) {
  719. case 0: return this.x;
  720. case 1: return this.y;
  721. default: throw new Error( "index is out of range: " + index );
  722. }
  723. },
  724. copy: function ( v ) {
  725. this.x = v.x;
  726. this.y = v.y;
  727. return this;
  728. },
  729. add: function ( v, w ) {
  730. if ( w !== undefined ) {
  731. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  732. return this.addVectors( v, w );
  733. }
  734. this.x += v.x;
  735. this.y += v.y;
  736. return this;
  737. },
  738. addVectors: function ( a, b ) {
  739. this.x = a.x + b.x;
  740. this.y = a.y + b.y;
  741. return this;
  742. },
  743. addScalar: function ( s ) {
  744. this.x += s;
  745. this.y += s;
  746. return this;
  747. },
  748. sub: function ( v, w ) {
  749. if ( w !== undefined ) {
  750. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  751. return this.subVectors( v, w );
  752. }
  753. this.x -= v.x;
  754. this.y -= v.y;
  755. return this;
  756. },
  757. subVectors: function ( a, b ) {
  758. this.x = a.x - b.x;
  759. this.y = a.y - b.y;
  760. return this;
  761. },
  762. multiply: function ( v ) {
  763. this.x *= v.x;
  764. this.y *= v.y;
  765. return this;
  766. },
  767. multiplyScalar: function ( s ) {
  768. this.x *= s;
  769. this.y *= s;
  770. return this;
  771. },
  772. divide: function ( v ) {
  773. this.x /= v.x;
  774. this.y /= v.y;
  775. return this;
  776. },
  777. divideScalar: function ( scalar ) {
  778. if ( scalar !== 0 ) {
  779. var invScalar = 1 / scalar;
  780. this.x *= invScalar;
  781. this.y *= invScalar;
  782. } else {
  783. this.x = 0;
  784. this.y = 0;
  785. }
  786. return this;
  787. },
  788. min: function ( v ) {
  789. if ( this.x > v.x ) {
  790. this.x = v.x;
  791. }
  792. if ( this.y > v.y ) {
  793. this.y = v.y;
  794. }
  795. return this;
  796. },
  797. max: function ( v ) {
  798. if ( this.x < v.x ) {
  799. this.x = v.x;
  800. }
  801. if ( this.y < v.y ) {
  802. this.y = v.y;
  803. }
  804. return this;
  805. },
  806. clamp: function ( min, max ) {
  807. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  808. if ( this.x < min.x ) {
  809. this.x = min.x;
  810. } else if ( this.x > max.x ) {
  811. this.x = max.x;
  812. }
  813. if ( this.y < min.y ) {
  814. this.y = min.y;
  815. } else if ( this.y > max.y ) {
  816. this.y = max.y;
  817. }
  818. return this;
  819. },
  820. clampScalar: ( function () {
  821. var min, max;
  822. return function ( minVal, maxVal ) {
  823. if ( min === undefined ) {
  824. min = new THREE.Vector2();
  825. max = new THREE.Vector2();
  826. }
  827. min.set( minVal, minVal );
  828. max.set( maxVal, maxVal );
  829. return this.clamp( min, max );
  830. };
  831. } )(),
  832. floor: function () {
  833. this.x = Math.floor( this.x );
  834. this.y = Math.floor( this.y );
  835. return this;
  836. },
  837. ceil: function () {
  838. this.x = Math.ceil( this.x );
  839. this.y = Math.ceil( this.y );
  840. return this;
  841. },
  842. round: function () {
  843. this.x = Math.round( this.x );
  844. this.y = Math.round( this.y );
  845. return this;
  846. },
  847. roundToZero: function () {
  848. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  849. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  850. return this;
  851. },
  852. negate: function () {
  853. return this.multiplyScalar( - 1 );
  854. },
  855. dot: function ( v ) {
  856. return this.x * v.x + this.y * v.y;
  857. },
  858. lengthSq: function () {
  859. return this.x * this.x + this.y * this.y;
  860. },
  861. length: function () {
  862. return Math.sqrt( this.x * this.x + this.y * this.y );
  863. },
  864. normalize: function () {
  865. return this.divideScalar( this.length() );
  866. },
  867. distanceTo: function ( v ) {
  868. return Math.sqrt( this.distanceToSquared( v ) );
  869. },
  870. distanceToSquared: function ( v ) {
  871. var dx = this.x - v.x, dy = this.y - v.y;
  872. return dx * dx + dy * dy;
  873. },
  874. setLength: function ( l ) {
  875. var oldLength = this.length();
  876. if ( oldLength !== 0 && l !== oldLength ) {
  877. this.multiplyScalar( l / oldLength );
  878. }
  879. return this;
  880. },
  881. lerp: function ( v, alpha ) {
  882. this.x += ( v.x - this.x ) * alpha;
  883. this.y += ( v.y - this.y ) * alpha;
  884. return this;
  885. },
  886. equals: function( v ) {
  887. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  888. },
  889. fromArray: function ( array ) {
  890. this.x = array[ 0 ];
  891. this.y = array[ 1 ];
  892. return this;
  893. },
  894. toArray: function () {
  895. return [ this.x, this.y ];
  896. },
  897. clone: function () {
  898. return new THREE.Vector2( this.x, this.y );
  899. }
  900. };
  901. /**
  902. * @author mrdoob / http://mrdoob.com/
  903. * @author *kile / http://kile.stravaganza.org/
  904. * @author philogb / http://blog.thejit.org/
  905. * @author mikael emtinger / http://gomo.se/
  906. * @author egraether / http://egraether.com/
  907. * @author WestLangley / http://github.com/WestLangley
  908. */
  909. THREE.Vector3 = function ( x, y, z ) {
  910. this.x = x || 0;
  911. this.y = y || 0;
  912. this.z = z || 0;
  913. };
  914. THREE.Vector3.prototype = {
  915. constructor: THREE.Vector3,
  916. set: function ( x, y, z ) {
  917. this.x = x;
  918. this.y = y;
  919. this.z = z;
  920. return this;
  921. },
  922. setX: function ( x ) {
  923. this.x = x;
  924. return this;
  925. },
  926. setY: function ( y ) {
  927. this.y = y;
  928. return this;
  929. },
  930. setZ: function ( z ) {
  931. this.z = z;
  932. return this;
  933. },
  934. setComponent: function ( index, value ) {
  935. switch ( index ) {
  936. case 0: this.x = value; break;
  937. case 1: this.y = value; break;
  938. case 2: this.z = value; break;
  939. default: throw new Error( "index is out of range: " + index );
  940. }
  941. },
  942. getComponent: function ( index ) {
  943. switch ( index ) {
  944. case 0: return this.x;
  945. case 1: return this.y;
  946. case 2: return this.z;
  947. default: throw new Error( "index is out of range: " + index );
  948. }
  949. },
  950. copy: function ( v ) {
  951. this.x = v.x;
  952. this.y = v.y;
  953. this.z = v.z;
  954. return this;
  955. },
  956. add: function ( v, w ) {
  957. if ( w !== undefined ) {
  958. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  959. return this.addVectors( v, w );
  960. }
  961. this.x += v.x;
  962. this.y += v.y;
  963. this.z += v.z;
  964. return this;
  965. },
  966. addScalar: function ( s ) {
  967. this.x += s;
  968. this.y += s;
  969. this.z += s;
  970. return this;
  971. },
  972. addVectors: function ( a, b ) {
  973. this.x = a.x + b.x;
  974. this.y = a.y + b.y;
  975. this.z = a.z + b.z;
  976. return this;
  977. },
  978. sub: function ( v, w ) {
  979. if ( w !== undefined ) {
  980. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  981. return this.subVectors( v, w );
  982. }
  983. this.x -= v.x;
  984. this.y -= v.y;
  985. this.z -= v.z;
  986. return this;
  987. },
  988. subVectors: function ( a, b ) {
  989. this.x = a.x - b.x;
  990. this.y = a.y - b.y;
  991. this.z = a.z - b.z;
  992. return this;
  993. },
  994. multiply: function ( v, w ) {
  995. if ( w !== undefined ) {
  996. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  997. return this.multiplyVectors( v, w );
  998. }
  999. this.x *= v.x;
  1000. this.y *= v.y;
  1001. this.z *= v.z;
  1002. return this;
  1003. },
  1004. multiplyScalar: function ( scalar ) {
  1005. this.x *= scalar;
  1006. this.y *= scalar;
  1007. this.z *= scalar;
  1008. return this;
  1009. },
  1010. multiplyVectors: function ( a, b ) {
  1011. this.x = a.x * b.x;
  1012. this.y = a.y * b.y;
  1013. this.z = a.z * b.z;
  1014. return this;
  1015. },
  1016. applyEuler: function () {
  1017. var quaternion;
  1018. return function ( euler ) {
  1019. if ( euler instanceof THREE.Euler === false ) {
  1020. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1021. }
  1022. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1023. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1024. return this;
  1025. };
  1026. }(),
  1027. applyAxisAngle: function () {
  1028. var quaternion;
  1029. return function ( axis, angle ) {
  1030. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1031. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1032. return this;
  1033. };
  1034. }(),
  1035. applyMatrix3: function ( m ) {
  1036. var x = this.x;
  1037. var y = this.y;
  1038. var z = this.z;
  1039. var e = m.elements;
  1040. this.x = e[0] * x + e[3] * y + e[6] * z;
  1041. this.y = e[1] * x + e[4] * y + e[7] * z;
  1042. this.z = e[2] * x + e[5] * y + e[8] * z;
  1043. return this;
  1044. },
  1045. applyMatrix4: function ( m ) {
  1046. // input: THREE.Matrix4 affine matrix
  1047. var x = this.x, y = this.y, z = this.z;
  1048. var e = m.elements;
  1049. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1050. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1051. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1052. return this;
  1053. },
  1054. applyProjection: function ( m ) {
  1055. // input: THREE.Matrix4 projection matrix
  1056. var x = this.x, y = this.y, z = this.z;
  1057. var e = m.elements;
  1058. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1059. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1060. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1061. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1062. return this;
  1063. },
  1064. applyQuaternion: function ( q ) {
  1065. var x = this.x;
  1066. var y = this.y;
  1067. var z = this.z;
  1068. var qx = q.x;
  1069. var qy = q.y;
  1070. var qz = q.z;
  1071. var qw = q.w;
  1072. // calculate quat * vector
  1073. var ix = qw * x + qy * z - qz * y;
  1074. var iy = qw * y + qz * x - qx * z;
  1075. var iz = qw * z + qx * y - qy * x;
  1076. var iw = -qx * x - qy * y - qz * z;
  1077. // calculate result * inverse quat
  1078. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1079. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1080. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1081. return this;
  1082. },
  1083. transformDirection: function ( m ) {
  1084. // input: THREE.Matrix4 affine matrix
  1085. // vector interpreted as a direction
  1086. var x = this.x, y = this.y, z = this.z;
  1087. var e = m.elements;
  1088. this.x = e[0] * x + e[4] * y + e[8] * z;
  1089. this.y = e[1] * x + e[5] * y + e[9] * z;
  1090. this.z = e[2] * x + e[6] * y + e[10] * z;
  1091. this.normalize();
  1092. return this;
  1093. },
  1094. divide: function ( v ) {
  1095. this.x /= v.x;
  1096. this.y /= v.y;
  1097. this.z /= v.z;
  1098. return this;
  1099. },
  1100. divideScalar: function ( scalar ) {
  1101. if ( scalar !== 0 ) {
  1102. var invScalar = 1 / scalar;
  1103. this.x *= invScalar;
  1104. this.y *= invScalar;
  1105. this.z *= invScalar;
  1106. } else {
  1107. this.x = 0;
  1108. this.y = 0;
  1109. this.z = 0;
  1110. }
  1111. return this;
  1112. },
  1113. min: function ( v ) {
  1114. if ( this.x > v.x ) {
  1115. this.x = v.x;
  1116. }
  1117. if ( this.y > v.y ) {
  1118. this.y = v.y;
  1119. }
  1120. if ( this.z > v.z ) {
  1121. this.z = v.z;
  1122. }
  1123. return this;
  1124. },
  1125. max: function ( v ) {
  1126. if ( this.x < v.x ) {
  1127. this.x = v.x;
  1128. }
  1129. if ( this.y < v.y ) {
  1130. this.y = v.y;
  1131. }
  1132. if ( this.z < v.z ) {
  1133. this.z = v.z;
  1134. }
  1135. return this;
  1136. },
  1137. clamp: function ( min, max ) {
  1138. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1139. if ( this.x < min.x ) {
  1140. this.x = min.x;
  1141. } else if ( this.x > max.x ) {
  1142. this.x = max.x;
  1143. }
  1144. if ( this.y < min.y ) {
  1145. this.y = min.y;
  1146. } else if ( this.y > max.y ) {
  1147. this.y = max.y;
  1148. }
  1149. if ( this.z < min.z ) {
  1150. this.z = min.z;
  1151. } else if ( this.z > max.z ) {
  1152. this.z = max.z;
  1153. }
  1154. return this;
  1155. },
  1156. clampScalar: ( function () {
  1157. var min, max;
  1158. return function ( minVal, maxVal ) {
  1159. if ( min === undefined ) {
  1160. min = new THREE.Vector3();
  1161. max = new THREE.Vector3();
  1162. }
  1163. min.set( minVal, minVal, minVal );
  1164. max.set( maxVal, maxVal, maxVal );
  1165. return this.clamp( min, max );
  1166. };
  1167. } )(),
  1168. floor: function () {
  1169. this.x = Math.floor( this.x );
  1170. this.y = Math.floor( this.y );
  1171. this.z = Math.floor( this.z );
  1172. return this;
  1173. },
  1174. ceil: function () {
  1175. this.x = Math.ceil( this.x );
  1176. this.y = Math.ceil( this.y );
  1177. this.z = Math.ceil( this.z );
  1178. return this;
  1179. },
  1180. round: function () {
  1181. this.x = Math.round( this.x );
  1182. this.y = Math.round( this.y );
  1183. this.z = Math.round( this.z );
  1184. return this;
  1185. },
  1186. roundToZero: function () {
  1187. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1188. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1189. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1190. return this;
  1191. },
  1192. negate: function () {
  1193. return this.multiplyScalar( - 1 );
  1194. },
  1195. dot: function ( v ) {
  1196. return this.x * v.x + this.y * v.y + this.z * v.z;
  1197. },
  1198. lengthSq: function () {
  1199. return this.x * this.x + this.y * this.y + this.z * this.z;
  1200. },
  1201. length: function () {
  1202. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1203. },
  1204. lengthManhattan: function () {
  1205. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1206. },
  1207. normalize: function () {
  1208. return this.divideScalar( this.length() );
  1209. },
  1210. setLength: function ( l ) {
  1211. var oldLength = this.length();
  1212. if ( oldLength !== 0 && l !== oldLength ) {
  1213. this.multiplyScalar( l / oldLength );
  1214. }
  1215. return this;
  1216. },
  1217. lerp: function ( v, alpha ) {
  1218. this.x += ( v.x - this.x ) * alpha;
  1219. this.y += ( v.y - this.y ) * alpha;
  1220. this.z += ( v.z - this.z ) * alpha;
  1221. return this;
  1222. },
  1223. cross: function ( v, w ) {
  1224. if ( w !== undefined ) {
  1225. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1226. return this.crossVectors( v, w );
  1227. }
  1228. var x = this.x, y = this.y, z = this.z;
  1229. this.x = y * v.z - z * v.y;
  1230. this.y = z * v.x - x * v.z;
  1231. this.z = x * v.y - y * v.x;
  1232. return this;
  1233. },
  1234. crossVectors: function ( a, b ) {
  1235. var ax = a.x, ay = a.y, az = a.z;
  1236. var bx = b.x, by = b.y, bz = b.z;
  1237. this.x = ay * bz - az * by;
  1238. this.y = az * bx - ax * bz;
  1239. this.z = ax * by - ay * bx;
  1240. return this;
  1241. },
  1242. projectOnVector: function () {
  1243. var v1, dot;
  1244. return function ( vector ) {
  1245. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1246. v1.copy( vector ).normalize();
  1247. dot = this.dot( v1 );
  1248. return this.copy( v1 ).multiplyScalar( dot );
  1249. };
  1250. }(),
  1251. projectOnPlane: function () {
  1252. var v1;
  1253. return function ( planeNormal ) {
  1254. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1255. v1.copy( this ).projectOnVector( planeNormal );
  1256. return this.sub( v1 );
  1257. }
  1258. }(),
  1259. reflect: function () {
  1260. // reflect incident vector off plane orthogonal to normal
  1261. // normal is assumed to have unit length
  1262. var v1;
  1263. return function ( normal ) {
  1264. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1265. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1266. }
  1267. }(),
  1268. angleTo: function ( v ) {
  1269. var theta = this.dot( v ) / ( this.length() * v.length() );
  1270. // clamp, to handle numerical problems
  1271. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1272. },
  1273. distanceTo: function ( v ) {
  1274. return Math.sqrt( this.distanceToSquared( v ) );
  1275. },
  1276. distanceToSquared: function ( v ) {
  1277. var dx = this.x - v.x;
  1278. var dy = this.y - v.y;
  1279. var dz = this.z - v.z;
  1280. return dx * dx + dy * dy + dz * dz;
  1281. },
  1282. setEulerFromRotationMatrix: function ( m, order ) {
  1283. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1284. },
  1285. setEulerFromQuaternion: function ( q, order ) {
  1286. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1287. },
  1288. getPositionFromMatrix: function ( m ) {
  1289. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1290. return this.setFromMatrixPosition( m );
  1291. },
  1292. getScaleFromMatrix: function ( m ) {
  1293. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1294. return this.setFromMatrixScale( m );
  1295. },
  1296. getColumnFromMatrix: function ( index, matrix ) {
  1297. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1298. return this.setFromMatrixColumn( index, matrix );
  1299. },
  1300. setFromMatrixPosition: function ( m ) {
  1301. this.x = m.elements[ 12 ];
  1302. this.y = m.elements[ 13 ];
  1303. this.z = m.elements[ 14 ];
  1304. return this;
  1305. },
  1306. setFromMatrixScale: function ( m ) {
  1307. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1308. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1309. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1310. this.x = sx;
  1311. this.y = sy;
  1312. this.z = sz;
  1313. return this;
  1314. },
  1315. setFromMatrixColumn: function ( index, matrix ) {
  1316. var offset = index * 4;
  1317. var me = matrix.elements;
  1318. this.x = me[ offset ];
  1319. this.y = me[ offset + 1 ];
  1320. this.z = me[ offset + 2 ];
  1321. return this;
  1322. },
  1323. equals: function ( v ) {
  1324. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1325. },
  1326. fromArray: function ( array ) {
  1327. this.x = array[ 0 ];
  1328. this.y = array[ 1 ];
  1329. this.z = array[ 2 ];
  1330. return this;
  1331. },
  1332. toArray: function () {
  1333. return [ this.x, this.y, this.z ];
  1334. },
  1335. clone: function () {
  1336. return new THREE.Vector3( this.x, this.y, this.z );
  1337. }
  1338. };
  1339. /**
  1340. * @author supereggbert / http://www.paulbrunt.co.uk/
  1341. * @author philogb / http://blog.thejit.org/
  1342. * @author mikael emtinger / http://gomo.se/
  1343. * @author egraether / http://egraether.com/
  1344. * @author WestLangley / http://github.com/WestLangley
  1345. */
  1346. THREE.Vector4 = function ( x, y, z, w ) {
  1347. this.x = x || 0;
  1348. this.y = y || 0;
  1349. this.z = z || 0;
  1350. this.w = ( w !== undefined ) ? w : 1;
  1351. };
  1352. THREE.Vector4.prototype = {
  1353. constructor: THREE.Vector4,
  1354. set: function ( x, y, z, w ) {
  1355. this.x = x;
  1356. this.y = y;
  1357. this.z = z;
  1358. this.w = w;
  1359. return this;
  1360. },
  1361. setX: function ( x ) {
  1362. this.x = x;
  1363. return this;
  1364. },
  1365. setY: function ( y ) {
  1366. this.y = y;
  1367. return this;
  1368. },
  1369. setZ: function ( z ) {
  1370. this.z = z;
  1371. return this;
  1372. },
  1373. setW: function ( w ) {
  1374. this.w = w;
  1375. return this;
  1376. },
  1377. setComponent: function ( index, value ) {
  1378. switch ( index ) {
  1379. case 0: this.x = value; break;
  1380. case 1: this.y = value; break;
  1381. case 2: this.z = value; break;
  1382. case 3: this.w = value; break;
  1383. default: throw new Error( "index is out of range: " + index );
  1384. }
  1385. },
  1386. getComponent: function ( index ) {
  1387. switch ( index ) {
  1388. case 0: return this.x;
  1389. case 1: return this.y;
  1390. case 2: return this.z;
  1391. case 3: return this.w;
  1392. default: throw new Error( "index is out of range: " + index );
  1393. }
  1394. },
  1395. copy: function ( v ) {
  1396. this.x = v.x;
  1397. this.y = v.y;
  1398. this.z = v.z;
  1399. this.w = ( v.w !== undefined ) ? v.w : 1;
  1400. return this;
  1401. },
  1402. add: function ( v, w ) {
  1403. if ( w !== undefined ) {
  1404. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1405. return this.addVectors( v, w );
  1406. }
  1407. this.x += v.x;
  1408. this.y += v.y;
  1409. this.z += v.z;
  1410. this.w += v.w;
  1411. return this;
  1412. },
  1413. addScalar: function ( s ) {
  1414. this.x += s;
  1415. this.y += s;
  1416. this.z += s;
  1417. this.w += s;
  1418. return this;
  1419. },
  1420. addVectors: function ( a, b ) {
  1421. this.x = a.x + b.x;
  1422. this.y = a.y + b.y;
  1423. this.z = a.z + b.z;
  1424. this.w = a.w + b.w;
  1425. return this;
  1426. },
  1427. sub: function ( v, w ) {
  1428. if ( w !== undefined ) {
  1429. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1430. return this.subVectors( v, w );
  1431. }
  1432. this.x -= v.x;
  1433. this.y -= v.y;
  1434. this.z -= v.z;
  1435. this.w -= v.w;
  1436. return this;
  1437. },
  1438. subVectors: function ( a, b ) {
  1439. this.x = a.x - b.x;
  1440. this.y = a.y - b.y;
  1441. this.z = a.z - b.z;
  1442. this.w = a.w - b.w;
  1443. return this;
  1444. },
  1445. multiplyScalar: function ( scalar ) {
  1446. this.x *= scalar;
  1447. this.y *= scalar;
  1448. this.z *= scalar;
  1449. this.w *= scalar;
  1450. return this;
  1451. },
  1452. applyMatrix4: function ( m ) {
  1453. var x = this.x;
  1454. var y = this.y;
  1455. var z = this.z;
  1456. var w = this.w;
  1457. var e = m.elements;
  1458. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1459. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1460. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1461. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1462. return this;
  1463. },
  1464. divideScalar: function ( scalar ) {
  1465. if ( scalar !== 0 ) {
  1466. var invScalar = 1 / scalar;
  1467. this.x *= invScalar;
  1468. this.y *= invScalar;
  1469. this.z *= invScalar;
  1470. this.w *= invScalar;
  1471. } else {
  1472. this.x = 0;
  1473. this.y = 0;
  1474. this.z = 0;
  1475. this.w = 1;
  1476. }
  1477. return this;
  1478. },
  1479. setAxisAngleFromQuaternion: function ( q ) {
  1480. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1481. // q is assumed to be normalized
  1482. this.w = 2 * Math.acos( q.w );
  1483. var s = Math.sqrt( 1 - q.w * q.w );
  1484. if ( s < 0.0001 ) {
  1485. this.x = 1;
  1486. this.y = 0;
  1487. this.z = 0;
  1488. } else {
  1489. this.x = q.x / s;
  1490. this.y = q.y / s;
  1491. this.z = q.z / s;
  1492. }
  1493. return this;
  1494. },
  1495. setAxisAngleFromRotationMatrix: function ( m ) {
  1496. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1497. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1498. var angle, x, y, z, // variables for result
  1499. epsilon = 0.01, // margin to allow for rounding errors
  1500. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1501. te = m.elements,
  1502. m11 = te[0], m12 = te[4], m13 = te[8],
  1503. m21 = te[1], m22 = te[5], m23 = te[9],
  1504. m31 = te[2], m32 = te[6], m33 = te[10];
  1505. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1506. && ( Math.abs( m13 - m31 ) < epsilon )
  1507. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1508. // singularity found
  1509. // first check for identity matrix which must have +1 for all terms
  1510. // in leading diagonal and zero in other terms
  1511. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1512. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1513. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1514. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1515. // this singularity is identity matrix so angle = 0
  1516. this.set( 1, 0, 0, 0 );
  1517. return this; // zero angle, arbitrary axis
  1518. }
  1519. // otherwise this singularity is angle = 180
  1520. angle = Math.PI;
  1521. var xx = ( m11 + 1 ) / 2;
  1522. var yy = ( m22 + 1 ) / 2;
  1523. var zz = ( m33 + 1 ) / 2;
  1524. var xy = ( m12 + m21 ) / 4;
  1525. var xz = ( m13 + m31 ) / 4;
  1526. var yz = ( m23 + m32 ) / 4;
  1527. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1528. if ( xx < epsilon ) {
  1529. x = 0;
  1530. y = 0.707106781;
  1531. z = 0.707106781;
  1532. } else {
  1533. x = Math.sqrt( xx );
  1534. y = xy / x;
  1535. z = xz / x;
  1536. }
  1537. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1538. if ( yy < epsilon ) {
  1539. x = 0.707106781;
  1540. y = 0;
  1541. z = 0.707106781;
  1542. } else {
  1543. y = Math.sqrt( yy );
  1544. x = xy / y;
  1545. z = yz / y;
  1546. }
  1547. } else { // m33 is the largest diagonal term so base result on this
  1548. if ( zz < epsilon ) {
  1549. x = 0.707106781;
  1550. y = 0.707106781;
  1551. z = 0;
  1552. } else {
  1553. z = Math.sqrt( zz );
  1554. x = xz / z;
  1555. y = yz / z;
  1556. }
  1557. }
  1558. this.set( x, y, z, angle );
  1559. return this; // return 180 deg rotation
  1560. }
  1561. // as we have reached here there are no singularities so we can handle normally
  1562. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1563. + ( m13 - m31 ) * ( m13 - m31 )
  1564. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1565. if ( Math.abs( s ) < 0.001 ) s = 1;
  1566. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1567. // caught by singularity test above, but I've left it in just in case
  1568. this.x = ( m32 - m23 ) / s;
  1569. this.y = ( m13 - m31 ) / s;
  1570. this.z = ( m21 - m12 ) / s;
  1571. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1572. return this;
  1573. },
  1574. min: function ( v ) {
  1575. if ( this.x > v.x ) {
  1576. this.x = v.x;
  1577. }
  1578. if ( this.y > v.y ) {
  1579. this.y = v.y;
  1580. }
  1581. if ( this.z > v.z ) {
  1582. this.z = v.z;
  1583. }
  1584. if ( this.w > v.w ) {
  1585. this.w = v.w;
  1586. }
  1587. return this;
  1588. },
  1589. max: function ( v ) {
  1590. if ( this.x < v.x ) {
  1591. this.x = v.x;
  1592. }
  1593. if ( this.y < v.y ) {
  1594. this.y = v.y;
  1595. }
  1596. if ( this.z < v.z ) {
  1597. this.z = v.z;
  1598. }
  1599. if ( this.w < v.w ) {
  1600. this.w = v.w;
  1601. }
  1602. return this;
  1603. },
  1604. clamp: function ( min, max ) {
  1605. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1606. if ( this.x < min.x ) {
  1607. this.x = min.x;
  1608. } else if ( this.x > max.x ) {
  1609. this.x = max.x;
  1610. }
  1611. if ( this.y < min.y ) {
  1612. this.y = min.y;
  1613. } else if ( this.y > max.y ) {
  1614. this.y = max.y;
  1615. }
  1616. if ( this.z < min.z ) {
  1617. this.z = min.z;
  1618. } else if ( this.z > max.z ) {
  1619. this.z = max.z;
  1620. }
  1621. if ( this.w < min.w ) {
  1622. this.w = min.w;
  1623. } else if ( this.w > max.w ) {
  1624. this.w = max.w;
  1625. }
  1626. return this;
  1627. },
  1628. clampScalar: ( function () {
  1629. var min, max;
  1630. return function ( minVal, maxVal ) {
  1631. if ( min === undefined ) {
  1632. min = new THREE.Vector4();
  1633. max = new THREE.Vector4();
  1634. }
  1635. min.set( minVal, minVal, minVal, minVal );
  1636. max.set( maxVal, maxVal, maxVal, maxVal );
  1637. return this.clamp( min, max );
  1638. };
  1639. } )(),
  1640. floor: function () {
  1641. this.x = Math.floor( this.x );
  1642. this.y = Math.floor( this.y );
  1643. this.z = Math.floor( this.z );
  1644. this.w = Math.floor( this.w );
  1645. return this;
  1646. },
  1647. ceil: function () {
  1648. this.x = Math.ceil( this.x );
  1649. this.y = Math.ceil( this.y );
  1650. this.z = Math.ceil( this.z );
  1651. this.w = Math.ceil( this.w );
  1652. return this;
  1653. },
  1654. round: function () {
  1655. this.x = Math.round( this.x );
  1656. this.y = Math.round( this.y );
  1657. this.z = Math.round( this.z );
  1658. this.w = Math.round( this.w );
  1659. return this;
  1660. },
  1661. roundToZero: function () {
  1662. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1663. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1664. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1665. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1666. return this;
  1667. },
  1668. negate: function () {
  1669. return this.multiplyScalar( -1 );
  1670. },
  1671. dot: function ( v ) {
  1672. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1673. },
  1674. lengthSq: function () {
  1675. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1676. },
  1677. length: function () {
  1678. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1679. },
  1680. lengthManhattan: function () {
  1681. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1682. },
  1683. normalize: function () {
  1684. return this.divideScalar( this.length() );
  1685. },
  1686. setLength: function ( l ) {
  1687. var oldLength = this.length();
  1688. if ( oldLength !== 0 && l !== oldLength ) {
  1689. this.multiplyScalar( l / oldLength );
  1690. }
  1691. return this;
  1692. },
  1693. lerp: function ( v, alpha ) {
  1694. this.x += ( v.x - this.x ) * alpha;
  1695. this.y += ( v.y - this.y ) * alpha;
  1696. this.z += ( v.z - this.z ) * alpha;
  1697. this.w += ( v.w - this.w ) * alpha;
  1698. return this;
  1699. },
  1700. equals: function ( v ) {
  1701. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1702. },
  1703. fromArray: function ( array ) {
  1704. this.x = array[ 0 ];
  1705. this.y = array[ 1 ];
  1706. this.z = array[ 2 ];
  1707. this.w = array[ 3 ];
  1708. return this;
  1709. },
  1710. toArray: function () {
  1711. return [ this.x, this.y, this.z, this.w ];
  1712. },
  1713. clone: function () {
  1714. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1715. }
  1716. };
  1717. /**
  1718. * @author mrdoob / http://mrdoob.com/
  1719. * @author WestLangley / http://github.com/WestLangley
  1720. * @author bhouston / http://exocortex.com
  1721. */
  1722. THREE.Euler = function ( x, y, z, order ) {
  1723. this._x = x || 0;
  1724. this._y = y || 0;
  1725. this._z = z || 0;
  1726. this._order = order || THREE.Euler.DefaultOrder;
  1727. };
  1728. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1729. THREE.Euler.DefaultOrder = 'XYZ';
  1730. THREE.Euler.prototype = {
  1731. constructor: THREE.Euler,
  1732. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1733. get x () {
  1734. return this._x;
  1735. },
  1736. set x ( value ) {
  1737. this._x = value;
  1738. this.onChangeCallback();
  1739. },
  1740. get y () {
  1741. return this._y;
  1742. },
  1743. set y ( value ) {
  1744. this._y = value;
  1745. this.onChangeCallback();
  1746. },
  1747. get z () {
  1748. return this._z;
  1749. },
  1750. set z ( value ) {
  1751. this._z = value;
  1752. this.onChangeCallback();
  1753. },
  1754. get order () {
  1755. return this._order;
  1756. },
  1757. set order ( value ) {
  1758. this._order = value;
  1759. this.onChangeCallback();
  1760. },
  1761. set: function ( x, y, z, order ) {
  1762. this._x = x;
  1763. this._y = y;
  1764. this._z = z;
  1765. this._order = order || this._order;
  1766. this.onChangeCallback();
  1767. return this;
  1768. },
  1769. copy: function ( euler ) {
  1770. this._x = euler._x;
  1771. this._y = euler._y;
  1772. this._z = euler._z;
  1773. this._order = euler._order;
  1774. this.onChangeCallback();
  1775. return this;
  1776. },
  1777. setFromRotationMatrix: function ( m, order ) {
  1778. var clamp = THREE.Math.clamp;
  1779. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1780. var te = m.elements;
  1781. var m11 = te[0], m12 = te[4], m13 = te[8];
  1782. var m21 = te[1], m22 = te[5], m23 = te[9];
  1783. var m31 = te[2], m32 = te[6], m33 = te[10];
  1784. order = order || this._order;
  1785. if ( order === 'XYZ' ) {
  1786. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1787. if ( Math.abs( m13 ) < 0.99999 ) {
  1788. this._x = Math.atan2( - m23, m33 );
  1789. this._z = Math.atan2( - m12, m11 );
  1790. } else {
  1791. this._x = Math.atan2( m32, m22 );
  1792. this._z = 0;
  1793. }
  1794. } else if ( order === 'YXZ' ) {
  1795. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1796. if ( Math.abs( m23 ) < 0.99999 ) {
  1797. this._y = Math.atan2( m13, m33 );
  1798. this._z = Math.atan2( m21, m22 );
  1799. } else {
  1800. this._y = Math.atan2( - m31, m11 );
  1801. this._z = 0;
  1802. }
  1803. } else if ( order === 'ZXY' ) {
  1804. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1805. if ( Math.abs( m32 ) < 0.99999 ) {
  1806. this._y = Math.atan2( - m31, m33 );
  1807. this._z = Math.atan2( - m12, m22 );
  1808. } else {
  1809. this._y = 0;
  1810. this._z = Math.atan2( m21, m11 );
  1811. }
  1812. } else if ( order === 'ZYX' ) {
  1813. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1814. if ( Math.abs( m31 ) < 0.99999 ) {
  1815. this._x = Math.atan2( m32, m33 );
  1816. this._z = Math.atan2( m21, m11 );
  1817. } else {
  1818. this._x = 0;
  1819. this._z = Math.atan2( - m12, m22 );
  1820. }
  1821. } else if ( order === 'YZX' ) {
  1822. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1823. if ( Math.abs( m21 ) < 0.99999 ) {
  1824. this._x = Math.atan2( - m23, m22 );
  1825. this._y = Math.atan2( - m31, m11 );
  1826. } else {
  1827. this._x = 0;
  1828. this._y = Math.atan2( m13, m33 );
  1829. }
  1830. } else if ( order === 'XZY' ) {
  1831. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1832. if ( Math.abs( m12 ) < 0.99999 ) {
  1833. this._x = Math.atan2( m32, m22 );
  1834. this._y = Math.atan2( m13, m11 );
  1835. } else {
  1836. this._x = Math.atan2( - m23, m33 );
  1837. this._y = 0;
  1838. }
  1839. } else {
  1840. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1841. }
  1842. this._order = order;
  1843. this.onChangeCallback();
  1844. return this;
  1845. },
  1846. setFromQuaternion: function ( q, order, update ) {
  1847. var clamp = THREE.Math.clamp;
  1848. // q is assumed to be normalized
  1849. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1850. var sqx = q.x * q.x;
  1851. var sqy = q.y * q.y;
  1852. var sqz = q.z * q.z;
  1853. var sqw = q.w * q.w;
  1854. order = order || this._order;
  1855. if ( order === 'XYZ' ) {
  1856. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1857. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1858. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1859. } else if ( order === 'YXZ' ) {
  1860. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1861. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1862. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1863. } else if ( order === 'ZXY' ) {
  1864. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1865. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1866. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1867. } else if ( order === 'ZYX' ) {
  1868. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1869. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1870. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1871. } else if ( order === 'YZX' ) {
  1872. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1873. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1874. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1875. } else if ( order === 'XZY' ) {
  1876. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1877. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1878. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1879. } else {
  1880. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1881. }
  1882. this._order = order;
  1883. if ( update !== false ) this.onChangeCallback();
  1884. return this;
  1885. },
  1886. reorder: function () {
  1887. // WARNING: this discards revolution information -bhouston
  1888. var q = new THREE.Quaternion();
  1889. return function ( newOrder ) {
  1890. q.setFromEuler( this );
  1891. this.setFromQuaternion( q, newOrder );
  1892. };
  1893. }(),
  1894. equals: function ( euler ) {
  1895. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1896. },
  1897. fromArray: function ( array ) {
  1898. this._x = array[ 0 ];
  1899. this._y = array[ 1 ];
  1900. this._z = array[ 2 ];
  1901. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1902. this.onChangeCallback();
  1903. return this;
  1904. },
  1905. toArray: function () {
  1906. return [ this._x, this._y, this._z, this._order ];
  1907. },
  1908. onChange: function ( callback ) {
  1909. this.onChangeCallback = callback;
  1910. return this;
  1911. },
  1912. onChangeCallback: function () {},
  1913. clone: function () {
  1914. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1915. }
  1916. };
  1917. /**
  1918. * @author bhouston / http://exocortex.com
  1919. */
  1920. THREE.Line3 = function ( start, end ) {
  1921. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1922. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1923. };
  1924. THREE.Line3.prototype = {
  1925. constructor: THREE.Line3,
  1926. set: function ( start, end ) {
  1927. this.start.copy( start );
  1928. this.end.copy( end );
  1929. return this;
  1930. },
  1931. copy: function ( line ) {
  1932. this.start.copy( line.start );
  1933. this.end.copy( line.end );
  1934. return this;
  1935. },
  1936. center: function ( optionalTarget ) {
  1937. var result = optionalTarget || new THREE.Vector3();
  1938. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1939. },
  1940. delta: function ( optionalTarget ) {
  1941. var result = optionalTarget || new THREE.Vector3();
  1942. return result.subVectors( this.end, this.start );
  1943. },
  1944. distanceSq: function () {
  1945. return this.start.distanceToSquared( this.end );
  1946. },
  1947. distance: function () {
  1948. return this.start.distanceTo( this.end );
  1949. },
  1950. at: function ( t, optionalTarget ) {
  1951. var result = optionalTarget || new THREE.Vector3();
  1952. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1953. },
  1954. closestPointToPointParameter: function() {
  1955. var startP = new THREE.Vector3();
  1956. var startEnd = new THREE.Vector3();
  1957. return function ( point, clampToLine ) {
  1958. startP.subVectors( point, this.start );
  1959. startEnd.subVectors( this.end, this.start );
  1960. var startEnd2 = startEnd.dot( startEnd );
  1961. var startEnd_startP = startEnd.dot( startP );
  1962. var t = startEnd_startP / startEnd2;
  1963. if ( clampToLine ) {
  1964. t = THREE.Math.clamp( t, 0, 1 );
  1965. }
  1966. return t;
  1967. };
  1968. }(),
  1969. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1970. var t = this.closestPointToPointParameter( point, clampToLine );
  1971. var result = optionalTarget || new THREE.Vector3();
  1972. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1973. },
  1974. applyMatrix4: function ( matrix ) {
  1975. this.start.applyMatrix4( matrix );
  1976. this.end.applyMatrix4( matrix );
  1977. return this;
  1978. },
  1979. equals: function ( line ) {
  1980. return line.start.equals( this.start ) && line.end.equals( this.end );
  1981. },
  1982. clone: function () {
  1983. return new THREE.Line3().copy( this );
  1984. }
  1985. };
  1986. /**
  1987. * @author bhouston / http://exocortex.com
  1988. */
  1989. THREE.Box2 = function ( min, max ) {
  1990. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1991. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1992. };
  1993. THREE.Box2.prototype = {
  1994. constructor: THREE.Box2,
  1995. set: function ( min, max ) {
  1996. this.min.copy( min );
  1997. this.max.copy( max );
  1998. return this;
  1999. },
  2000. setFromPoints: function ( points ) {
  2001. if ( points.length > 0 ) {
  2002. var point = points[ 0 ];
  2003. this.min.copy( point );
  2004. this.max.copy( point );
  2005. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2006. point = points[ i ];
  2007. if ( point.x < this.min.x ) {
  2008. this.min.x = point.x;
  2009. } else if ( point.x > this.max.x ) {
  2010. this.max.x = point.x;
  2011. }
  2012. if ( point.y < this.min.y ) {
  2013. this.min.y = point.y;
  2014. } else if ( point.y > this.max.y ) {
  2015. this.max.y = point.y;
  2016. }
  2017. }
  2018. } else {
  2019. this.makeEmpty();
  2020. }
  2021. return this;
  2022. },
  2023. setFromCenterAndSize: function () {
  2024. var v1 = new THREE.Vector2();
  2025. return function ( center, size ) {
  2026. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2027. this.min.copy( center ).sub( halfSize );
  2028. this.max.copy( center ).add( halfSize );
  2029. return this;
  2030. };
  2031. }(),
  2032. copy: function ( box ) {
  2033. this.min.copy( box.min );
  2034. this.max.copy( box.max );
  2035. return this;
  2036. },
  2037. makeEmpty: function () {
  2038. this.min.x = this.min.y = Infinity;
  2039. this.max.x = this.max.y = -Infinity;
  2040. return this;
  2041. },
  2042. empty: function () {
  2043. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2044. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2045. },
  2046. center: function ( optionalTarget ) {
  2047. var result = optionalTarget || new THREE.Vector2();
  2048. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2049. },
  2050. size: function ( optionalTarget ) {
  2051. var result = optionalTarget || new THREE.Vector2();
  2052. return result.subVectors( this.max, this.min );
  2053. },
  2054. expandByPoint: function ( point ) {
  2055. this.min.min( point );
  2056. this.max.max( point );
  2057. return this;
  2058. },
  2059. expandByVector: function ( vector ) {
  2060. this.min.sub( vector );
  2061. this.max.add( vector );
  2062. return this;
  2063. },
  2064. expandByScalar: function ( scalar ) {
  2065. this.min.addScalar( -scalar );
  2066. this.max.addScalar( scalar );
  2067. return this;
  2068. },
  2069. containsPoint: function ( point ) {
  2070. if ( point.x < this.min.x || point.x > this.max.x ||
  2071. point.y < this.min.y || point.y > this.max.y ) {
  2072. return false;
  2073. }
  2074. return true;
  2075. },
  2076. containsBox: function ( box ) {
  2077. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2078. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2079. return true;
  2080. }
  2081. return false;
  2082. },
  2083. getParameter: function ( point, optionalTarget ) {
  2084. // This can potentially have a divide by zero if the box
  2085. // has a size dimension of 0.
  2086. var result = optionalTarget || new THREE.Vector2();
  2087. return result.set(
  2088. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2089. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2090. );
  2091. },
  2092. isIntersectionBox: function ( box ) {
  2093. // using 6 splitting planes to rule out intersections.
  2094. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2095. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2096. return false;
  2097. }
  2098. return true;
  2099. },
  2100. clampPoint: function ( point, optionalTarget ) {
  2101. var result = optionalTarget || new THREE.Vector2();
  2102. return result.copy( point ).clamp( this.min, this.max );
  2103. },
  2104. distanceToPoint: function () {
  2105. var v1 = new THREE.Vector2();
  2106. return function ( point ) {
  2107. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2108. return clampedPoint.sub( point ).length();
  2109. };
  2110. }(),
  2111. intersect: function ( box ) {
  2112. this.min.max( box.min );
  2113. this.max.min( box.max );
  2114. return this;
  2115. },
  2116. union: function ( box ) {
  2117. this.min.min( box.min );
  2118. this.max.max( box.max );
  2119. return this;
  2120. },
  2121. translate: function ( offset ) {
  2122. this.min.add( offset );
  2123. this.max.add( offset );
  2124. return this;
  2125. },
  2126. equals: function ( box ) {
  2127. return box.min.equals( this.min ) && box.max.equals( this.max );
  2128. },
  2129. clone: function () {
  2130. return new THREE.Box2().copy( this );
  2131. }
  2132. };
  2133. /**
  2134. * @author bhouston / http://exocortex.com
  2135. * @author WestLangley / http://github.com/WestLangley
  2136. */
  2137. THREE.Box3 = function ( min, max ) {
  2138. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2139. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2140. };
  2141. THREE.Box3.prototype = {
  2142. constructor: THREE.Box3,
  2143. set: function ( min, max ) {
  2144. this.min.copy( min );
  2145. this.max.copy( max );
  2146. return this;
  2147. },
  2148. addPoint: function ( point ) {
  2149. if ( point.x < this.min.x ) {
  2150. this.min.x = point.x;
  2151. } else if ( point.x > this.max.x ) {
  2152. this.max.x = point.x;
  2153. }
  2154. if ( point.y < this.min.y ) {
  2155. this.min.y = point.y;
  2156. } else if ( point.y > this.max.y ) {
  2157. this.max.y = point.y;
  2158. }
  2159. if ( point.z < this.min.z ) {
  2160. this.min.z = point.z;
  2161. } else if ( point.z > this.max.z ) {
  2162. this.max.z = point.z;
  2163. }
  2164. return this;
  2165. },
  2166. setFromPoints: function ( points ) {
  2167. if ( points.length > 0 ) {
  2168. var point = points[ 0 ];
  2169. this.min.copy( point );
  2170. this.max.copy( point );
  2171. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2172. this.addPoint( points[ i ] )
  2173. }
  2174. } else {
  2175. this.makeEmpty();
  2176. }
  2177. return this;
  2178. },
  2179. setFromCenterAndSize: function() {
  2180. var v1 = new THREE.Vector3();
  2181. return function ( center, size ) {
  2182. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2183. this.min.copy( center ).sub( halfSize );
  2184. this.max.copy( center ).add( halfSize );
  2185. return this;
  2186. };
  2187. }(),
  2188. setFromObject: function() {
  2189. // Computes the world-axis-aligned bounding box of an object (including its children),
  2190. // accounting for both the object's, and childrens', world transforms
  2191. var v1 = new THREE.Vector3();
  2192. return function( object ) {
  2193. var scope = this;
  2194. object.updateMatrixWorld( true );
  2195. this.makeEmpty();
  2196. object.traverse( function ( node ) {
  2197. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2198. var vertices = node.geometry.vertices;
  2199. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2200. v1.copy( vertices[ i ] );
  2201. v1.applyMatrix4( node.matrixWorld );
  2202. scope.expandByPoint( v1 );
  2203. }
  2204. }
  2205. } );
  2206. return this;
  2207. };
  2208. }(),
  2209. copy: function ( box ) {
  2210. this.min.copy( box.min );
  2211. this.max.copy( box.max );
  2212. return this;
  2213. },
  2214. makeEmpty: function () {
  2215. this.min.x = this.min.y = this.min.z = Infinity;
  2216. this.max.x = this.max.y = this.max.z = -Infinity;
  2217. return this;
  2218. },
  2219. empty: function () {
  2220. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2221. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2222. },
  2223. center: function ( optionalTarget ) {
  2224. var result = optionalTarget || new THREE.Vector3();
  2225. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2226. },
  2227. size: function ( optionalTarget ) {
  2228. var result = optionalTarget || new THREE.Vector3();
  2229. return result.subVectors( this.max, this.min );
  2230. },
  2231. expandByPoint: function ( point ) {
  2232. this.min.min( point );
  2233. this.max.max( point );
  2234. return this;
  2235. },
  2236. expandByVector: function ( vector ) {
  2237. this.min.sub( vector );
  2238. this.max.add( vector );
  2239. return this;
  2240. },
  2241. expandByScalar: function ( scalar ) {
  2242. this.min.addScalar( -scalar );
  2243. this.max.addScalar( scalar );
  2244. return this;
  2245. },
  2246. containsPoint: function ( point ) {
  2247. if ( point.x < this.min.x || point.x > this.max.x ||
  2248. point.y < this.min.y || point.y > this.max.y ||
  2249. point.z < this.min.z || point.z > this.max.z ) {
  2250. return false;
  2251. }
  2252. return true;
  2253. },
  2254. containsBox: function ( box ) {
  2255. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2256. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2257. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2258. return true;
  2259. }
  2260. return false;
  2261. },
  2262. getParameter: function ( point, optionalTarget ) {
  2263. // This can potentially have a divide by zero if the box
  2264. // has a size dimension of 0.
  2265. var result = optionalTarget || new THREE.Vector3();
  2266. return result.set(
  2267. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2268. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2269. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2270. );
  2271. },
  2272. isIntersectionBox: function ( box ) {
  2273. // using 6 splitting planes to rule out intersections.
  2274. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2275. box.max.y < this.min.y || box.min.y > this.max.y ||
  2276. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2277. return false;
  2278. }
  2279. return true;
  2280. },
  2281. clampPoint: function ( point, optionalTarget ) {
  2282. var result = optionalTarget || new THREE.Vector3();
  2283. return result.copy( point ).clamp( this.min, this.max );
  2284. },
  2285. distanceToPoint: function() {
  2286. var v1 = new THREE.Vector3();
  2287. return function ( point ) {
  2288. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2289. return clampedPoint.sub( point ).length();
  2290. };
  2291. }(),
  2292. getBoundingSphere: function() {
  2293. var v1 = new THREE.Vector3();
  2294. return function ( optionalTarget ) {
  2295. var result = optionalTarget || new THREE.Sphere();
  2296. result.center = this.center();
  2297. result.radius = this.size( v1 ).length() * 0.5;
  2298. return result;
  2299. };
  2300. }(),
  2301. intersect: function ( box ) {
  2302. this.min.max( box.min );
  2303. this.max.min( box.max );
  2304. return this;
  2305. },
  2306. union: function ( box ) {
  2307. this.min.min( box.min );
  2308. this.max.max( box.max );
  2309. return this;
  2310. },
  2311. applyMatrix4: function() {
  2312. var points = [
  2313. new THREE.Vector3(),
  2314. new THREE.Vector3(),
  2315. new THREE.Vector3(),
  2316. new THREE.Vector3(),
  2317. new THREE.Vector3(),
  2318. new THREE.Vector3(),
  2319. new THREE.Vector3(),
  2320. new THREE.Vector3()
  2321. ];
  2322. return function ( matrix ) {
  2323. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2324. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2325. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2326. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2327. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2328. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2329. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2330. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2331. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2332. this.makeEmpty();
  2333. this.setFromPoints( points );
  2334. return this;
  2335. };
  2336. }(),
  2337. translate: function ( offset ) {
  2338. this.min.add( offset );
  2339. this.max.add( offset );
  2340. return this;
  2341. },
  2342. equals: function ( box ) {
  2343. return box.min.equals( this.min ) && box.max.equals( this.max );
  2344. },
  2345. clone: function () {
  2346. return new THREE.Box3().copy( this );
  2347. }
  2348. };
  2349. /**
  2350. * @author alteredq / http://alteredqualia.com/
  2351. * @author WestLangley / http://github.com/WestLangley
  2352. * @author bhouston / http://exocortex.com
  2353. */
  2354. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2355. this.elements = new Float32Array( 9 );
  2356. var te = this.elements;
  2357. te[0] = ( n11 !== undefined ) ? n11 : 1; te[3] = n12 || 0; te[6] = n13 || 0;
  2358. te[1] = n21 || 0; te[4] = ( n22 !== undefined ) ? n22 : 1; te[7] = n23 || 0;
  2359. te[2] = n31 || 0; te[5] = n32 || 0; te[8] = ( n33 !== undefined ) ? n33 : 1;
  2360. };
  2361. THREE.Matrix3.prototype = {
  2362. constructor: THREE.Matrix3,
  2363. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2364. var te = this.elements;
  2365. te[0] = n11; te[3] = n12; te[6] = n13;
  2366. te[1] = n21; te[4] = n22; te[7] = n23;
  2367. te[2] = n31; te[5] = n32; te[8] = n33;
  2368. return this;
  2369. },
  2370. identity: function () {
  2371. this.set(
  2372. 1, 0, 0,
  2373. 0, 1, 0,
  2374. 0, 0, 1
  2375. );
  2376. return this;
  2377. },
  2378. copy: function ( m ) {
  2379. var me = m.elements;
  2380. this.set(
  2381. me[0], me[3], me[6],
  2382. me[1], me[4], me[7],
  2383. me[2], me[5], me[8]
  2384. );
  2385. return this;
  2386. },
  2387. multiplyVector3: function ( vector ) {
  2388. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2389. return vector.applyMatrix3( this );
  2390. },
  2391. multiplyVector3Array: function ( a ) {
  2392. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2393. return this.applyToVector3Array( a );
  2394. },
  2395. applyToVector3Array: function() {
  2396. var v1 = new THREE.Vector3();
  2397. return function ( array, offset, length ) {
  2398. if ( offset === undefined ) offset = 0;
  2399. if ( length === undefined ) length = array.length;
  2400. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2401. v1.x = array[ j ];
  2402. v1.y = array[ j + 1 ];
  2403. v1.z = array[ j + 2 ];
  2404. v1.applyMatrix3( this );
  2405. array[ j ] = v1.x;
  2406. array[ j + 1 ] = v1.y;
  2407. array[ j + 2 ] = v1.z;
  2408. }
  2409. return array;
  2410. };
  2411. }(),
  2412. multiplyScalar: function ( s ) {
  2413. var te = this.elements;
  2414. te[0] *= s; te[3] *= s; te[6] *= s;
  2415. te[1] *= s; te[4] *= s; te[7] *= s;
  2416. te[2] *= s; te[5] *= s; te[8] *= s;
  2417. return this;
  2418. },
  2419. determinant: function () {
  2420. var te = this.elements;
  2421. var a = te[0], b = te[1], c = te[2],
  2422. d = te[3], e = te[4], f = te[5],
  2423. g = te[6], h = te[7], i = te[8];
  2424. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2425. },
  2426. getInverse: function ( matrix, throwOnInvertible ) {
  2427. // input: THREE.Matrix4
  2428. // ( based on http://code.google.com/p/webgl-mjs/ )
  2429. var me = matrix.elements;
  2430. var te = this.elements;
  2431. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2432. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2433. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2434. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2435. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2436. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2437. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2438. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2439. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2440. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2441. // no inverse
  2442. if ( det === 0 ) {
  2443. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2444. if ( throwOnInvertible || false ) {
  2445. throw new Error( msg );
  2446. } else {
  2447. console.warn( msg );
  2448. }
  2449. this.identity();
  2450. return this;
  2451. }
  2452. this.multiplyScalar( 1.0 / det );
  2453. return this;
  2454. },
  2455. transpose: function () {
  2456. var tmp, m = this.elements;
  2457. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2458. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2459. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2460. return this;
  2461. },
  2462. flattenToArrayOffset: function( array, offset ) {
  2463. var te = this.elements;
  2464. array[ offset ] = te[0];
  2465. array[ offset + 1 ] = te[1];
  2466. array[ offset + 2 ] = te[2];
  2467. array[ offset + 3 ] = te[3];
  2468. array[ offset + 4 ] = te[4];
  2469. array[ offset + 5 ] = te[5];
  2470. array[ offset + 6 ] = te[6];
  2471. array[ offset + 7 ] = te[7];
  2472. array[ offset + 8 ] = te[8];
  2473. return array;
  2474. },
  2475. getNormalMatrix: function ( m ) {
  2476. // input: THREE.Matrix4
  2477. this.getInverse( m ).transpose();
  2478. return this;
  2479. },
  2480. transposeIntoArray: function ( r ) {
  2481. var m = this.elements;
  2482. r[ 0 ] = m[ 0 ];
  2483. r[ 1 ] = m[ 3 ];
  2484. r[ 2 ] = m[ 6 ];
  2485. r[ 3 ] = m[ 1 ];
  2486. r[ 4 ] = m[ 4 ];
  2487. r[ 5 ] = m[ 7 ];
  2488. r[ 6 ] = m[ 2 ];
  2489. r[ 7 ] = m[ 5 ];
  2490. r[ 8 ] = m[ 8 ];
  2491. return this;
  2492. },
  2493. fromArray: function ( array ) {
  2494. this.elements.set( array );
  2495. return this;
  2496. },
  2497. toArray: function () {
  2498. var te = this.elements;
  2499. return [
  2500. te[ 0 ], te[ 1 ], te[ 2 ],
  2501. te[ 3 ], te[ 4 ], te[ 5 ],
  2502. te[ 6 ], te[ 7 ], te[ 8 ]
  2503. ];
  2504. },
  2505. clone: function () {
  2506. var te = this.elements;
  2507. return new THREE.Matrix3(
  2508. te[0], te[3], te[6],
  2509. te[1], te[4], te[7],
  2510. te[2], te[5], te[8]
  2511. );
  2512. }
  2513. };
  2514. /**
  2515. * @author mrdoob / http://mrdoob.com/
  2516. * @author supereggbert / http://www.paulbrunt.co.uk/
  2517. * @author philogb / http://blog.thejit.org/
  2518. * @author jordi_ros / http://plattsoft.com
  2519. * @author D1plo1d / http://github.com/D1plo1d
  2520. * @author alteredq / http://alteredqualia.com/
  2521. * @author mikael emtinger / http://gomo.se/
  2522. * @author timknip / http://www.floorplanner.com/
  2523. * @author bhouston / http://exocortex.com
  2524. * @author WestLangley / http://github.com/WestLangley
  2525. */
  2526. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2527. this.elements = new Float32Array( 16 );
  2528. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2529. // we should not support semi specification of Matrix4, it is just weird.
  2530. var te = this.elements;
  2531. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2532. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2533. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2534. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2535. };
  2536. THREE.Matrix4.prototype = {
  2537. constructor: THREE.Matrix4,
  2538. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2539. var te = this.elements;
  2540. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2541. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2542. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2543. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2544. return this;
  2545. },
  2546. identity: function () {
  2547. this.set(
  2548. 1, 0, 0, 0,
  2549. 0, 1, 0, 0,
  2550. 0, 0, 1, 0,
  2551. 0, 0, 0, 1
  2552. );
  2553. return this;
  2554. },
  2555. copy: function ( m ) {
  2556. this.elements.set( m.elements );
  2557. return this;
  2558. },
  2559. extractPosition: function ( m ) {
  2560. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2561. return this.copyPosition( m );
  2562. },
  2563. copyPosition: function ( m ) {
  2564. var te = this.elements;
  2565. var me = m.elements;
  2566. te[12] = me[12];
  2567. te[13] = me[13];
  2568. te[14] = me[14];
  2569. return this;
  2570. },
  2571. extractRotation: function () {
  2572. var v1 = new THREE.Vector3();
  2573. return function ( m ) {
  2574. var te = this.elements;
  2575. var me = m.elements;
  2576. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2577. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2578. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2579. te[0] = me[0] * scaleX;
  2580. te[1] = me[1] * scaleX;
  2581. te[2] = me[2] * scaleX;
  2582. te[4] = me[4] * scaleY;
  2583. te[5] = me[5] * scaleY;
  2584. te[6] = me[6] * scaleY;
  2585. te[8] = me[8] * scaleZ;
  2586. te[9] = me[9] * scaleZ;
  2587. te[10] = me[10] * scaleZ;
  2588. return this;
  2589. };
  2590. }(),
  2591. makeRotationFromEuler: function ( euler ) {
  2592. if ( euler instanceof THREE.Euler === false ) {
  2593. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2594. }
  2595. var te = this.elements;
  2596. var x = euler.x, y = euler.y, z = euler.z;
  2597. var a = Math.cos( x ), b = Math.sin( x );
  2598. var c = Math.cos( y ), d = Math.sin( y );
  2599. var e = Math.cos( z ), f = Math.sin( z );
  2600. if ( euler.order === 'XYZ' ) {
  2601. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2602. te[0] = c * e;
  2603. te[4] = - c * f;
  2604. te[8] = d;
  2605. te[1] = af + be * d;
  2606. te[5] = ae - bf * d;
  2607. te[9] = - b * c;
  2608. te[2] = bf - ae * d;
  2609. te[6] = be + af * d;
  2610. te[10] = a * c;
  2611. } else if ( euler.order === 'YXZ' ) {
  2612. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2613. te[0] = ce + df * b;
  2614. te[4] = de * b - cf;
  2615. te[8] = a * d;
  2616. te[1] = a * f;
  2617. te[5] = a * e;
  2618. te[9] = - b;
  2619. te[2] = cf * b - de;
  2620. te[6] = df + ce * b;
  2621. te[10] = a * c;
  2622. } else if ( euler.order === 'ZXY' ) {
  2623. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2624. te[0] = ce - df * b;
  2625. te[4] = - a * f;
  2626. te[8] = de + cf * b;
  2627. te[1] = cf + de * b;
  2628. te[5] = a * e;
  2629. te[9] = df - ce * b;
  2630. te[2] = - a * d;
  2631. te[6] = b;
  2632. te[10] = a * c;
  2633. } else if ( euler.order === 'ZYX' ) {
  2634. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2635. te[0] = c * e;
  2636. te[4] = be * d - af;
  2637. te[8] = ae * d + bf;
  2638. te[1] = c * f;
  2639. te[5] = bf * d + ae;
  2640. te[9] = af * d - be;
  2641. te[2] = - d;
  2642. te[6] = b * c;
  2643. te[10] = a * c;
  2644. } else if ( euler.order === 'YZX' ) {
  2645. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2646. te[0] = c * e;
  2647. te[4] = bd - ac * f;
  2648. te[8] = bc * f + ad;
  2649. te[1] = f;
  2650. te[5] = a * e;
  2651. te[9] = - b * e;
  2652. te[2] = - d * e;
  2653. te[6] = ad * f + bc;
  2654. te[10] = ac - bd * f;
  2655. } else if ( euler.order === 'XZY' ) {
  2656. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2657. te[0] = c * e;
  2658. te[4] = - f;
  2659. te[8] = d * e;
  2660. te[1] = ac * f + bd;
  2661. te[5] = a * e;
  2662. te[9] = ad * f - bc;
  2663. te[2] = bc * f - ad;
  2664. te[6] = b * e;
  2665. te[10] = bd * f + ac;
  2666. }
  2667. // last column
  2668. te[3] = 0;
  2669. te[7] = 0;
  2670. te[11] = 0;
  2671. // bottom row
  2672. te[12] = 0;
  2673. te[13] = 0;
  2674. te[14] = 0;
  2675. te[15] = 1;
  2676. return this;
  2677. },
  2678. setRotationFromQuaternion: function ( q ) {
  2679. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2680. return this.makeRotationFromQuaternion( q );
  2681. },
  2682. makeRotationFromQuaternion: function ( q ) {
  2683. var te = this.elements;
  2684. var x = q.x, y = q.y, z = q.z, w = q.w;
  2685. var x2 = x + x, y2 = y + y, z2 = z + z;
  2686. var xx = x * x2, xy = x * y2, xz = x * z2;
  2687. var yy = y * y2, yz = y * z2, zz = z * z2;
  2688. var wx = w * x2, wy = w * y2, wz = w * z2;
  2689. te[0] = 1 - ( yy + zz );
  2690. te[4] = xy - wz;
  2691. te[8] = xz + wy;
  2692. te[1] = xy + wz;
  2693. te[5] = 1 - ( xx + zz );
  2694. te[9] = yz - wx;
  2695. te[2] = xz - wy;
  2696. te[6] = yz + wx;
  2697. te[10] = 1 - ( xx + yy );
  2698. // last column
  2699. te[3] = 0;
  2700. te[7] = 0;
  2701. te[11] = 0;
  2702. // bottom row
  2703. te[12] = 0;
  2704. te[13] = 0;
  2705. te[14] = 0;
  2706. te[15] = 1;
  2707. return this;
  2708. },
  2709. lookAt: function() {
  2710. var x = new THREE.Vector3();
  2711. var y = new THREE.Vector3();
  2712. var z = new THREE.Vector3();
  2713. return function ( eye, target, up ) {
  2714. var te = this.elements;
  2715. z.subVectors( eye, target ).normalize();
  2716. if ( z.length() === 0 ) {
  2717. z.z = 1;
  2718. }
  2719. x.crossVectors( up, z ).normalize();
  2720. if ( x.length() === 0 ) {
  2721. z.x += 0.0001;
  2722. x.crossVectors( up, z ).normalize();
  2723. }
  2724. y.crossVectors( z, x );
  2725. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2726. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2727. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2728. return this;
  2729. };
  2730. }(),
  2731. multiply: function ( m, n ) {
  2732. if ( n !== undefined ) {
  2733. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2734. return this.multiplyMatrices( m, n );
  2735. }
  2736. return this.multiplyMatrices( this, m );
  2737. },
  2738. multiplyMatrices: function ( a, b ) {
  2739. var ae = a.elements;
  2740. var be = b.elements;
  2741. var te = this.elements;
  2742. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2743. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2744. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2745. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2746. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2747. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2748. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2749. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2750. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2751. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2752. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2753. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2754. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2755. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2756. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2757. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2758. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2759. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2760. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2761. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2762. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2763. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2764. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2765. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2766. return this;
  2767. },
  2768. multiplyToArray: function ( a, b, r ) {
  2769. var te = this.elements;
  2770. this.multiplyMatrices( a, b );
  2771. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2772. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2773. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2774. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2775. return this;
  2776. },
  2777. multiplyScalar: function ( s ) {
  2778. var te = this.elements;
  2779. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2780. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2781. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2782. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2783. return this;
  2784. },
  2785. multiplyVector3: function ( vector ) {
  2786. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2787. return vector.applyProjection( this );
  2788. },
  2789. multiplyVector4: function ( vector ) {
  2790. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2791. return vector.applyMatrix4( this );
  2792. },
  2793. multiplyVector3Array: function ( a ) {
  2794. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2795. return this.applyToVector3Array( a );
  2796. },
  2797. applyToVector3Array: function() {
  2798. var v1 = new THREE.Vector3();
  2799. return function ( array, offset, length ) {
  2800. if ( offset === undefined ) offset = 0;
  2801. if ( length === undefined ) length = array.length;
  2802. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2803. v1.x = array[ j ];
  2804. v1.y = array[ j + 1 ];
  2805. v1.z = array[ j + 2 ];
  2806. v1.applyMatrix4( this );
  2807. array[ j ] = v1.x;
  2808. array[ j + 1 ] = v1.y;
  2809. array[ j + 2 ] = v1.z;
  2810. }
  2811. return array;
  2812. };
  2813. }(),
  2814. rotateAxis: function ( v ) {
  2815. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2816. v.transformDirection( this );
  2817. },
  2818. crossVector: function ( vector ) {
  2819. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2820. return vector.applyMatrix4( this );
  2821. },
  2822. determinant: function () {
  2823. var te = this.elements;
  2824. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2825. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2826. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2827. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2828. //TODO: make this more efficient
  2829. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2830. return (
  2831. n41 * (
  2832. +n14 * n23 * n32
  2833. -n13 * n24 * n32
  2834. -n14 * n22 * n33
  2835. +n12 * n24 * n33
  2836. +n13 * n22 * n34
  2837. -n12 * n23 * n34
  2838. ) +
  2839. n42 * (
  2840. +n11 * n23 * n34
  2841. -n11 * n24 * n33
  2842. +n14 * n21 * n33
  2843. -n13 * n21 * n34
  2844. +n13 * n24 * n31
  2845. -n14 * n23 * n31
  2846. ) +
  2847. n43 * (
  2848. +n11 * n24 * n32
  2849. -n11 * n22 * n34
  2850. -n14 * n21 * n32
  2851. +n12 * n21 * n34
  2852. +n14 * n22 * n31
  2853. -n12 * n24 * n31
  2854. ) +
  2855. n44 * (
  2856. -n13 * n22 * n31
  2857. -n11 * n23 * n32
  2858. +n11 * n22 * n33
  2859. +n13 * n21 * n32
  2860. -n12 * n21 * n33
  2861. +n12 * n23 * n31
  2862. )
  2863. );
  2864. },
  2865. transpose: function () {
  2866. var te = this.elements;
  2867. var tmp;
  2868. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2869. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2870. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2871. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2872. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2873. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2874. return this;
  2875. },
  2876. flattenToArrayOffset: function( array, offset ) {
  2877. var te = this.elements;
  2878. array[ offset ] = te[0];
  2879. array[ offset + 1 ] = te[1];
  2880. array[ offset + 2 ] = te[2];
  2881. array[ offset + 3 ] = te[3];
  2882. array[ offset + 4 ] = te[4];
  2883. array[ offset + 5 ] = te[5];
  2884. array[ offset + 6 ] = te[6];
  2885. array[ offset + 7 ] = te[7];
  2886. array[ offset + 8 ] = te[8];
  2887. array[ offset + 9 ] = te[9];
  2888. array[ offset + 10 ] = te[10];
  2889. array[ offset + 11 ] = te[11];
  2890. array[ offset + 12 ] = te[12];
  2891. array[ offset + 13 ] = te[13];
  2892. array[ offset + 14 ] = te[14];
  2893. array[ offset + 15 ] = te[15];
  2894. return array;
  2895. },
  2896. getPosition: function() {
  2897. var v1 = new THREE.Vector3();
  2898. return function () {
  2899. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2900. var te = this.elements;
  2901. return v1.set( te[12], te[13], te[14] );
  2902. };
  2903. }(),
  2904. setPosition: function ( v ) {
  2905. var te = this.elements;
  2906. te[12] = v.x;
  2907. te[13] = v.y;
  2908. te[14] = v.z;
  2909. return this;
  2910. },
  2911. getInverse: function ( m, throwOnInvertible ) {
  2912. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2913. var te = this.elements;
  2914. var me = m.elements;
  2915. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2916. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2917. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2918. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2919. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2920. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2921. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2922. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2923. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2924. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2925. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2926. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2927. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2928. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2929. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2930. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2931. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2932. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2933. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2934. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2935. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2936. if ( det == 0 ) {
  2937. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2938. if ( throwOnInvertible || false ) {
  2939. throw new Error( msg );
  2940. } else {
  2941. console.warn( msg );
  2942. }
  2943. this.identity();
  2944. return this;
  2945. }
  2946. this.multiplyScalar( 1 / det );
  2947. return this;
  2948. },
  2949. translate: function ( v ) {
  2950. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2951. },
  2952. rotateX: function ( angle ) {
  2953. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2954. },
  2955. rotateY: function ( angle ) {
  2956. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2957. },
  2958. rotateZ: function ( angle ) {
  2959. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2960. },
  2961. rotateByAxis: function ( axis, angle ) {
  2962. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2963. },
  2964. scale: function ( v ) {
  2965. var te = this.elements;
  2966. var x = v.x, y = v.y, z = v.z;
  2967. te[0] *= x; te[4] *= y; te[8] *= z;
  2968. te[1] *= x; te[5] *= y; te[9] *= z;
  2969. te[2] *= x; te[6] *= y; te[10] *= z;
  2970. te[3] *= x; te[7] *= y; te[11] *= z;
  2971. return this;
  2972. },
  2973. getMaxScaleOnAxis: function () {
  2974. var te = this.elements;
  2975. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2976. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2977. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2978. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2979. },
  2980. makeTranslation: function ( x, y, z ) {
  2981. this.set(
  2982. 1, 0, 0, x,
  2983. 0, 1, 0, y,
  2984. 0, 0, 1, z,
  2985. 0, 0, 0, 1
  2986. );
  2987. return this;
  2988. },
  2989. makeRotationX: function ( theta ) {
  2990. var c = Math.cos( theta ), s = Math.sin( theta );
  2991. this.set(
  2992. 1, 0, 0, 0,
  2993. 0, c, -s, 0,
  2994. 0, s, c, 0,
  2995. 0, 0, 0, 1
  2996. );
  2997. return this;
  2998. },
  2999. makeRotationY: function ( theta ) {
  3000. var c = Math.cos( theta ), s = Math.sin( theta );
  3001. this.set(
  3002. c, 0, s, 0,
  3003. 0, 1, 0, 0,
  3004. -s, 0, c, 0,
  3005. 0, 0, 0, 1
  3006. );
  3007. return this;
  3008. },
  3009. makeRotationZ: function ( theta ) {
  3010. var c = Math.cos( theta ), s = Math.sin( theta );
  3011. this.set(
  3012. c, -s, 0, 0,
  3013. s, c, 0, 0,
  3014. 0, 0, 1, 0,
  3015. 0, 0, 0, 1
  3016. );
  3017. return this;
  3018. },
  3019. makeRotationAxis: function ( axis, angle ) {
  3020. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3021. var c = Math.cos( angle );
  3022. var s = Math.sin( angle );
  3023. var t = 1 - c;
  3024. var x = axis.x, y = axis.y, z = axis.z;
  3025. var tx = t * x, ty = t * y;
  3026. this.set(
  3027. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3028. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3029. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3030. 0, 0, 0, 1
  3031. );
  3032. return this;
  3033. },
  3034. makeScale: function ( x, y, z ) {
  3035. this.set(
  3036. x, 0, 0, 0,
  3037. 0, y, 0, 0,
  3038. 0, 0, z, 0,
  3039. 0, 0, 0, 1
  3040. );
  3041. return this;
  3042. },
  3043. compose: function ( position, quaternion, scale ) {
  3044. this.makeRotationFromQuaternion( quaternion );
  3045. this.scale( scale );
  3046. this.setPosition( position );
  3047. return this;
  3048. },
  3049. decompose: function () {
  3050. var vector = new THREE.Vector3();
  3051. var matrix = new THREE.Matrix4();
  3052. return function ( position, quaternion, scale ) {
  3053. var te = this.elements;
  3054. var sx = vector.set( te[0], te[1], te[2] ).length();
  3055. var sy = vector.set( te[4], te[5], te[6] ).length();
  3056. var sz = vector.set( te[8], te[9], te[10] ).length();
  3057. // if determine is negative, we need to invert one scale
  3058. var det = this.determinant();
  3059. if( det < 0 ) {
  3060. sx = -sx;
  3061. }
  3062. position.x = te[12];
  3063. position.y = te[13];
  3064. position.z = te[14];
  3065. // scale the rotation part
  3066. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3067. var invSX = 1 / sx;
  3068. var invSY = 1 / sy;
  3069. var invSZ = 1 / sz;
  3070. matrix.elements[0] *= invSX;
  3071. matrix.elements[1] *= invSX;
  3072. matrix.elements[2] *= invSX;
  3073. matrix.elements[4] *= invSY;
  3074. matrix.elements[5] *= invSY;
  3075. matrix.elements[6] *= invSY;
  3076. matrix.elements[8] *= invSZ;
  3077. matrix.elements[9] *= invSZ;
  3078. matrix.elements[10] *= invSZ;
  3079. quaternion.setFromRotationMatrix( matrix );
  3080. scale.x = sx;
  3081. scale.y = sy;
  3082. scale.z = sz;
  3083. return this;
  3084. };
  3085. }(),
  3086. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3087. var te = this.elements;
  3088. var x = 2 * near / ( right - left );
  3089. var y = 2 * near / ( top - bottom );
  3090. var a = ( right + left ) / ( right - left );
  3091. var b = ( top + bottom ) / ( top - bottom );
  3092. var c = - ( far + near ) / ( far - near );
  3093. var d = - 2 * far * near / ( far - near );
  3094. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3095. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3096. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3097. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3098. return this;
  3099. },
  3100. makePerspective: function ( fov, aspect, near, far ) {
  3101. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3102. var ymin = - ymax;
  3103. var xmin = ymin * aspect;
  3104. var xmax = ymax * aspect;
  3105. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3106. },
  3107. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3108. var te = this.elements;
  3109. var w = right - left;
  3110. var h = top - bottom;
  3111. var p = far - near;
  3112. var x = ( right + left ) / w;
  3113. var y = ( top + bottom ) / h;
  3114. var z = ( far + near ) / p;
  3115. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3116. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3117. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3118. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3119. return this;
  3120. },
  3121. fromArray: function ( array ) {
  3122. this.elements.set( array );
  3123. return this;
  3124. },
  3125. toArray: function () {
  3126. var te = this.elements;
  3127. return [
  3128. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3129. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3130. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3131. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3132. ];
  3133. },
  3134. clone: function () {
  3135. var te = this.elements;
  3136. return new THREE.Matrix4(
  3137. te[0], te[4], te[8], te[12],
  3138. te[1], te[5], te[9], te[13],
  3139. te[2], te[6], te[10], te[14],
  3140. te[3], te[7], te[11], te[15]
  3141. );
  3142. }
  3143. };
  3144. /**
  3145. * @author bhouston / http://exocortex.com
  3146. */
  3147. THREE.Ray = function ( origin, direction ) {
  3148. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3149. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3150. };
  3151. THREE.Ray.prototype = {
  3152. constructor: THREE.Ray,
  3153. set: function ( origin, direction ) {
  3154. this.origin.copy( origin );
  3155. this.direction.copy( direction );
  3156. return this;
  3157. },
  3158. copy: function ( ray ) {
  3159. this.origin.copy( ray.origin );
  3160. this.direction.copy( ray.direction );
  3161. return this;
  3162. },
  3163. at: function ( t, optionalTarget ) {
  3164. var result = optionalTarget || new THREE.Vector3();
  3165. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3166. },
  3167. recast: function () {
  3168. var v1 = new THREE.Vector3();
  3169. return function ( t ) {
  3170. this.origin.copy( this.at( t, v1 ) );
  3171. return this;
  3172. };
  3173. }(),
  3174. closestPointToPoint: function ( point, optionalTarget ) {
  3175. var result = optionalTarget || new THREE.Vector3();
  3176. result.subVectors( point, this.origin );
  3177. var directionDistance = result.dot( this.direction );
  3178. if ( directionDistance < 0 ) {
  3179. return result.copy( this.origin );
  3180. }
  3181. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3182. },
  3183. distanceToPoint: function () {
  3184. var v1 = new THREE.Vector3();
  3185. return function ( point ) {
  3186. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3187. // point behind the ray
  3188. if ( directionDistance < 0 ) {
  3189. return this.origin.distanceTo( point );
  3190. }
  3191. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3192. return v1.distanceTo( point );
  3193. };
  3194. }(),
  3195. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3196. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3197. // It returns the min distance between the ray and the segment
  3198. // defined by v0 and v1
  3199. // It can also set two optional targets :
  3200. // - The closest point on the ray
  3201. // - The closest point on the segment
  3202. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3203. var segDir = v1.clone().sub( v0 ).normalize();
  3204. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3205. var diff = this.origin.clone().sub( segCenter );
  3206. var a01 = - this.direction.dot( segDir );
  3207. var b0 = diff.dot( this.direction );
  3208. var b1 = - diff.dot( segDir );
  3209. var c = diff.lengthSq();
  3210. var det = Math.abs( 1 - a01 * a01 );
  3211. var s0, s1, sqrDist, extDet;
  3212. if ( det >= 0 ) {
  3213. // The ray and segment are not parallel.
  3214. s0 = a01 * b1 - b0;
  3215. s1 = a01 * b0 - b1;
  3216. extDet = segExtent * det;
  3217. if ( s0 >= 0 ) {
  3218. if ( s1 >= - extDet ) {
  3219. if ( s1 <= extDet ) {
  3220. // region 0
  3221. // Minimum at interior points of ray and segment.
  3222. var invDet = 1 / det;
  3223. s0 *= invDet;
  3224. s1 *= invDet;
  3225. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3226. } else {
  3227. // region 1
  3228. s1 = segExtent;
  3229. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3230. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3231. }
  3232. } else {
  3233. // region 5
  3234. s1 = - segExtent;
  3235. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3236. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3237. }
  3238. } else {
  3239. if ( s1 <= - extDet) {
  3240. // region 4
  3241. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3242. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3243. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3244. } else if ( s1 <= extDet ) {
  3245. // region 3
  3246. s0 = 0;
  3247. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3248. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3249. } else {
  3250. // region 2
  3251. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3252. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3253. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3254. }
  3255. }
  3256. } else {
  3257. // Ray and segment are parallel.
  3258. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3259. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3260. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3261. }
  3262. if ( optionalPointOnRay ) {
  3263. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3264. }
  3265. if ( optionalPointOnSegment ) {
  3266. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3267. }
  3268. return sqrDist;
  3269. },
  3270. isIntersectionSphere: function ( sphere ) {
  3271. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3272. },
  3273. isIntersectionPlane: function ( plane ) {
  3274. // check if the ray lies on the plane first
  3275. var distToPoint = plane.distanceToPoint( this.origin );
  3276. if ( distToPoint === 0 ) {
  3277. return true;
  3278. }
  3279. var denominator = plane.normal.dot( this.direction );
  3280. if ( denominator * distToPoint < 0 ) {
  3281. return true
  3282. }
  3283. // ray origin is behind the plane (and is pointing behind it)
  3284. return false;
  3285. },
  3286. distanceToPlane: function ( plane ) {
  3287. var denominator = plane.normal.dot( this.direction );
  3288. if ( denominator == 0 ) {
  3289. // line is coplanar, return origin
  3290. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3291. return 0;
  3292. }
  3293. // Null is preferable to undefined since undefined means.... it is undefined
  3294. return null;
  3295. }
  3296. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3297. // Return if the ray never intersects the plane
  3298. return t >= 0 ? t : null;
  3299. },
  3300. intersectPlane: function ( plane, optionalTarget ) {
  3301. var t = this.distanceToPlane( plane );
  3302. if ( t === null ) {
  3303. return null;
  3304. }
  3305. return this.at( t, optionalTarget );
  3306. },
  3307. isIntersectionBox: function () {
  3308. var v = new THREE.Vector3();
  3309. return function ( box ) {
  3310. return this.intersectBox( box, v ) !== null;
  3311. }
  3312. }(),
  3313. intersectBox: function ( box , optionalTarget ) {
  3314. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3315. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3316. var invdirx = 1/this.direction.x,
  3317. invdiry = 1/this.direction.y,
  3318. invdirz = 1/this.direction.z;
  3319. var origin = this.origin;
  3320. if (invdirx >= 0) {
  3321. tmin = (box.min.x - origin.x) * invdirx;
  3322. tmax = (box.max.x - origin.x) * invdirx;
  3323. } else {
  3324. tmin = (box.max.x - origin.x) * invdirx;
  3325. tmax = (box.min.x - origin.x) * invdirx;
  3326. }
  3327. if (invdiry >= 0) {
  3328. tymin = (box.min.y - origin.y) * invdiry;
  3329. tymax = (box.max.y - origin.y) * invdiry;
  3330. } else {
  3331. tymin = (box.max.y - origin.y) * invdiry;
  3332. tymax = (box.min.y - origin.y) * invdiry;
  3333. }
  3334. if ((tmin > tymax) || (tymin > tmax)) return null;
  3335. // These lines also handle the case where tmin or tmax is NaN
  3336. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3337. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3338. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3339. if (invdirz >= 0) {
  3340. tzmin = (box.min.z - origin.z) * invdirz;
  3341. tzmax = (box.max.z - origin.z) * invdirz;
  3342. } else {
  3343. tzmin = (box.max.z - origin.z) * invdirz;
  3344. tzmax = (box.min.z - origin.z) * invdirz;
  3345. }
  3346. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3347. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3348. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3349. //return point closest to the ray (positive side)
  3350. if ( tmax < 0 ) return null;
  3351. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3352. },
  3353. intersectTriangle: function() {
  3354. // Compute the offset origin, edges, and normal.
  3355. var diff = new THREE.Vector3();
  3356. var edge1 = new THREE.Vector3();
  3357. var edge2 = new THREE.Vector3();
  3358. var normal = new THREE.Vector3();
  3359. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3360. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3361. edge1.subVectors( b, a );
  3362. edge2.subVectors( c, a );
  3363. normal.crossVectors( edge1, edge2 );
  3364. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3365. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3366. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3367. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3368. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3369. var DdN = this.direction.dot( normal );
  3370. var sign;
  3371. if ( DdN > 0 ) {
  3372. if ( backfaceCulling ) return null;
  3373. sign = 1;
  3374. } else if ( DdN < 0 ) {
  3375. sign = - 1;
  3376. DdN = - DdN;
  3377. } else {
  3378. return null;
  3379. }
  3380. diff.subVectors( this.origin, a );
  3381. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3382. // b1 < 0, no intersection
  3383. if ( DdQxE2 < 0 ) {
  3384. return null;
  3385. }
  3386. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3387. // b2 < 0, no intersection
  3388. if ( DdE1xQ < 0 ) {
  3389. return null;
  3390. }
  3391. // b1+b2 > 1, no intersection
  3392. if ( DdQxE2 + DdE1xQ > DdN ) {
  3393. return null;
  3394. }
  3395. // Line intersects triangle, check if ray does.
  3396. var QdN = - sign * diff.dot( normal );
  3397. // t < 0, no intersection
  3398. if ( QdN < 0 ) {
  3399. return null;
  3400. }
  3401. // Ray intersects triangle.
  3402. return this.at( QdN / DdN, optionalTarget );
  3403. }
  3404. }(),
  3405. applyMatrix4: function ( matrix4 ) {
  3406. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3407. this.origin.applyMatrix4( matrix4 );
  3408. this.direction.sub( this.origin );
  3409. this.direction.normalize();
  3410. return this;
  3411. },
  3412. equals: function ( ray ) {
  3413. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3414. },
  3415. clone: function () {
  3416. return new THREE.Ray().copy( this );
  3417. }
  3418. };
  3419. /**
  3420. * @author bhouston / http://exocortex.com
  3421. * @author mrdoob / http://mrdoob.com/
  3422. */
  3423. THREE.Sphere = function ( center, radius ) {
  3424. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3425. this.radius = ( radius !== undefined ) ? radius : 0;
  3426. };
  3427. THREE.Sphere.prototype = {
  3428. constructor: THREE.Sphere,
  3429. set: function ( center, radius ) {
  3430. this.center.copy( center );
  3431. this.radius = radius;
  3432. return this;
  3433. },
  3434. setFromPoints: function () {
  3435. var box = new THREE.Box3();
  3436. return function ( points, optionalCenter ) {
  3437. var center = this.center;
  3438. if ( optionalCenter !== undefined ) {
  3439. center.copy( optionalCenter );
  3440. } else {
  3441. box.setFromPoints( points ).center( center );
  3442. }
  3443. var maxRadiusSq = 0;
  3444. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3445. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3446. }
  3447. this.radius = Math.sqrt( maxRadiusSq );
  3448. return this;
  3449. };
  3450. }(),
  3451. copy: function ( sphere ) {
  3452. this.center.copy( sphere.center );
  3453. this.radius = sphere.radius;
  3454. return this;
  3455. },
  3456. empty: function () {
  3457. return ( this.radius <= 0 );
  3458. },
  3459. containsPoint: function ( point ) {
  3460. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3461. },
  3462. distanceToPoint: function ( point ) {
  3463. return ( point.distanceTo( this.center ) - this.radius );
  3464. },
  3465. intersectsSphere: function ( sphere ) {
  3466. var radiusSum = this.radius + sphere.radius;
  3467. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3468. },
  3469. clampPoint: function ( point, optionalTarget ) {
  3470. var deltaLengthSq = this.center.distanceToSquared( point );
  3471. var result = optionalTarget || new THREE.Vector3();
  3472. result.copy( point );
  3473. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3474. result.sub( this.center ).normalize();
  3475. result.multiplyScalar( this.radius ).add( this.center );
  3476. }
  3477. return result;
  3478. },
  3479. getBoundingBox: function ( optionalTarget ) {
  3480. var box = optionalTarget || new THREE.Box3();
  3481. box.set( this.center, this.center );
  3482. box.expandByScalar( this.radius );
  3483. return box;
  3484. },
  3485. applyMatrix4: function ( matrix ) {
  3486. this.center.applyMatrix4( matrix );
  3487. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3488. return this;
  3489. },
  3490. translate: function ( offset ) {
  3491. this.center.add( offset );
  3492. return this;
  3493. },
  3494. equals: function ( sphere ) {
  3495. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3496. },
  3497. clone: function () {
  3498. return new THREE.Sphere().copy( this );
  3499. }
  3500. };
  3501. /**
  3502. * @author mrdoob / http://mrdoob.com/
  3503. * @author alteredq / http://alteredqualia.com/
  3504. * @author bhouston / http://exocortex.com
  3505. */
  3506. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3507. this.planes = [
  3508. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3509. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3510. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3511. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3512. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3513. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3514. ];
  3515. };
  3516. THREE.Frustum.prototype = {
  3517. constructor: THREE.Frustum,
  3518. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3519. var planes = this.planes;
  3520. planes[0].copy( p0 );
  3521. planes[1].copy( p1 );
  3522. planes[2].copy( p2 );
  3523. planes[3].copy( p3 );
  3524. planes[4].copy( p4 );
  3525. planes[5].copy( p5 );
  3526. return this;
  3527. },
  3528. copy: function ( frustum ) {
  3529. var planes = this.planes;
  3530. for( var i = 0; i < 6; i ++ ) {
  3531. planes[i].copy( frustum.planes[i] );
  3532. }
  3533. return this;
  3534. },
  3535. setFromMatrix: function ( m ) {
  3536. var planes = this.planes;
  3537. var me = m.elements;
  3538. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3539. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3540. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3541. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3542. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3543. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3544. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3545. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3546. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3547. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3548. return this;
  3549. },
  3550. intersectsObject: function () {
  3551. var sphere = new THREE.Sphere();
  3552. return function ( object ) {
  3553. var geometry = object.geometry;
  3554. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3555. sphere.copy( geometry.boundingSphere );
  3556. sphere.applyMatrix4( object.matrixWorld );
  3557. return this.intersectsSphere( sphere );
  3558. };
  3559. }(),
  3560. intersectsSphere: function ( sphere ) {
  3561. var planes = this.planes;
  3562. var center = sphere.center;
  3563. var negRadius = -sphere.radius;
  3564. for ( var i = 0; i < 6; i ++ ) {
  3565. var distance = planes[ i ].distanceToPoint( center );
  3566. if ( distance < negRadius ) {
  3567. return false;
  3568. }
  3569. }
  3570. return true;
  3571. },
  3572. intersectsBox : function() {
  3573. var p1 = new THREE.Vector3(),
  3574. p2 = new THREE.Vector3();
  3575. return function( box ) {
  3576. var planes = this.planes;
  3577. for ( var i = 0; i < 6 ; i ++ ) {
  3578. var plane = planes[i];
  3579. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3580. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3581. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3582. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3583. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3584. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3585. var d1 = plane.distanceToPoint( p1 );
  3586. var d2 = plane.distanceToPoint( p2 );
  3587. // if both outside plane, no intersection
  3588. if ( d1 < 0 && d2 < 0 ) {
  3589. return false;
  3590. }
  3591. }
  3592. return true;
  3593. };
  3594. }(),
  3595. containsPoint: function ( point ) {
  3596. var planes = this.planes;
  3597. for ( var i = 0; i < 6; i ++ ) {
  3598. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3599. return false;
  3600. }
  3601. }
  3602. return true;
  3603. },
  3604. clone: function () {
  3605. return new THREE.Frustum().copy( this );
  3606. }
  3607. };
  3608. /**
  3609. * @author bhouston / http://exocortex.com
  3610. */
  3611. THREE.Plane = function ( normal, constant ) {
  3612. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3613. this.constant = ( constant !== undefined ) ? constant : 0;
  3614. };
  3615. THREE.Plane.prototype = {
  3616. constructor: THREE.Plane,
  3617. set: function ( normal, constant ) {
  3618. this.normal.copy( normal );
  3619. this.constant = constant;
  3620. return this;
  3621. },
  3622. setComponents: function ( x, y, z, w ) {
  3623. this.normal.set( x, y, z );
  3624. this.constant = w;
  3625. return this;
  3626. },
  3627. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3628. this.normal.copy( normal );
  3629. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3630. return this;
  3631. },
  3632. setFromCoplanarPoints: function() {
  3633. var v1 = new THREE.Vector3();
  3634. var v2 = new THREE.Vector3();
  3635. return function ( a, b, c ) {
  3636. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3637. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3638. this.setFromNormalAndCoplanarPoint( normal, a );
  3639. return this;
  3640. };
  3641. }(),
  3642. copy: function ( plane ) {
  3643. this.normal.copy( plane.normal );
  3644. this.constant = plane.constant;
  3645. return this;
  3646. },
  3647. normalize: function () {
  3648. // Note: will lead to a divide by zero if the plane is invalid.
  3649. var inverseNormalLength = 1.0 / this.normal.length();
  3650. this.normal.multiplyScalar( inverseNormalLength );
  3651. this.constant *= inverseNormalLength;
  3652. return this;
  3653. },
  3654. negate: function () {
  3655. this.constant *= -1;
  3656. this.normal.negate();
  3657. return this;
  3658. },
  3659. distanceToPoint: function ( point ) {
  3660. return this.normal.dot( point ) + this.constant;
  3661. },
  3662. distanceToSphere: function ( sphere ) {
  3663. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3664. },
  3665. projectPoint: function ( point, optionalTarget ) {
  3666. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3667. },
  3668. orthoPoint: function ( point, optionalTarget ) {
  3669. var perpendicularMagnitude = this.distanceToPoint( point );
  3670. var result = optionalTarget || new THREE.Vector3();
  3671. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3672. },
  3673. isIntersectionLine: function ( line ) {
  3674. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3675. var startSign = this.distanceToPoint( line.start );
  3676. var endSign = this.distanceToPoint( line.end );
  3677. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3678. },
  3679. intersectLine: function() {
  3680. var v1 = new THREE.Vector3();
  3681. return function ( line, optionalTarget ) {
  3682. var result = optionalTarget || new THREE.Vector3();
  3683. var direction = line.delta( v1 );
  3684. var denominator = this.normal.dot( direction );
  3685. if ( denominator == 0 ) {
  3686. // line is coplanar, return origin
  3687. if( this.distanceToPoint( line.start ) == 0 ) {
  3688. return result.copy( line.start );
  3689. }
  3690. // Unsure if this is the correct method to handle this case.
  3691. return undefined;
  3692. }
  3693. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3694. if( t < 0 || t > 1 ) {
  3695. return undefined;
  3696. }
  3697. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3698. };
  3699. }(),
  3700. coplanarPoint: function ( optionalTarget ) {
  3701. var result = optionalTarget || new THREE.Vector3();
  3702. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3703. },
  3704. applyMatrix4: function() {
  3705. var v1 = new THREE.Vector3();
  3706. var v2 = new THREE.Vector3();
  3707. var m1 = new THREE.Matrix3();
  3708. return function ( matrix, optionalNormalMatrix ) {
  3709. // compute new normal based on theory here:
  3710. // http://www.songho.ca/opengl/gl_normaltransform.html
  3711. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3712. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3713. var newCoplanarPoint = this.coplanarPoint( v2 );
  3714. newCoplanarPoint.applyMatrix4( matrix );
  3715. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3716. return this;
  3717. };
  3718. }(),
  3719. translate: function ( offset ) {
  3720. this.constant = this.constant - offset.dot( this.normal );
  3721. return this;
  3722. },
  3723. equals: function ( plane ) {
  3724. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3725. },
  3726. clone: function () {
  3727. return new THREE.Plane().copy( this );
  3728. }
  3729. };
  3730. /**
  3731. * @author alteredq / http://alteredqualia.com/
  3732. * @author mrdoob / http://mrdoob.com/
  3733. */
  3734. THREE.Math = {
  3735. generateUUID: function () {
  3736. // http://www.broofa.com/Tools/Math.uuid.htm
  3737. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3738. var uuid = new Array(36);
  3739. var rnd = 0, r;
  3740. return function () {
  3741. for ( var i = 0; i < 36; i ++ ) {
  3742. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3743. uuid[ i ] = '-';
  3744. } else if ( i == 14 ) {
  3745. uuid[ i ] = '4';
  3746. } else {
  3747. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3748. r = rnd & 0xf;
  3749. rnd = rnd >> 4;
  3750. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3751. }
  3752. }
  3753. return uuid.join('');
  3754. };
  3755. }(),
  3756. // Clamp value to range <a, b>
  3757. clamp: function ( x, a, b ) {
  3758. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3759. },
  3760. // Clamp value to range <a, inf)
  3761. clampBottom: function ( x, a ) {
  3762. return x < a ? a : x;
  3763. },
  3764. // Linear mapping from range <a1, a2> to range <b1, b2>
  3765. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3766. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3767. },
  3768. // http://en.wikipedia.org/wiki/Smoothstep
  3769. smoothstep: function ( x, min, max ) {
  3770. if ( x <= min ) return 0;
  3771. if ( x >= max ) return 1;
  3772. x = ( x - min )/( max - min );
  3773. return x*x*(3 - 2*x);
  3774. },
  3775. smootherstep: function ( x, min, max ) {
  3776. if ( x <= min ) return 0;
  3777. if ( x >= max ) return 1;
  3778. x = ( x - min )/( max - min );
  3779. return x*x*x*(x*(x*6 - 15) + 10);
  3780. },
  3781. // Random float from <0, 1> with 16 bits of randomness
  3782. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3783. random16: function () {
  3784. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3785. },
  3786. // Random integer from <low, high> interval
  3787. randInt: function ( low, high ) {
  3788. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3789. },
  3790. // Random float from <low, high> interval
  3791. randFloat: function ( low, high ) {
  3792. return low + Math.random() * ( high - low );
  3793. },
  3794. // Random float from <-range/2, range/2> interval
  3795. randFloatSpread: function ( range ) {
  3796. return range * ( 0.5 - Math.random() );
  3797. },
  3798. sign: function ( x ) {
  3799. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3800. },
  3801. degToRad: function() {
  3802. var degreeToRadiansFactor = Math.PI / 180;
  3803. return function ( degrees ) {
  3804. return degrees * degreeToRadiansFactor;
  3805. };
  3806. }(),
  3807. radToDeg: function() {
  3808. var radianToDegreesFactor = 180 / Math.PI;
  3809. return function ( radians ) {
  3810. return radians * radianToDegreesFactor;
  3811. };
  3812. }(),
  3813. isPowerOfTwo: function ( value ) {
  3814. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3815. }
  3816. };
  3817. /**
  3818. * Spline from Tween.js, slightly optimized (and trashed)
  3819. * http://sole.github.com/tween.js/examples/05_spline.html
  3820. *
  3821. * @author mrdoob / http://mrdoob.com/
  3822. * @author alteredq / http://alteredqualia.com/
  3823. */
  3824. THREE.Spline = function ( points ) {
  3825. this.points = points;
  3826. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3827. point, intPoint, weight, w2, w3,
  3828. pa, pb, pc, pd;
  3829. this.initFromArray = function( a ) {
  3830. this.points = [];
  3831. for ( var i = 0; i < a.length; i++ ) {
  3832. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3833. }
  3834. };
  3835. this.getPoint = function ( k ) {
  3836. point = ( this.points.length - 1 ) * k;
  3837. intPoint = Math.floor( point );
  3838. weight = point - intPoint;
  3839. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3840. c[ 1 ] = intPoint;
  3841. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3842. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3843. pa = this.points[ c[ 0 ] ];
  3844. pb = this.points[ c[ 1 ] ];
  3845. pc = this.points[ c[ 2 ] ];
  3846. pd = this.points[ c[ 3 ] ];
  3847. w2 = weight * weight;
  3848. w3 = weight * w2;
  3849. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3850. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3851. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3852. return v3;
  3853. };
  3854. this.getControlPointsArray = function () {
  3855. var i, p, l = this.points.length,
  3856. coords = [];
  3857. for ( i = 0; i < l; i ++ ) {
  3858. p = this.points[ i ];
  3859. coords[ i ] = [ p.x, p.y, p.z ];
  3860. }
  3861. return coords;
  3862. };
  3863. // approximate length by summing linear segments
  3864. this.getLength = function ( nSubDivisions ) {
  3865. var i, index, nSamples, position,
  3866. point = 0, intPoint = 0, oldIntPoint = 0,
  3867. oldPosition = new THREE.Vector3(),
  3868. tmpVec = new THREE.Vector3(),
  3869. chunkLengths = [],
  3870. totalLength = 0;
  3871. // first point has 0 length
  3872. chunkLengths[ 0 ] = 0;
  3873. if ( !nSubDivisions ) nSubDivisions = 100;
  3874. nSamples = this.points.length * nSubDivisions;
  3875. oldPosition.copy( this.points[ 0 ] );
  3876. for ( i = 1; i < nSamples; i ++ ) {
  3877. index = i / nSamples;
  3878. position = this.getPoint( index );
  3879. tmpVec.copy( position );
  3880. totalLength += tmpVec.distanceTo( oldPosition );
  3881. oldPosition.copy( position );
  3882. point = ( this.points.length - 1 ) * index;
  3883. intPoint = Math.floor( point );
  3884. if ( intPoint != oldIntPoint ) {
  3885. chunkLengths[ intPoint ] = totalLength;
  3886. oldIntPoint = intPoint;
  3887. }
  3888. }
  3889. // last point ends with total length
  3890. chunkLengths[ chunkLengths.length ] = totalLength;
  3891. return { chunks: chunkLengths, total: totalLength };
  3892. };
  3893. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3894. var i, j,
  3895. index, indexCurrent, indexNext,
  3896. linearDistance, realDistance,
  3897. sampling, position,
  3898. newpoints = [],
  3899. tmpVec = new THREE.Vector3(),
  3900. sl = this.getLength();
  3901. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3902. for ( i = 1; i < this.points.length; i++ ) {
  3903. //tmpVec.copy( this.points[ i - 1 ] );
  3904. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3905. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3906. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3907. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3908. indexNext = i / ( this.points.length - 1 );
  3909. for ( j = 1; j < sampling - 1; j++ ) {
  3910. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3911. position = this.getPoint( index );
  3912. newpoints.push( tmpVec.copy( position ).clone() );
  3913. }
  3914. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3915. }
  3916. this.points = newpoints;
  3917. };
  3918. // Catmull-Rom
  3919. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3920. var v0 = ( p2 - p0 ) * 0.5,
  3921. v1 = ( p3 - p1 ) * 0.5;
  3922. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3923. };
  3924. };
  3925. /**
  3926. * @author bhouston / http://exocortex.com
  3927. * @author mrdoob / http://mrdoob.com/
  3928. */
  3929. THREE.Triangle = function ( a, b, c ) {
  3930. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3931. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3932. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3933. };
  3934. THREE.Triangle.normal = function() {
  3935. var v0 = new THREE.Vector3();
  3936. return function ( a, b, c, optionalTarget ) {
  3937. var result = optionalTarget || new THREE.Vector3();
  3938. result.subVectors( c, b );
  3939. v0.subVectors( a, b );
  3940. result.cross( v0 );
  3941. var resultLengthSq = result.lengthSq();
  3942. if( resultLengthSq > 0 ) {
  3943. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3944. }
  3945. return result.set( 0, 0, 0 );
  3946. };
  3947. }();
  3948. // static/instance method to calculate barycoordinates
  3949. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3950. THREE.Triangle.barycoordFromPoint = function() {
  3951. var v0 = new THREE.Vector3();
  3952. var v1 = new THREE.Vector3();
  3953. var v2 = new THREE.Vector3();
  3954. return function ( point, a, b, c, optionalTarget ) {
  3955. v0.subVectors( c, a );
  3956. v1.subVectors( b, a );
  3957. v2.subVectors( point, a );
  3958. var dot00 = v0.dot( v0 );
  3959. var dot01 = v0.dot( v1 );
  3960. var dot02 = v0.dot( v2 );
  3961. var dot11 = v1.dot( v1 );
  3962. var dot12 = v1.dot( v2 );
  3963. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3964. var result = optionalTarget || new THREE.Vector3();
  3965. // colinear or singular triangle
  3966. if( denom == 0 ) {
  3967. // arbitrary location outside of triangle?
  3968. // not sure if this is the best idea, maybe should be returning undefined
  3969. return result.set( -2, -1, -1 );
  3970. }
  3971. var invDenom = 1 / denom;
  3972. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3973. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3974. // barycoordinates must always sum to 1
  3975. return result.set( 1 - u - v, v, u );
  3976. };
  3977. }();
  3978. THREE.Triangle.containsPoint = function() {
  3979. var v1 = new THREE.Vector3();
  3980. return function ( point, a, b, c ) {
  3981. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3982. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3983. };
  3984. }();
  3985. THREE.Triangle.prototype = {
  3986. constructor: THREE.Triangle,
  3987. set: function ( a, b, c ) {
  3988. this.a.copy( a );
  3989. this.b.copy( b );
  3990. this.c.copy( c );
  3991. return this;
  3992. },
  3993. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3994. this.a.copy( points[i0] );
  3995. this.b.copy( points[i1] );
  3996. this.c.copy( points[i2] );
  3997. return this;
  3998. },
  3999. copy: function ( triangle ) {
  4000. this.a.copy( triangle.a );
  4001. this.b.copy( triangle.b );
  4002. this.c.copy( triangle.c );
  4003. return this;
  4004. },
  4005. area: function() {
  4006. var v0 = new THREE.Vector3();
  4007. var v1 = new THREE.Vector3();
  4008. return function () {
  4009. v0.subVectors( this.c, this.b );
  4010. v1.subVectors( this.a, this.b );
  4011. return v0.cross( v1 ).length() * 0.5;
  4012. };
  4013. }(),
  4014. midpoint: function ( optionalTarget ) {
  4015. var result = optionalTarget || new THREE.Vector3();
  4016. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4017. },
  4018. normal: function ( optionalTarget ) {
  4019. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4020. },
  4021. plane: function ( optionalTarget ) {
  4022. var result = optionalTarget || new THREE.Plane();
  4023. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4024. },
  4025. barycoordFromPoint: function ( point, optionalTarget ) {
  4026. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4027. },
  4028. containsPoint: function ( point ) {
  4029. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4030. },
  4031. equals: function ( triangle ) {
  4032. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4033. },
  4034. clone: function () {
  4035. return new THREE.Triangle().copy( this );
  4036. }
  4037. };
  4038. /**
  4039. * @author alteredq / http://alteredqualia.com/
  4040. */
  4041. THREE.Clock = function ( autoStart ) {
  4042. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4043. this.startTime = 0;
  4044. this.oldTime = 0;
  4045. this.elapsedTime = 0;
  4046. this.running = false;
  4047. };
  4048. THREE.Clock.prototype = {
  4049. constructor: THREE.Clock,
  4050. start: function () {
  4051. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4052. ? self.performance.now()
  4053. : Date.now();
  4054. this.oldTime = this.startTime;
  4055. this.running = true;
  4056. },
  4057. stop: function () {
  4058. this.getElapsedTime();
  4059. this.running = false;
  4060. },
  4061. getElapsedTime: function () {
  4062. this.getDelta();
  4063. return this.elapsedTime;
  4064. },
  4065. getDelta: function () {
  4066. var diff = 0;
  4067. if ( this.autoStart && ! this.running ) {
  4068. this.start();
  4069. }
  4070. if ( this.running ) {
  4071. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4072. ? self.performance.now()
  4073. : Date.now();
  4074. diff = 0.001 * ( newTime - this.oldTime );
  4075. this.oldTime = newTime;
  4076. this.elapsedTime += diff;
  4077. }
  4078. return diff;
  4079. }
  4080. };
  4081. /**
  4082. * https://github.com/mrdoob/eventdispatcher.js/
  4083. */
  4084. THREE.EventDispatcher = function () {}
  4085. THREE.EventDispatcher.prototype = {
  4086. constructor: THREE.EventDispatcher,
  4087. apply: function ( object ) {
  4088. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4089. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4090. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4091. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4092. },
  4093. addEventListener: function ( type, listener ) {
  4094. if ( this._listeners === undefined ) this._listeners = {};
  4095. var listeners = this._listeners;
  4096. if ( listeners[ type ] === undefined ) {
  4097. listeners[ type ] = [];
  4098. }
  4099. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4100. listeners[ type ].push( listener );
  4101. }
  4102. },
  4103. hasEventListener: function ( type, listener ) {
  4104. if ( this._listeners === undefined ) return false;
  4105. var listeners = this._listeners;
  4106. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4107. return true;
  4108. }
  4109. return false;
  4110. },
  4111. removeEventListener: function ( type, listener ) {
  4112. if ( this._listeners === undefined ) return;
  4113. var listeners = this._listeners;
  4114. var listenerArray = listeners[ type ];
  4115. if ( listenerArray !== undefined ) {
  4116. var index = listenerArray.indexOf( listener );
  4117. if ( index !== - 1 ) {
  4118. listenerArray.splice( index, 1 );
  4119. }
  4120. }
  4121. },
  4122. dispatchEvent: function ( event ) {
  4123. if ( this._listeners === undefined ) return;
  4124. var listeners = this._listeners;
  4125. var listenerArray = listeners[ event.type ];
  4126. if ( listenerArray !== undefined ) {
  4127. event.target = this;
  4128. var array = [];
  4129. var length = listenerArray.length;
  4130. for ( var i = 0; i < length; i ++ ) {
  4131. array[ i ] = listenerArray[ i ];
  4132. }
  4133. for ( var i = 0; i < length; i ++ ) {
  4134. array[ i ].call( this, event );
  4135. }
  4136. }
  4137. }
  4138. };
  4139. /**
  4140. * @author mrdoob / http://mrdoob.com/
  4141. * @author bhouston / http://exocortex.com/
  4142. * @author stephomi / http://stephaneginier.com/
  4143. */
  4144. ( function ( THREE ) {
  4145. THREE.Raycaster = function ( origin, direction, near, far ) {
  4146. this.ray = new THREE.Ray( origin, direction );
  4147. // direction is assumed to be normalized (for accurate distance calculations)
  4148. this.near = near || 0;
  4149. this.far = far || Infinity;
  4150. };
  4151. var sphere = new THREE.Sphere();
  4152. var localRay = new THREE.Ray();
  4153. var facePlane = new THREE.Plane();
  4154. var intersectPoint = new THREE.Vector3();
  4155. var matrixPosition = new THREE.Vector3();
  4156. var inverseMatrix = new THREE.Matrix4();
  4157. var descSort = function ( a, b ) {
  4158. return a.distance - b.distance;
  4159. };
  4160. var vA = new THREE.Vector3();
  4161. var vB = new THREE.Vector3();
  4162. var vC = new THREE.Vector3();
  4163. var intersectObject = function ( object, raycaster, intersects ) {
  4164. if ( object instanceof THREE.Sprite ) {
  4165. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4166. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4167. if ( distance > object.scale.x ) {
  4168. return intersects;
  4169. }
  4170. intersects.push( {
  4171. distance: distance,
  4172. point: object.position,
  4173. face: null,
  4174. object: object
  4175. } );
  4176. } else if ( object instanceof THREE.LOD ) {
  4177. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4178. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4179. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4180. } else if ( object instanceof THREE.Mesh ) {
  4181. var geometry = object.geometry;
  4182. // Checking boundingSphere distance to ray
  4183. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4184. sphere.copy( geometry.boundingSphere );
  4185. sphere.applyMatrix4( object.matrixWorld );
  4186. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4187. return intersects;
  4188. }
  4189. // Check boundingBox before continuing
  4190. inverseMatrix.getInverse( object.matrixWorld );
  4191. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4192. if ( geometry.boundingBox !== null ) {
  4193. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4194. return intersects;
  4195. }
  4196. }
  4197. if ( geometry instanceof THREE.BufferGeometry ) {
  4198. var material = object.material;
  4199. if ( material === undefined ) return intersects;
  4200. var attributes = geometry.attributes;
  4201. var a, b, c;
  4202. var precision = raycaster.precision;
  4203. if ( attributes.index !== undefined ) {
  4204. var indices = attributes.index.array;
  4205. var positions = attributes.position.array;
  4206. var offsets = geometry.offsets;
  4207. if ( offsets.length === 0 ) {
  4208. offsets = [ { start: 0, count: positions.length, index: 0 } ];
  4209. }
  4210. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4211. var start = offsets[ oi ].start;
  4212. var count = offsets[ oi ].count;
  4213. var index = offsets[ oi ].index;
  4214. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4215. a = index + indices[ i ];
  4216. b = index + indices[ i + 1 ];
  4217. c = index + indices[ i + 2 ];
  4218. vA.set(
  4219. positions[ a * 3 ],
  4220. positions[ a * 3 + 1 ],
  4221. positions[ a * 3 + 2 ]
  4222. );
  4223. vB.set(
  4224. positions[ b * 3 ],
  4225. positions[ b * 3 + 1 ],
  4226. positions[ b * 3 + 2 ]
  4227. );
  4228. vC.set(
  4229. positions[ c * 3 ],
  4230. positions[ c * 3 + 1 ],
  4231. positions[ c * 3 + 2 ]
  4232. );
  4233. if ( material.side === THREE.BackSide ) {
  4234. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4235. } else {
  4236. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4237. }
  4238. if ( intersectionPoint === null ) continue;
  4239. intersectionPoint.applyMatrix4( object.matrixWorld );
  4240. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4241. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4242. intersects.push( {
  4243. distance: distance,
  4244. point: intersectionPoint,
  4245. indices: [a, b, c],
  4246. face: null,
  4247. faceIndex: null,
  4248. object: object
  4249. } );
  4250. }
  4251. }
  4252. } else {
  4253. var offsets = geometry.offsets;
  4254. var positions = attributes.position.array;
  4255. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4256. a = i;
  4257. b = i + 1;
  4258. c = i + 2;
  4259. vA.set(
  4260. positions[ a * 3 ],
  4261. positions[ a * 3 + 1 ],
  4262. positions[ a * 3 + 2 ]
  4263. );
  4264. vB.set(
  4265. positions[ b * 3 ],
  4266. positions[ b * 3 + 1 ],
  4267. positions[ b * 3 + 2 ]
  4268. );
  4269. vC.set(
  4270. positions[ c * 3 ],
  4271. positions[ c * 3 + 1 ],
  4272. positions[ c * 3 + 2 ]
  4273. );
  4274. if ( material.side === THREE.BackSide ) {
  4275. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4276. } else {
  4277. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4278. }
  4279. if ( intersectionPoint === null ) continue;
  4280. intersectionPoint.applyMatrix4( object.matrixWorld );
  4281. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4282. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4283. intersects.push( {
  4284. distance: distance,
  4285. point: intersectionPoint,
  4286. indices: [a, b, c],
  4287. face: null,
  4288. faceIndex: null,
  4289. object: object
  4290. } );
  4291. }
  4292. }
  4293. } else if ( geometry instanceof THREE.Geometry ) {
  4294. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4295. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4296. var a, b, c, d;
  4297. var precision = raycaster.precision;
  4298. var vertices = geometry.vertices;
  4299. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4300. var face = geometry.faces[ f ];
  4301. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4302. if ( material === undefined ) continue;
  4303. a = vertices[ face.a ];
  4304. b = vertices[ face.b ];
  4305. c = vertices[ face.c ];
  4306. if ( material.morphTargets === true ) {
  4307. var morphTargets = geometry.morphTargets;
  4308. var morphInfluences = object.morphTargetInfluences;
  4309. vA.set( 0, 0, 0 );
  4310. vB.set( 0, 0, 0 );
  4311. vC.set( 0, 0, 0 );
  4312. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4313. var influence = morphInfluences[ t ];
  4314. if ( influence === 0 ) continue;
  4315. var targets = morphTargets[ t ].vertices;
  4316. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4317. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4318. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4319. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4320. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4321. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4322. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4323. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4324. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4325. }
  4326. vA.add( a );
  4327. vB.add( b );
  4328. vC.add( c );
  4329. a = vA;
  4330. b = vB;
  4331. c = vC;
  4332. }
  4333. if ( material.side === THREE.BackSide ) {
  4334. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4335. } else {
  4336. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4337. }
  4338. if ( intersectionPoint === null ) continue;
  4339. intersectionPoint.applyMatrix4( object.matrixWorld );
  4340. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4341. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4342. intersects.push( {
  4343. distance: distance,
  4344. point: intersectionPoint,
  4345. face: face,
  4346. faceIndex: f,
  4347. object: object
  4348. } );
  4349. }
  4350. }
  4351. } else if ( object instanceof THREE.Line ) {
  4352. var precision = raycaster.linePrecision;
  4353. var precisionSq = precision * precision;
  4354. var geometry = object.geometry;
  4355. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4356. // Checking boundingSphere distance to ray
  4357. sphere.copy( geometry.boundingSphere );
  4358. sphere.applyMatrix4( object.matrixWorld );
  4359. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4360. return intersects;
  4361. }
  4362. inverseMatrix.getInverse( object.matrixWorld );
  4363. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4364. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4365. } else */ if ( geometry instanceof THREE.Geometry ) {
  4366. var vertices = geometry.vertices;
  4367. var nbVertices = vertices.length;
  4368. var interSegment = new THREE.Vector3();
  4369. var interRay = new THREE.Vector3();
  4370. var step = object.type === THREE.LineStrip ? 1 : 2;
  4371. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4372. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4373. if ( distSq > precisionSq ) continue;
  4374. var distance = localRay.origin.distanceTo( interRay );
  4375. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4376. intersects.push( {
  4377. distance: distance,
  4378. // What do we want? intersection point on the ray or on the segment??
  4379. // point: raycaster.ray.at( distance ),
  4380. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4381. face: null,
  4382. faceIndex: null,
  4383. object: object
  4384. } );
  4385. }
  4386. }
  4387. }
  4388. };
  4389. var intersectDescendants = function ( object, raycaster, intersects ) {
  4390. var descendants = object.getDescendants();
  4391. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4392. intersectObject( descendants[ i ], raycaster, intersects );
  4393. }
  4394. };
  4395. //
  4396. THREE.Raycaster.prototype.precision = 0.0001;
  4397. THREE.Raycaster.prototype.linePrecision = 1;
  4398. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4399. this.ray.set( origin, direction );
  4400. // direction is assumed to be normalized (for accurate distance calculations)
  4401. };
  4402. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4403. var intersects = [];
  4404. if ( recursive === true ) {
  4405. intersectDescendants( object, this, intersects );
  4406. }
  4407. intersectObject( object, this, intersects );
  4408. intersects.sort( descSort );
  4409. return intersects;
  4410. };
  4411. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4412. var intersects = [];
  4413. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4414. intersectObject( objects[ i ], this, intersects );
  4415. if ( recursive === true ) {
  4416. intersectDescendants( objects[ i ], this, intersects );
  4417. }
  4418. }
  4419. intersects.sort( descSort );
  4420. return intersects;
  4421. };
  4422. }( THREE ) );
  4423. /**
  4424. * @author mrdoob / http://mrdoob.com/
  4425. * @author mikael emtinger / http://gomo.se/
  4426. * @author alteredq / http://alteredqualia.com/
  4427. * @author WestLangley / http://github.com/WestLangley
  4428. */
  4429. THREE.Object3D = function () {
  4430. this.id = THREE.Object3DIdCount ++;
  4431. this.uuid = THREE.Math.generateUUID();
  4432. this.name = '';
  4433. this.parent = undefined;
  4434. this.children = [];
  4435. this.up = new THREE.Vector3( 0, 1, 0 );
  4436. this.position = new THREE.Vector3();
  4437. var scope = this;
  4438. Object.defineProperties( this, {
  4439. rotation: {
  4440. enumerable: true,
  4441. value: new THREE.Euler().onChange( function () {
  4442. scope.quaternion.setFromEuler( scope.rotation, false );
  4443. } )
  4444. },
  4445. quaternion: {
  4446. enumerable: true,
  4447. value: new THREE.Quaternion().onChange( function () {
  4448. scope.rotation.setFromQuaternion( scope.quaternion, undefined, false );
  4449. } )
  4450. },
  4451. scale: {
  4452. enumerable: true,
  4453. value: new THREE.Vector3( 1, 1, 1 )
  4454. }
  4455. } );
  4456. this.renderDepth = null;
  4457. this.rotationAutoUpdate = true;
  4458. this.matrix = new THREE.Matrix4();
  4459. this.matrixWorld = new THREE.Matrix4();
  4460. this.matrixAutoUpdate = true;
  4461. this.matrixWorldNeedsUpdate = false;
  4462. this.visible = true;
  4463. this.castShadow = false;
  4464. this.receiveShadow = false;
  4465. this.frustumCulled = true;
  4466. this.userData = {};
  4467. };
  4468. THREE.Object3D.prototype = {
  4469. constructor: THREE.Object3D,
  4470. get eulerOrder () {
  4471. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4472. return this.rotation.order;
  4473. },
  4474. set eulerOrder ( value ) {
  4475. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4476. this.rotation.order = value;
  4477. },
  4478. get useQuaternion () {
  4479. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4480. },
  4481. set useQuaternion ( value ) {
  4482. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4483. },
  4484. applyMatrix: function ( matrix ) {
  4485. this.matrix.multiplyMatrices( matrix, this.matrix );
  4486. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4487. },
  4488. setRotationFromAxisAngle: function ( axis, angle ) {
  4489. // assumes axis is normalized
  4490. this.quaternion.setFromAxisAngle( axis, angle );
  4491. },
  4492. setRotationFromEuler: function ( euler ) {
  4493. this.quaternion.setFromEuler( euler, true );
  4494. },
  4495. setRotationFromMatrix: function ( m ) {
  4496. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4497. this.quaternion.setFromRotationMatrix( m );
  4498. },
  4499. setRotationFromQuaternion: function ( q ) {
  4500. // assumes q is normalized
  4501. this.quaternion.copy( q );
  4502. },
  4503. rotateOnAxis: function() {
  4504. // rotate object on axis in object space
  4505. // axis is assumed to be normalized
  4506. var q1 = new THREE.Quaternion();
  4507. return function ( axis, angle ) {
  4508. q1.setFromAxisAngle( axis, angle );
  4509. this.quaternion.multiply( q1 );
  4510. return this;
  4511. }
  4512. }(),
  4513. rotateX: function () {
  4514. var v1 = new THREE.Vector3( 1, 0, 0 );
  4515. return function ( angle ) {
  4516. return this.rotateOnAxis( v1, angle );
  4517. };
  4518. }(),
  4519. rotateY: function () {
  4520. var v1 = new THREE.Vector3( 0, 1, 0 );
  4521. return function ( angle ) {
  4522. return this.rotateOnAxis( v1, angle );
  4523. };
  4524. }(),
  4525. rotateZ: function () {
  4526. var v1 = new THREE.Vector3( 0, 0, 1 );
  4527. return function ( angle ) {
  4528. return this.rotateOnAxis( v1, angle );
  4529. };
  4530. }(),
  4531. translateOnAxis: function () {
  4532. // translate object by distance along axis in object space
  4533. // axis is assumed to be normalized
  4534. var v1 = new THREE.Vector3();
  4535. return function ( axis, distance ) {
  4536. v1.copy( axis );
  4537. v1.applyQuaternion( this.quaternion );
  4538. this.position.add( v1.multiplyScalar( distance ) );
  4539. return this;
  4540. }
  4541. }(),
  4542. translate: function ( distance, axis ) {
  4543. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4544. return this.translateOnAxis( axis, distance );
  4545. },
  4546. translateX: function () {
  4547. var v1 = new THREE.Vector3( 1, 0, 0 );
  4548. return function ( distance ) {
  4549. return this.translateOnAxis( v1, distance );
  4550. };
  4551. }(),
  4552. translateY: function () {
  4553. var v1 = new THREE.Vector3( 0, 1, 0 );
  4554. return function ( distance ) {
  4555. return this.translateOnAxis( v1, distance );
  4556. };
  4557. }(),
  4558. translateZ: function () {
  4559. var v1 = new THREE.Vector3( 0, 0, 1 );
  4560. return function ( distance ) {
  4561. return this.translateOnAxis( v1, distance );
  4562. };
  4563. }(),
  4564. localToWorld: function ( vector ) {
  4565. return vector.applyMatrix4( this.matrixWorld );
  4566. },
  4567. worldToLocal: function () {
  4568. var m1 = new THREE.Matrix4();
  4569. return function ( vector ) {
  4570. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4571. };
  4572. }(),
  4573. lookAt: function () {
  4574. // This routine does not support objects with rotated and/or translated parent(s)
  4575. var m1 = new THREE.Matrix4();
  4576. return function ( vector ) {
  4577. m1.lookAt( vector, this.position, this.up );
  4578. this.quaternion.setFromRotationMatrix( m1 );
  4579. };
  4580. }(),
  4581. add: function ( object ) {
  4582. if ( object === this ) {
  4583. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4584. return;
  4585. }
  4586. if ( object instanceof THREE.Object3D ) {
  4587. if ( object.parent !== undefined ) {
  4588. object.parent.remove( object );
  4589. }
  4590. object.parent = this;
  4591. object.dispatchEvent( { type: 'added' } );
  4592. this.children.push( object );
  4593. // add to scene
  4594. var scene = this;
  4595. while ( scene.parent !== undefined ) {
  4596. scene = scene.parent;
  4597. }
  4598. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4599. scene.__addObject( object );
  4600. }
  4601. }
  4602. },
  4603. remove: function ( object ) {
  4604. var index = this.children.indexOf( object );
  4605. if ( index !== - 1 ) {
  4606. object.parent = undefined;
  4607. object.dispatchEvent( { type: 'removed' } );
  4608. this.children.splice( index, 1 );
  4609. // remove from scene
  4610. var scene = this;
  4611. while ( scene.parent !== undefined ) {
  4612. scene = scene.parent;
  4613. }
  4614. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4615. scene.__removeObject( object );
  4616. }
  4617. }
  4618. },
  4619. traverse: function ( callback ) {
  4620. callback( this );
  4621. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4622. this.children[ i ].traverse( callback );
  4623. }
  4624. },
  4625. getObjectById: function ( id, recursive ) {
  4626. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4627. var child = this.children[ i ];
  4628. if ( child.id === id ) {
  4629. return child;
  4630. }
  4631. if ( recursive === true ) {
  4632. child = child.getObjectById( id, recursive );
  4633. if ( child !== undefined ) {
  4634. return child;
  4635. }
  4636. }
  4637. }
  4638. return undefined;
  4639. },
  4640. getObjectByName: function ( name, recursive ) {
  4641. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4642. var child = this.children[ i ];
  4643. if ( child.name === name ) {
  4644. return child;
  4645. }
  4646. if ( recursive === true ) {
  4647. child = child.getObjectByName( name, recursive );
  4648. if ( child !== undefined ) {
  4649. return child;
  4650. }
  4651. }
  4652. }
  4653. return undefined;
  4654. },
  4655. getChildByName: function ( name, recursive ) {
  4656. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4657. return this.getObjectByName( name, recursive );
  4658. },
  4659. getDescendants: function ( array ) {
  4660. if ( array === undefined ) array = [];
  4661. Array.prototype.push.apply( array, this.children );
  4662. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4663. this.children[ i ].getDescendants( array );
  4664. }
  4665. return array;
  4666. },
  4667. updateMatrix: function () {
  4668. this.matrix.compose( this.position, this.quaternion, this.scale );
  4669. this.matrixWorldNeedsUpdate = true;
  4670. },
  4671. updateMatrixWorld: function ( force ) {
  4672. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4673. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4674. if ( this.parent === undefined ) {
  4675. this.matrixWorld.copy( this.matrix );
  4676. } else {
  4677. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4678. }
  4679. this.matrixWorldNeedsUpdate = false;
  4680. force = true;
  4681. }
  4682. // update children
  4683. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4684. this.children[ i ].updateMatrixWorld( force );
  4685. }
  4686. },
  4687. clone: function ( object, recursive ) {
  4688. if ( object === undefined ) object = new THREE.Object3D();
  4689. if ( recursive === undefined ) recursive = true;
  4690. object.name = this.name;
  4691. object.up.copy( this.up );
  4692. object.position.copy( this.position );
  4693. object.quaternion.copy( this.quaternion );
  4694. object.scale.copy( this.scale );
  4695. object.renderDepth = this.renderDepth;
  4696. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4697. object.matrix.copy( this.matrix );
  4698. object.matrixWorld.copy( this.matrixWorld );
  4699. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4700. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4701. object.visible = this.visible;
  4702. object.castShadow = this.castShadow;
  4703. object.receiveShadow = this.receiveShadow;
  4704. object.frustumCulled = this.frustumCulled;
  4705. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4706. if ( recursive === true ) {
  4707. for ( var i = 0; i < this.children.length; i ++ ) {
  4708. var child = this.children[ i ];
  4709. object.add( child.clone() );
  4710. }
  4711. }
  4712. return object;
  4713. }
  4714. };
  4715. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4716. THREE.Object3DIdCount = 0;
  4717. /**
  4718. * @author mrdoob / http://mrdoob.com/
  4719. * @author supereggbert / http://www.paulbrunt.co.uk/
  4720. * @author julianwa / https://github.com/julianwa
  4721. */
  4722. THREE.Projector = function () {
  4723. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4724. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4725. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4726. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4727. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4728. _renderData = { objects: [], lights: [], elements: [] },
  4729. _vA = new THREE.Vector3(),
  4730. _vB = new THREE.Vector3(),
  4731. _vC = new THREE.Vector3(),
  4732. _vector3 = new THREE.Vector3(),
  4733. _vector4 = new THREE.Vector4(),
  4734. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4735. _boundingBox = new THREE.Box3(),
  4736. _points3 = new Array( 3 ),
  4737. _points4 = new Array( 4 ),
  4738. _viewMatrix = new THREE.Matrix4(),
  4739. _viewProjectionMatrix = new THREE.Matrix4(),
  4740. _modelMatrix,
  4741. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4742. _normalMatrix = new THREE.Matrix3(),
  4743. _frustum = new THREE.Frustum(),
  4744. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4745. _clippedVertex2PositionScreen = new THREE.Vector4();
  4746. this.projectVector = function ( vector, camera ) {
  4747. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4748. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4749. return vector.applyProjection( _viewProjectionMatrix );
  4750. };
  4751. this.unprojectVector = function () {
  4752. var projectionMatrixInverse = new THREE.Matrix4();
  4753. return function ( vector, camera ) {
  4754. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4755. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4756. return vector.applyProjection( _viewProjectionMatrix );
  4757. };
  4758. }();
  4759. this.pickingRay = function ( vector, camera ) {
  4760. // set two vectors with opposing z values
  4761. vector.z = -1.0;
  4762. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4763. this.unprojectVector( vector, camera );
  4764. this.unprojectVector( end, camera );
  4765. // find direction from vector to end
  4766. end.sub( vector ).normalize();
  4767. return new THREE.Raycaster( vector, end );
  4768. };
  4769. var projectObject = function ( object ) {
  4770. if ( object.visible === false ) return;
  4771. if ( object instanceof THREE.Light ) {
  4772. _renderData.lights.push( object );
  4773. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4774. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4775. _object = getNextObjectInPool();
  4776. _object.id = object.id;
  4777. _object.object = object;
  4778. if ( object.renderDepth !== null ) {
  4779. _object.z = object.renderDepth;
  4780. } else {
  4781. _vector3.setFromMatrixPosition( object.matrixWorld );
  4782. _vector3.applyProjection( _viewProjectionMatrix );
  4783. _object.z = _vector3.z;
  4784. }
  4785. _renderData.objects.push( _object );
  4786. }
  4787. }
  4788. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4789. projectObject( object.children[ i ] );
  4790. }
  4791. };
  4792. var projectGraph = function ( root, sortObjects ) {
  4793. _objectCount = 0;
  4794. _renderData.objects.length = 0;
  4795. _renderData.lights.length = 0;
  4796. projectObject( root );
  4797. if ( sortObjects === true ) {
  4798. _renderData.objects.sort( painterSort );
  4799. }
  4800. };
  4801. var RenderList = function () {
  4802. var normals = [];
  4803. var uvs = [];
  4804. var object = null;
  4805. var material = null;
  4806. var normalMatrix = new THREE.Matrix3();
  4807. var setObject = function ( value ) {
  4808. object = value;
  4809. material = object.material;
  4810. normalMatrix.getNormalMatrix( object.matrixWorld );
  4811. normals.length = 0;
  4812. uvs.length = 0;
  4813. };
  4814. var projectVertex = function ( vertex ) {
  4815. var position = vertex.position;
  4816. var positionWorld = vertex.positionWorld;
  4817. var positionScreen = vertex.positionScreen;
  4818. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4819. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4820. var invW = 1 / positionScreen.w;
  4821. positionScreen.x *= invW;
  4822. positionScreen.y *= invW;
  4823. positionScreen.z *= invW;
  4824. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4825. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4826. positionScreen.z >= -1 && positionScreen.z <= 1;
  4827. };
  4828. var pushVertex = function ( x, y, z ) {
  4829. _vertex = getNextVertexInPool();
  4830. _vertex.position.set( x, y, z );
  4831. projectVertex( _vertex );
  4832. };
  4833. var pushNormal = function ( x, y, z ) {
  4834. normals.push( x, y, z );
  4835. };
  4836. var pushUv = function ( x, y ) {
  4837. uvs.push( x, y );
  4838. };
  4839. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4840. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4841. _points3[ 0 ] = v1.positionScreen;
  4842. _points3[ 1 ] = v2.positionScreen;
  4843. _points3[ 2 ] = v3.positionScreen;
  4844. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4845. };
  4846. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4847. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4848. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4849. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4850. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4851. };
  4852. var pushLine = function ( a, b ) {
  4853. var v1 = _vertexPool[ a ];
  4854. var v2 = _vertexPool[ b ];
  4855. _line = getNextLineInPool();
  4856. _line.id = object.id;
  4857. _line.v1.copy( v1 );
  4858. _line.v2.copy( v2 );
  4859. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4860. _line.material = object.material;
  4861. _renderData.elements.push( _line );
  4862. };
  4863. var pushTriangle = function ( a, b, c ) {
  4864. var v1 = _vertexPool[ a ];
  4865. var v2 = _vertexPool[ b ];
  4866. var v3 = _vertexPool[ c ];
  4867. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4868. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4869. _face = getNextFaceInPool();
  4870. _face.id = object.id;
  4871. _face.v1.copy( v1 );
  4872. _face.v2.copy( v2 );
  4873. _face.v3.copy( v3 );
  4874. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4875. for ( var i = 0; i < 3; i ++ ) {
  4876. var offset = arguments[ i ] * 3;
  4877. var normal = _face.vertexNormalsModel[ i ];
  4878. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4879. normal.applyMatrix3( normalMatrix ).normalize();
  4880. var offset2 = arguments[ i ] * 2;
  4881. var uv = _face.uvs[ i ];
  4882. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4883. }
  4884. _face.vertexNormalsLength = 3;
  4885. _face.material = object.material;
  4886. _renderData.elements.push( _face );
  4887. }
  4888. };
  4889. return {
  4890. setObject: setObject,
  4891. projectVertex: projectVertex,
  4892. checkTriangleVisibility: checkTriangleVisibility,
  4893. checkBackfaceCulling: checkBackfaceCulling,
  4894. pushVertex: pushVertex,
  4895. pushNormal: pushNormal,
  4896. pushUv: pushUv,
  4897. pushLine: pushLine,
  4898. pushTriangle: pushTriangle
  4899. }
  4900. };
  4901. var renderList = new RenderList();
  4902. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4903. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4904. isFaceMaterial, objectMaterials;
  4905. _faceCount = 0;
  4906. _lineCount = 0;
  4907. _spriteCount = 0;
  4908. _renderData.elements.length = 0;
  4909. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4910. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4911. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4912. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4913. _frustum.setFromMatrix( _viewProjectionMatrix );
  4914. projectGraph( scene, sortObjects );
  4915. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4916. object = _renderData.objects[ o ].object;
  4917. geometry = object.geometry;
  4918. renderList.setObject( object );
  4919. _modelMatrix = object.matrixWorld;
  4920. _vertexCount = 0;
  4921. if ( object instanceof THREE.Mesh ) {
  4922. if ( geometry instanceof THREE.BufferGeometry ) {
  4923. var attributes = geometry.attributes;
  4924. var offsets = geometry.offsets;
  4925. if ( attributes.position === undefined ) continue;
  4926. var positions = attributes.position.array;
  4927. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4928. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4929. }
  4930. if ( attributes.normal !== undefined ) {
  4931. var normals = attributes.normal.array;
  4932. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4933. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4934. }
  4935. }
  4936. if ( attributes.uv !== undefined ) {
  4937. var uvs = attributes.uv.array;
  4938. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4939. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4940. }
  4941. }
  4942. if ( attributes.index !== undefined ) {
  4943. var indices = attributes.index.array;
  4944. if ( offsets.length > 0 ) {
  4945. for ( var o = 0; o < offsets.length; o ++ ) {
  4946. var offset = offsets[ o ];
  4947. var index = offset.index;
  4948. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4949. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4950. }
  4951. }
  4952. } else {
  4953. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4954. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4955. }
  4956. }
  4957. } else {
  4958. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4959. renderList.pushTriangle( i, i + 1, i + 2 );
  4960. }
  4961. }
  4962. } else if ( geometry instanceof THREE.Geometry ) {
  4963. vertices = geometry.vertices;
  4964. faces = geometry.faces;
  4965. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4966. _normalMatrix.getNormalMatrix( _modelMatrix );
  4967. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4968. objectMaterials = isFaceMaterial === true ? object.material : null;
  4969. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4970. var vertex = vertices[ v ];
  4971. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4972. }
  4973. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4974. face = faces[ f ];
  4975. var material = isFaceMaterial === true
  4976. ? objectMaterials.materials[ face.materialIndex ]
  4977. : object.material;
  4978. if ( material === undefined ) continue;
  4979. var side = material.side;
  4980. var v1 = _vertexPool[ face.a ];
  4981. var v2 = _vertexPool[ face.b ];
  4982. var v3 = _vertexPool[ face.c ];
  4983. if ( material.morphTargets === true ) {
  4984. var morphTargets = geometry.morphTargets;
  4985. var morphInfluences = object.morphTargetInfluences;
  4986. var v1p = v1.position;
  4987. var v2p = v2.position;
  4988. var v3p = v3.position;
  4989. _vA.set( 0, 0, 0 );
  4990. _vB.set( 0, 0, 0 );
  4991. _vC.set( 0, 0, 0 );
  4992. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4993. var influence = morphInfluences[ t ];
  4994. if ( influence === 0 ) continue;
  4995. var targets = morphTargets[ t ].vertices;
  4996. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4997. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4998. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4999. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  5000. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  5001. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  5002. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  5003. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  5004. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  5005. }
  5006. v1.position.add( _vA );
  5007. v2.position.add( _vB );
  5008. v3.position.add( _vC );
  5009. renderList.projectVertex( v1 );
  5010. renderList.projectVertex( v2 );
  5011. renderList.projectVertex( v3 );
  5012. }
  5013. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  5014. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  5015. if ( side !== THREE.DoubleSide ) {
  5016. if ( side === THREE.FrontSide && visible === false ) continue;
  5017. if ( side === THREE.BackSide && visible === true ) continue;
  5018. }
  5019. _face = getNextFaceInPool();
  5020. _face.id = object.id;
  5021. _face.v1.copy( v1 );
  5022. _face.v2.copy( v2 );
  5023. _face.v3.copy( v3 );
  5024. _face.normalModel.copy( face.normal );
  5025. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5026. _face.normalModel.negate();
  5027. }
  5028. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  5029. faceVertexNormals = face.vertexNormals;
  5030. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  5031. var normalModel = _face.vertexNormalsModel[ n ];
  5032. normalModel.copy( faceVertexNormals[ n ] );
  5033. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5034. normalModel.negate();
  5035. }
  5036. normalModel.applyMatrix3( _normalMatrix ).normalize();
  5037. }
  5038. _face.vertexNormalsLength = faceVertexNormals.length;
  5039. var vertexUvs = faceVertexUvs[ f ];
  5040. if ( vertexUvs !== undefined ) {
  5041. for ( var u = 0; u < 3; u ++ ) {
  5042. _face.uvs[ u ].copy( vertexUvs[ u ] );
  5043. }
  5044. }
  5045. _face.color = face.color;
  5046. _face.material = material;
  5047. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5048. _renderData.elements.push( _face );
  5049. }
  5050. }
  5051. } else if ( object instanceof THREE.Line ) {
  5052. if ( geometry instanceof THREE.BufferGeometry ) {
  5053. var attributes = geometry.attributes;
  5054. if ( attributes.position !== undefined ) {
  5055. var positions = attributes.position.array;
  5056. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5057. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5058. }
  5059. if ( attributes.index !== undefined ) {
  5060. var indices = attributes.index.array;
  5061. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5062. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5063. }
  5064. } else {
  5065. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5066. renderList.pushLine( i, i + 1 );
  5067. }
  5068. }
  5069. }
  5070. } else if ( geometry instanceof THREE.Geometry ) {
  5071. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5072. vertices = object.geometry.vertices;
  5073. if ( vertices.length === 0 ) continue;
  5074. v1 = getNextVertexInPool();
  5075. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5076. // Handle LineStrip and LinePieces
  5077. var step = object.type === THREE.LinePieces ? 2 : 1;
  5078. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5079. v1 = getNextVertexInPool();
  5080. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5081. if ( ( v + 1 ) % step > 0 ) continue;
  5082. v2 = _vertexPool[ _vertexCount - 2 ];
  5083. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5084. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5085. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5086. // Perform the perspective divide
  5087. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5088. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5089. _line = getNextLineInPool();
  5090. _line.id = object.id;
  5091. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5092. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5093. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5094. _line.material = object.material;
  5095. if ( object.material.vertexColors === THREE.VertexColors ) {
  5096. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5097. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5098. }
  5099. _renderData.elements.push( _line );
  5100. }
  5101. }
  5102. }
  5103. } else if ( object instanceof THREE.Sprite ) {
  5104. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5105. _vector4.applyMatrix4( _viewProjectionMatrix );
  5106. var invW = 1 / _vector4.w;
  5107. _vector4.z *= invW;
  5108. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5109. _sprite = getNextSpriteInPool();
  5110. _sprite.id = object.id;
  5111. _sprite.x = _vector4.x * invW;
  5112. _sprite.y = _vector4.y * invW;
  5113. _sprite.z = _vector4.z;
  5114. _sprite.object = object;
  5115. _sprite.rotation = object.rotation;
  5116. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5117. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5118. _sprite.material = object.material;
  5119. _renderData.elements.push( _sprite );
  5120. }
  5121. }
  5122. }
  5123. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5124. return _renderData;
  5125. };
  5126. // Pools
  5127. function getNextObjectInPool() {
  5128. if ( _objectCount === _objectPoolLength ) {
  5129. var object = new THREE.RenderableObject();
  5130. _objectPool.push( object );
  5131. _objectPoolLength ++;
  5132. _objectCount ++;
  5133. return object;
  5134. }
  5135. return _objectPool[ _objectCount ++ ];
  5136. }
  5137. function getNextVertexInPool() {
  5138. if ( _vertexCount === _vertexPoolLength ) {
  5139. var vertex = new THREE.RenderableVertex();
  5140. _vertexPool.push( vertex );
  5141. _vertexPoolLength ++;
  5142. _vertexCount ++;
  5143. return vertex;
  5144. }
  5145. return _vertexPool[ _vertexCount ++ ];
  5146. }
  5147. function getNextFaceInPool() {
  5148. if ( _faceCount === _facePoolLength ) {
  5149. var face = new THREE.RenderableFace();
  5150. _facePool.push( face );
  5151. _facePoolLength ++;
  5152. _faceCount ++;
  5153. return face;
  5154. }
  5155. return _facePool[ _faceCount ++ ];
  5156. }
  5157. function getNextLineInPool() {
  5158. if ( _lineCount === _linePoolLength ) {
  5159. var line = new THREE.RenderableLine();
  5160. _linePool.push( line );
  5161. _linePoolLength ++;
  5162. _lineCount ++
  5163. return line;
  5164. }
  5165. return _linePool[ _lineCount ++ ];
  5166. }
  5167. function getNextSpriteInPool() {
  5168. if ( _spriteCount === _spritePoolLength ) {
  5169. var sprite = new THREE.RenderableSprite();
  5170. _spritePool.push( sprite );
  5171. _spritePoolLength ++;
  5172. _spriteCount ++
  5173. return sprite;
  5174. }
  5175. return _spritePool[ _spriteCount ++ ];
  5176. }
  5177. //
  5178. function painterSort( a, b ) {
  5179. if ( a.z !== b.z ) {
  5180. return b.z - a.z;
  5181. } else if ( a.id !== b.id ) {
  5182. return a.id - b.id;
  5183. } else {
  5184. return 0;
  5185. }
  5186. }
  5187. function clipLine( s1, s2 ) {
  5188. var alpha1 = 0, alpha2 = 1,
  5189. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5190. // Z = -1 and Z = +1, respectively.
  5191. bc1near = s1.z + s1.w,
  5192. bc2near = s2.z + s2.w,
  5193. bc1far = - s1.z + s1.w,
  5194. bc2far = - s2.z + s2.w;
  5195. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5196. // Both vertices lie entirely within all clip planes.
  5197. return true;
  5198. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5199. // Both vertices lie entirely outside one of the clip planes.
  5200. return false;
  5201. } else {
  5202. // The line segment spans at least one clip plane.
  5203. if ( bc1near < 0 ) {
  5204. // v1 lies outside the near plane, v2 inside
  5205. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5206. } else if ( bc2near < 0 ) {
  5207. // v2 lies outside the near plane, v1 inside
  5208. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5209. }
  5210. if ( bc1far < 0 ) {
  5211. // v1 lies outside the far plane, v2 inside
  5212. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5213. } else if ( bc2far < 0 ) {
  5214. // v2 lies outside the far plane, v2 inside
  5215. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5216. }
  5217. if ( alpha2 < alpha1 ) {
  5218. // The line segment spans two boundaries, but is outside both of them.
  5219. // (This can't happen when we're only clipping against just near/far but good
  5220. // to leave the check here for future usage if other clip planes are added.)
  5221. return false;
  5222. } else {
  5223. // Update the s1 and s2 vertices to match the clipped line segment.
  5224. s1.lerp( s2, alpha1 );
  5225. s2.lerp( s1, 1 - alpha2 );
  5226. return true;
  5227. }
  5228. }
  5229. }
  5230. };
  5231. /**
  5232. * @author mrdoob / http://mrdoob.com/
  5233. * @author alteredq / http://alteredqualia.com/
  5234. */
  5235. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5236. this.a = a;
  5237. this.b = b;
  5238. this.c = c;
  5239. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5240. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5241. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5242. this.vertexColors = color instanceof Array ? color : [];
  5243. this.vertexTangents = [];
  5244. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5245. };
  5246. THREE.Face3.prototype = {
  5247. constructor: THREE.Face3,
  5248. clone: function () {
  5249. var face = new THREE.Face3( this.a, this.b, this.c );
  5250. face.normal.copy( this.normal );
  5251. face.color.copy( this.color );
  5252. face.materialIndex = this.materialIndex;
  5253. var i, il;
  5254. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5255. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5256. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5257. return face;
  5258. }
  5259. };
  5260. /**
  5261. * @author mrdoob / http://mrdoob.com/
  5262. */
  5263. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5264. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5265. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5266. };
  5267. /**
  5268. * @author mrdoob / http://mrdoob.com/
  5269. */
  5270. THREE.BufferAttribute = function () {};
  5271. THREE.BufferAttribute.prototype = {
  5272. constructor: THREE.BufferAttribute,
  5273. get length () {
  5274. return this.array.length;
  5275. },
  5276. set: function ( value ) {
  5277. this.array.set( value );
  5278. return this;
  5279. },
  5280. setX: function ( index, x ) {
  5281. this.array[ index * this.itemSize ] = x;
  5282. return this;
  5283. },
  5284. setY: function ( index, y ) {
  5285. this.array[ index * this.itemSize + 1 ] = y;
  5286. return this;
  5287. },
  5288. setZ: function ( index, z ) {
  5289. this.array[ index * this.itemSize + 2 ] = z;
  5290. return this;
  5291. },
  5292. setXY: function ( index, x, y ) {
  5293. index *= this.itemSize;
  5294. this.array[ index ] = x;
  5295. this.array[ index + 1 ] = y;
  5296. return this;
  5297. },
  5298. setXYZ: function ( index, x, y, z ) {
  5299. index *= this.itemSize;
  5300. this.array[ index ] = x;
  5301. this.array[ index + 1 ] = y;
  5302. this.array[ index + 2 ] = z;
  5303. return this;
  5304. },
  5305. setXYZW: function ( index, x, y, z, w ) {
  5306. index *= this.itemSize;
  5307. this.array[ index ] = x;
  5308. this.array[ index + 1 ] = y;
  5309. this.array[ index + 2 ] = z;
  5310. this.array[ index + 3 ] = w;
  5311. return this;
  5312. }
  5313. };
  5314. //
  5315. THREE.Int8Attribute = function ( data, itemSize ) {
  5316. this.array = new Int8Array( data );
  5317. this.itemSize = itemSize;
  5318. };
  5319. THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5320. THREE.Uint8Attribute = function ( data, itemSize ) {
  5321. this.array = new Uint8Array( data );
  5322. this.itemSize = itemSize;
  5323. };
  5324. THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5325. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  5326. this.array = new Uint8ClampedArray( data );
  5327. this.itemSize = itemSize;
  5328. };
  5329. THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5330. THREE.Int16Attribute = function ( data, itemSize ) {
  5331. this.array = new Int16Array( data );
  5332. this.itemSize = itemSize;
  5333. };
  5334. THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5335. THREE.Uint16Attribute = function ( data, itemSize ) {
  5336. this.array = new Uint16Array( data );
  5337. this.itemSize = itemSize;
  5338. };
  5339. THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5340. THREE.Int32Attribute = function ( data, itemSize ) {
  5341. this.array = new Int32Array( data );
  5342. this.itemSize = itemSize;
  5343. };
  5344. THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5345. THREE.Uint32Attribute = function ( data, itemSize ) {
  5346. this.array = new Uint32Array( data );
  5347. this.itemSize = itemSize;
  5348. };
  5349. THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5350. THREE.Float32Attribute = function ( data, itemSize ) {
  5351. this.array = new Float32Array( data );
  5352. this.itemSize = itemSize;
  5353. };
  5354. THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5355. THREE.Float64Attribute = function ( data, itemSize ) {
  5356. this.array = new Float64Array( data );
  5357. this.itemSize = itemSize;
  5358. };
  5359. THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5360. /**
  5361. * @author alteredq / http://alteredqualia.com/
  5362. */
  5363. THREE.BufferGeometry = function () {
  5364. this.id = THREE.GeometryIdCount ++;
  5365. this.uuid = THREE.Math.generateUUID();
  5366. this.name = '';
  5367. this.attributes = {};
  5368. this.drawcalls = [];
  5369. this.offsets = this.drawcalls; // backwards compatibility
  5370. this.boundingBox = null;
  5371. this.boundingSphere = null;
  5372. };
  5373. THREE.BufferGeometry.prototype = {
  5374. constructor: THREE.BufferGeometry,
  5375. addAttribute: function ( name, attribute ) {
  5376. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5377. console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' );
  5378. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5379. return;
  5380. }
  5381. this.attributes[ name ] = attribute;
  5382. },
  5383. getAttribute: function ( name ) {
  5384. return this.attributes[ name ];
  5385. },
  5386. addDrawCall: function ( start, count, indexOffset ) {
  5387. this.drawcalls.push( {
  5388. start: start,
  5389. count: count,
  5390. index: indexOffset !== undefined ? indexOffset : 0
  5391. } );
  5392. },
  5393. applyMatrix: function ( matrix ) {
  5394. var position = this.attributes.position;
  5395. if ( position !== undefined ) {
  5396. matrix.applyToVector3Array( position.array );
  5397. position.needsUpdate = true;
  5398. }
  5399. var normal = this.attributes.normal;
  5400. if ( normal !== undefined ) {
  5401. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5402. normalMatrix.applyToVector3Array( normal.array );
  5403. normal.needsUpdate = true;
  5404. }
  5405. },
  5406. computeBoundingBox: function () {
  5407. if ( this.boundingBox === null ) {
  5408. this.boundingBox = new THREE.Box3();
  5409. }
  5410. var positions = this.attributes[ "position" ].array;
  5411. if ( positions ) {
  5412. var bb = this.boundingBox;
  5413. if( positions.length >= 3 ) {
  5414. bb.min.x = bb.max.x = positions[ 0 ];
  5415. bb.min.y = bb.max.y = positions[ 1 ];
  5416. bb.min.z = bb.max.z = positions[ 2 ];
  5417. }
  5418. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5419. var x = positions[ i ];
  5420. var y = positions[ i + 1 ];
  5421. var z = positions[ i + 2 ];
  5422. // bounding box
  5423. if ( x < bb.min.x ) {
  5424. bb.min.x = x;
  5425. } else if ( x > bb.max.x ) {
  5426. bb.max.x = x;
  5427. }
  5428. if ( y < bb.min.y ) {
  5429. bb.min.y = y;
  5430. } else if ( y > bb.max.y ) {
  5431. bb.max.y = y;
  5432. }
  5433. if ( z < bb.min.z ) {
  5434. bb.min.z = z;
  5435. } else if ( z > bb.max.z ) {
  5436. bb.max.z = z;
  5437. }
  5438. }
  5439. }
  5440. if ( positions === undefined || positions.length === 0 ) {
  5441. this.boundingBox.min.set( 0, 0, 0 );
  5442. this.boundingBox.max.set( 0, 0, 0 );
  5443. }
  5444. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5445. console.error( 'THREE.BufferGeometry.computeBoundingBox()', 'Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5446. }
  5447. },
  5448. computeBoundingSphere: function () {
  5449. var box = new THREE.Box3();
  5450. var vector = new THREE.Vector3();
  5451. return function () {
  5452. if ( this.boundingSphere === null ) {
  5453. this.boundingSphere = new THREE.Sphere();
  5454. }
  5455. var positions = this.attributes[ "position" ].array;
  5456. if ( positions ) {
  5457. box.makeEmpty();
  5458. var center = this.boundingSphere.center;
  5459. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5460. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5461. box.addPoint( vector );
  5462. }
  5463. box.center( center );
  5464. // hoping to find a boundingSphere with a radius smaller than the
  5465. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5466. var maxRadiusSq = 0;
  5467. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5468. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5469. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5470. }
  5471. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5472. if ( isNaN( this.boundingSphere.radius ) ) {
  5473. console.error( 'THREE.BufferGeometry.computeBoundingSphere()', 'Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5474. }
  5475. }
  5476. }
  5477. }(),
  5478. computeFaceNormals: function () {
  5479. // backwards compatibility
  5480. },
  5481. computeVertexNormals: function () {
  5482. if ( this.attributes[ "position" ] ) {
  5483. var i, il;
  5484. var j, jl;
  5485. var nVertexElements = this.attributes[ "position" ].array.length;
  5486. if ( this.attributes[ "normal" ] === undefined ) {
  5487. this.attributes[ "normal" ] = {
  5488. itemSize: 3,
  5489. array: new Float32Array( nVertexElements )
  5490. };
  5491. } else {
  5492. // reset existing normals to zero
  5493. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5494. this.attributes[ "normal" ].array[ i ] = 0;
  5495. }
  5496. }
  5497. var positions = this.attributes[ "position" ].array;
  5498. var normals = this.attributes[ "normal" ].array;
  5499. var vA, vB, vC, x, y, z,
  5500. pA = new THREE.Vector3(),
  5501. pB = new THREE.Vector3(),
  5502. pC = new THREE.Vector3(),
  5503. cb = new THREE.Vector3(),
  5504. ab = new THREE.Vector3();
  5505. // indexed elements
  5506. if ( this.attributes[ "index" ] ) {
  5507. var indices = this.attributes[ "index" ].array;
  5508. var offsets = (this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ]);
  5509. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5510. var start = offsets[ j ].start;
  5511. var count = offsets[ j ].count;
  5512. var index = offsets[ j ].index;
  5513. for ( i = start, il = start + count; i < il; i += 3 ) {
  5514. vA = index + indices[ i ];
  5515. vB = index + indices[ i + 1 ];
  5516. vC = index + indices[ i + 2 ];
  5517. x = positions[ vA * 3 ];
  5518. y = positions[ vA * 3 + 1 ];
  5519. z = positions[ vA * 3 + 2 ];
  5520. pA.set( x, y, z );
  5521. x = positions[ vB * 3 ];
  5522. y = positions[ vB * 3 + 1 ];
  5523. z = positions[ vB * 3 + 2 ];
  5524. pB.set( x, y, z );
  5525. x = positions[ vC * 3 ];
  5526. y = positions[ vC * 3 + 1 ];
  5527. z = positions[ vC * 3 + 2 ];
  5528. pC.set( x, y, z );
  5529. cb.subVectors( pC, pB );
  5530. ab.subVectors( pA, pB );
  5531. cb.cross( ab );
  5532. normals[ vA * 3 ] += cb.x;
  5533. normals[ vA * 3 + 1 ] += cb.y;
  5534. normals[ vA * 3 + 2 ] += cb.z;
  5535. normals[ vB * 3 ] += cb.x;
  5536. normals[ vB * 3 + 1 ] += cb.y;
  5537. normals[ vB * 3 + 2 ] += cb.z;
  5538. normals[ vC * 3 ] += cb.x;
  5539. normals[ vC * 3 + 1 ] += cb.y;
  5540. normals[ vC * 3 + 2 ] += cb.z;
  5541. }
  5542. }
  5543. // non-indexed elements (unconnected triangle soup)
  5544. } else {
  5545. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5546. x = positions[ i ];
  5547. y = positions[ i + 1 ];
  5548. z = positions[ i + 2 ];
  5549. pA.set( x, y, z );
  5550. x = positions[ i + 3 ];
  5551. y = positions[ i + 4 ];
  5552. z = positions[ i + 5 ];
  5553. pB.set( x, y, z );
  5554. x = positions[ i + 6 ];
  5555. y = positions[ i + 7 ];
  5556. z = positions[ i + 8 ];
  5557. pC.set( x, y, z );
  5558. cb.subVectors( pC, pB );
  5559. ab.subVectors( pA, pB );
  5560. cb.cross( ab );
  5561. normals[ i ] = cb.x;
  5562. normals[ i + 1 ] = cb.y;
  5563. normals[ i + 2 ] = cb.z;
  5564. normals[ i + 3 ] = cb.x;
  5565. normals[ i + 4 ] = cb.y;
  5566. normals[ i + 5 ] = cb.z;
  5567. normals[ i + 6 ] = cb.x;
  5568. normals[ i + 7 ] = cb.y;
  5569. normals[ i + 8 ] = cb.z;
  5570. }
  5571. }
  5572. this.normalizeNormals();
  5573. this.normalsNeedUpdate = true;
  5574. }
  5575. },
  5576. computeTangents: function () {
  5577. // based on http://www.terathon.com/code/tangent.html
  5578. // (per vertex tangents)
  5579. if ( this.attributes[ "index" ] === undefined ||
  5580. this.attributes[ "position" ] === undefined ||
  5581. this.attributes[ "normal" ] === undefined ||
  5582. this.attributes[ "uv" ] === undefined ) {
  5583. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5584. return;
  5585. }
  5586. var indices = this.attributes[ "index" ].array;
  5587. var positions = this.attributes[ "position" ].array;
  5588. var normals = this.attributes[ "normal" ].array;
  5589. var uvs = this.attributes[ "uv" ].array;
  5590. var nVertices = positions.length / 3;
  5591. if ( this.attributes[ "tangent" ] === undefined ) {
  5592. var nTangentElements = 4 * nVertices;
  5593. this.attributes[ "tangent" ] = {
  5594. itemSize: 4,
  5595. array: new Float32Array( nTangentElements )
  5596. };
  5597. }
  5598. var tangents = this.attributes[ "tangent" ].array;
  5599. var tan1 = [], tan2 = [];
  5600. for ( var k = 0; k < nVertices; k ++ ) {
  5601. tan1[ k ] = new THREE.Vector3();
  5602. tan2[ k ] = new THREE.Vector3();
  5603. }
  5604. var xA, yA, zA,
  5605. xB, yB, zB,
  5606. xC, yC, zC,
  5607. uA, vA,
  5608. uB, vB,
  5609. uC, vC,
  5610. x1, x2, y1, y2, z1, z2,
  5611. s1, s2, t1, t2, r;
  5612. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5613. function handleTriangle( a, b, c ) {
  5614. xA = positions[ a * 3 ];
  5615. yA = positions[ a * 3 + 1 ];
  5616. zA = positions[ a * 3 + 2 ];
  5617. xB = positions[ b * 3 ];
  5618. yB = positions[ b * 3 + 1 ];
  5619. zB = positions[ b * 3 + 2 ];
  5620. xC = positions[ c * 3 ];
  5621. yC = positions[ c * 3 + 1 ];
  5622. zC = positions[ c * 3 + 2 ];
  5623. uA = uvs[ a * 2 ];
  5624. vA = uvs[ a * 2 + 1 ];
  5625. uB = uvs[ b * 2 ];
  5626. vB = uvs[ b * 2 + 1 ];
  5627. uC = uvs[ c * 2 ];
  5628. vC = uvs[ c * 2 + 1 ];
  5629. x1 = xB - xA;
  5630. x2 = xC - xA;
  5631. y1 = yB - yA;
  5632. y2 = yC - yA;
  5633. z1 = zB - zA;
  5634. z2 = zC - zA;
  5635. s1 = uB - uA;
  5636. s2 = uC - uA;
  5637. t1 = vB - vA;
  5638. t2 = vC - vA;
  5639. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5640. sdir.set(
  5641. ( t2 * x1 - t1 * x2 ) * r,
  5642. ( t2 * y1 - t1 * y2 ) * r,
  5643. ( t2 * z1 - t1 * z2 ) * r
  5644. );
  5645. tdir.set(
  5646. ( s1 * x2 - s2 * x1 ) * r,
  5647. ( s1 * y2 - s2 * y1 ) * r,
  5648. ( s1 * z2 - s2 * z1 ) * r
  5649. );
  5650. tan1[ a ].add( sdir );
  5651. tan1[ b ].add( sdir );
  5652. tan1[ c ].add( sdir );
  5653. tan2[ a ].add( tdir );
  5654. tan2[ b ].add( tdir );
  5655. tan2[ c ].add( tdir );
  5656. }
  5657. var i, il;
  5658. var j, jl;
  5659. var iA, iB, iC;
  5660. var offsets = this.offsets;
  5661. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5662. var start = offsets[ j ].start;
  5663. var count = offsets[ j ].count;
  5664. var index = offsets[ j ].index;
  5665. for ( i = start, il = start + count; i < il; i += 3 ) {
  5666. iA = index + indices[ i ];
  5667. iB = index + indices[ i + 1 ];
  5668. iC = index + indices[ i + 2 ];
  5669. handleTriangle( iA, iB, iC );
  5670. }
  5671. }
  5672. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5673. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5674. var w, t, test;
  5675. function handleVertex( v ) {
  5676. n.x = normals[ v * 3 ];
  5677. n.y = normals[ v * 3 + 1 ];
  5678. n.z = normals[ v * 3 + 2 ];
  5679. n2.copy( n );
  5680. t = tan1[ v ];
  5681. // Gram-Schmidt orthogonalize
  5682. tmp.copy( t );
  5683. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5684. // Calculate handedness
  5685. tmp2.crossVectors( n2, t );
  5686. test = tmp2.dot( tan2[ v ] );
  5687. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5688. tangents[ v * 4 ] = tmp.x;
  5689. tangents[ v * 4 + 1 ] = tmp.y;
  5690. tangents[ v * 4 + 2 ] = tmp.z;
  5691. tangents[ v * 4 + 3 ] = w;
  5692. }
  5693. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5694. var start = offsets[ j ].start;
  5695. var count = offsets[ j ].count;
  5696. var index = offsets[ j ].index;
  5697. for ( i = start, il = start + count; i < il; i += 3 ) {
  5698. iA = index + indices[ i ];
  5699. iB = index + indices[ i + 1 ];
  5700. iC = index + indices[ i + 2 ];
  5701. handleVertex( iA );
  5702. handleVertex( iB );
  5703. handleVertex( iC );
  5704. }
  5705. }
  5706. },
  5707. /*
  5708. computeOffsets
  5709. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5710. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5711. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5712. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5713. */
  5714. computeOffsets: function(indexBufferSize) {
  5715. var size = indexBufferSize;
  5716. if(indexBufferSize === undefined)
  5717. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5718. var s = Date.now();
  5719. var indices = this.attributes['index'].array;
  5720. var vertices = this.attributes['position'].array;
  5721. var verticesCount = (vertices.length/3);
  5722. var facesCount = (indices.length/3);
  5723. /*
  5724. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5725. console.log("Faces to process: "+(indices.length/3));
  5726. console.log("Reordering "+verticesCount+" vertices.");
  5727. */
  5728. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5729. var indexPtr = 0;
  5730. var vertexPtr = 0;
  5731. var offsets = [ { start:0, count:0, index:0 } ];
  5732. var offset = offsets[0];
  5733. var duplicatedVertices = 0;
  5734. var newVerticeMaps = 0;
  5735. var faceVertices = new Int32Array(6);
  5736. var vertexMap = new Int32Array( vertices.length );
  5737. var revVertexMap = new Int32Array( vertices.length );
  5738. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5739. /*
  5740. Traverse every face and reorder vertices in the proper offsets of 65k.
  5741. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5742. */
  5743. for(var findex = 0; findex < facesCount; findex++) {
  5744. newVerticeMaps = 0;
  5745. for(var vo = 0; vo < 3; vo++) {
  5746. var vid = indices[ findex*3 + vo ];
  5747. if(vertexMap[vid] == -1) {
  5748. //Unmapped vertice
  5749. faceVertices[vo*2] = vid;
  5750. faceVertices[vo*2+1] = -1;
  5751. newVerticeMaps++;
  5752. } else if(vertexMap[vid] < offset.index) {
  5753. //Reused vertices from previous block (duplicate)
  5754. faceVertices[vo*2] = vid;
  5755. faceVertices[vo*2+1] = -1;
  5756. duplicatedVertices++;
  5757. } else {
  5758. //Reused vertice in the current block
  5759. faceVertices[vo*2] = vid;
  5760. faceVertices[vo*2+1] = vertexMap[vid];
  5761. }
  5762. }
  5763. var faceMax = vertexPtr + newVerticeMaps;
  5764. if(faceMax > (offset.index + size)) {
  5765. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5766. offsets.push(new_offset);
  5767. offset = new_offset;
  5768. //Re-evaluate reused vertices in light of new offset.
  5769. for(var v = 0; v < 6; v+=2) {
  5770. var new_vid = faceVertices[v+1];
  5771. if(new_vid > -1 && new_vid < offset.index)
  5772. faceVertices[v+1] = -1;
  5773. }
  5774. }
  5775. //Reindex the face.
  5776. for(var v = 0; v < 6; v+=2) {
  5777. var vid = faceVertices[v];
  5778. var new_vid = faceVertices[v+1];
  5779. if(new_vid === -1)
  5780. new_vid = vertexPtr++;
  5781. vertexMap[vid] = new_vid;
  5782. revVertexMap[new_vid] = vid;
  5783. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5784. offset.count++;
  5785. }
  5786. }
  5787. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5788. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5789. this.offsets = offsets;
  5790. /*
  5791. var orderTime = Date.now();
  5792. console.log("Reorder time: "+(orderTime-s)+"ms");
  5793. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5794. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5795. console.log("Draw offsets: "+offsets.length);
  5796. */
  5797. return offsets;
  5798. },
  5799. merge: function () {
  5800. console.log( 'BufferGeometry.merge(): TODO' );
  5801. },
  5802. normalizeNormals: function () {
  5803. var normals = this.attributes[ "normal" ].array;
  5804. var x, y, z, n;
  5805. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5806. x = normals[ i ];
  5807. y = normals[ i + 1 ];
  5808. z = normals[ i + 2 ];
  5809. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5810. normals[ i ] *= n;
  5811. normals[ i + 1 ] *= n;
  5812. normals[ i + 2 ] *= n;
  5813. }
  5814. },
  5815. /*
  5816. reoderBuffers:
  5817. Reorder attributes based on a new indexBuffer and indexMap.
  5818. indexBuffer - Uint16Array of the new ordered indices.
  5819. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5820. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5821. */
  5822. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5823. /* Create a copy of all attributes for reordering. */
  5824. var sortedAttributes = {};
  5825. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5826. for( var attr in this.attributes ) {
  5827. if(attr == 'index')
  5828. continue;
  5829. var sourceArray = this.attributes[attr].array;
  5830. for ( var i = 0, il = types.length; i < il; i++ ) {
  5831. var type = types[i];
  5832. if (sourceArray instanceof type) {
  5833. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5834. break;
  5835. }
  5836. }
  5837. }
  5838. /* Move attribute positions based on the new index map */
  5839. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5840. var vid = indexMap[new_vid];
  5841. for ( var attr in this.attributes ) {
  5842. if(attr == 'index')
  5843. continue;
  5844. var attrArray = this.attributes[attr].array;
  5845. var attrSize = this.attributes[attr].itemSize;
  5846. var sortedAttr = sortedAttributes[attr];
  5847. for(var k = 0; k < attrSize; k++)
  5848. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5849. }
  5850. }
  5851. /* Carry the new sorted buffers locally */
  5852. this.attributes['index'].array = indexBuffer;
  5853. for ( var attr in this.attributes ) {
  5854. if(attr == 'index')
  5855. continue;
  5856. this.attributes[attr].array = sortedAttributes[attr];
  5857. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5858. }
  5859. },
  5860. clone: function () {
  5861. var geometry = new THREE.BufferGeometry();
  5862. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5863. for ( var attr in this.attributes ) {
  5864. var sourceAttr = this.attributes[ attr ];
  5865. var sourceArray = sourceAttr.array;
  5866. var attribute = {
  5867. itemSize: sourceAttr.itemSize,
  5868. array: null
  5869. };
  5870. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5871. var type = types[ i ];
  5872. if ( sourceArray instanceof type ) {
  5873. attribute.array = new type( sourceArray );
  5874. break;
  5875. }
  5876. }
  5877. geometry.attributes[ attr ] = attribute;
  5878. }
  5879. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5880. var offset = this.offsets[ i ];
  5881. geometry.offsets.push( {
  5882. start: offset.start,
  5883. index: offset.index,
  5884. count: offset.count
  5885. } );
  5886. }
  5887. return geometry;
  5888. },
  5889. dispose: function () {
  5890. this.dispatchEvent( { type: 'dispose' } );
  5891. }
  5892. };
  5893. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5894. /**
  5895. * @author mrdoob / http://mrdoob.com/
  5896. * @author kile / http://kile.stravaganza.org/
  5897. * @author alteredq / http://alteredqualia.com/
  5898. * @author mikael emtinger / http://gomo.se/
  5899. * @author zz85 / http://www.lab4games.net/zz85/blog
  5900. * @author bhouston / http://exocortex.com
  5901. */
  5902. THREE.Geometry = function () {
  5903. this.id = THREE.GeometryIdCount ++;
  5904. this.uuid = THREE.Math.generateUUID();
  5905. this.name = '';
  5906. this.vertices = [];
  5907. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5908. this.faces = [];
  5909. this.faceVertexUvs = [[]];
  5910. this.morphTargets = [];
  5911. this.morphColors = [];
  5912. this.morphNormals = [];
  5913. this.skinWeights = [];
  5914. this.skinIndices = [];
  5915. this.lineDistances = [];
  5916. this.boundingBox = null;
  5917. this.boundingSphere = null;
  5918. this.hasTangents = false;
  5919. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5920. // update flags
  5921. this.verticesNeedUpdate = false;
  5922. this.elementsNeedUpdate = false;
  5923. this.uvsNeedUpdate = false;
  5924. this.normalsNeedUpdate = false;
  5925. this.tangentsNeedUpdate = false;
  5926. this.colorsNeedUpdate = false;
  5927. this.lineDistancesNeedUpdate = false;
  5928. this.buffersNeedUpdate = false;
  5929. };
  5930. THREE.Geometry.prototype = {
  5931. constructor: THREE.Geometry,
  5932. applyMatrix: function ( matrix ) {
  5933. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5934. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5935. var vertex = this.vertices[ i ];
  5936. vertex.applyMatrix4( matrix );
  5937. }
  5938. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5939. var face = this.faces[ i ];
  5940. face.normal.applyMatrix3( normalMatrix ).normalize();
  5941. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5942. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5943. }
  5944. }
  5945. if ( this.boundingBox instanceof THREE.Box3 ) {
  5946. this.computeBoundingBox();
  5947. }
  5948. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5949. this.computeBoundingSphere();
  5950. }
  5951. },
  5952. computeFaceNormals: function () {
  5953. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5954. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5955. var face = this.faces[ f ];
  5956. var vA = this.vertices[ face.a ];
  5957. var vB = this.vertices[ face.b ];
  5958. var vC = this.vertices[ face.c ];
  5959. cb.subVectors( vC, vB );
  5960. ab.subVectors( vA, vB );
  5961. cb.cross( ab );
  5962. cb.normalize();
  5963. face.normal.copy( cb );
  5964. }
  5965. },
  5966. computeVertexNormals: function ( areaWeighted ) {
  5967. var v, vl, f, fl, face, vertices;
  5968. vertices = new Array( this.vertices.length );
  5969. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5970. vertices[ v ] = new THREE.Vector3();
  5971. }
  5972. if ( areaWeighted ) {
  5973. // vertex normals weighted by triangle areas
  5974. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5975. var vA, vB, vC, vD;
  5976. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5977. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5978. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5979. face = this.faces[ f ];
  5980. vA = this.vertices[ face.a ];
  5981. vB = this.vertices[ face.b ];
  5982. vC = this.vertices[ face.c ];
  5983. cb.subVectors( vC, vB );
  5984. ab.subVectors( vA, vB );
  5985. cb.cross( ab );
  5986. vertices[ face.a ].add( cb );
  5987. vertices[ face.b ].add( cb );
  5988. vertices[ face.c ].add( cb );
  5989. }
  5990. } else {
  5991. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5992. face = this.faces[ f ];
  5993. vertices[ face.a ].add( face.normal );
  5994. vertices[ face.b ].add( face.normal );
  5995. vertices[ face.c ].add( face.normal );
  5996. }
  5997. }
  5998. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5999. vertices[ v ].normalize();
  6000. }
  6001. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6002. face = this.faces[ f ];
  6003. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6004. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6005. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6006. }
  6007. },
  6008. computeMorphNormals: function () {
  6009. var i, il, f, fl, face;
  6010. // save original normals
  6011. // - create temp variables on first access
  6012. // otherwise just copy (for faster repeated calls)
  6013. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6014. face = this.faces[ f ];
  6015. if ( ! face.__originalFaceNormal ) {
  6016. face.__originalFaceNormal = face.normal.clone();
  6017. } else {
  6018. face.__originalFaceNormal.copy( face.normal );
  6019. }
  6020. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6021. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6022. if ( ! face.__originalVertexNormals[ i ] ) {
  6023. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6024. } else {
  6025. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6026. }
  6027. }
  6028. }
  6029. // use temp geometry to compute face and vertex normals for each morph
  6030. var tmpGeo = new THREE.Geometry();
  6031. tmpGeo.faces = this.faces;
  6032. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6033. // create on first access
  6034. if ( ! this.morphNormals[ i ] ) {
  6035. this.morphNormals[ i ] = {};
  6036. this.morphNormals[ i ].faceNormals = [];
  6037. this.morphNormals[ i ].vertexNormals = [];
  6038. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6039. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6040. var faceNormal, vertexNormals;
  6041. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6042. faceNormal = new THREE.Vector3();
  6043. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6044. dstNormalsFace.push( faceNormal );
  6045. dstNormalsVertex.push( vertexNormals );
  6046. }
  6047. }
  6048. var morphNormals = this.morphNormals[ i ];
  6049. // set vertices to morph target
  6050. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6051. // compute morph normals
  6052. tmpGeo.computeFaceNormals();
  6053. tmpGeo.computeVertexNormals();
  6054. // store morph normals
  6055. var faceNormal, vertexNormals;
  6056. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6057. face = this.faces[ f ];
  6058. faceNormal = morphNormals.faceNormals[ f ];
  6059. vertexNormals = morphNormals.vertexNormals[ f ];
  6060. faceNormal.copy( face.normal );
  6061. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6062. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6063. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6064. }
  6065. }
  6066. // restore original normals
  6067. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6068. face = this.faces[ f ];
  6069. face.normal = face.__originalFaceNormal;
  6070. face.vertexNormals = face.__originalVertexNormals;
  6071. }
  6072. },
  6073. computeTangents: function () {
  6074. // based on http://www.terathon.com/code/tangent.html
  6075. // tangents go to vertices
  6076. var f, fl, v, vl, i, il, vertexIndex,
  6077. face, uv, vA, vB, vC, uvA, uvB, uvC,
  6078. x1, x2, y1, y2, z1, z2,
  6079. s1, s2, t1, t2, r, t, test,
  6080. tan1 = [], tan2 = [],
  6081. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  6082. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  6083. n = new THREE.Vector3(), w;
  6084. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6085. tan1[ v ] = new THREE.Vector3();
  6086. tan2[ v ] = new THREE.Vector3();
  6087. }
  6088. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  6089. vA = context.vertices[ a ];
  6090. vB = context.vertices[ b ];
  6091. vC = context.vertices[ c ];
  6092. uvA = uv[ ua ];
  6093. uvB = uv[ ub ];
  6094. uvC = uv[ uc ];
  6095. x1 = vB.x - vA.x;
  6096. x2 = vC.x - vA.x;
  6097. y1 = vB.y - vA.y;
  6098. y2 = vC.y - vA.y;
  6099. z1 = vB.z - vA.z;
  6100. z2 = vC.z - vA.z;
  6101. s1 = uvB.x - uvA.x;
  6102. s2 = uvC.x - uvA.x;
  6103. t1 = uvB.y - uvA.y;
  6104. t2 = uvC.y - uvA.y;
  6105. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6106. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  6107. ( t2 * y1 - t1 * y2 ) * r,
  6108. ( t2 * z1 - t1 * z2 ) * r );
  6109. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  6110. ( s1 * y2 - s2 * y1 ) * r,
  6111. ( s1 * z2 - s2 * z1 ) * r );
  6112. tan1[ a ].add( sdir );
  6113. tan1[ b ].add( sdir );
  6114. tan1[ c ].add( sdir );
  6115. tan2[ a ].add( tdir );
  6116. tan2[ b ].add( tdir );
  6117. tan2[ c ].add( tdir );
  6118. }
  6119. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6120. face = this.faces[ f ];
  6121. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6122. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6123. }
  6124. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6125. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6126. face = this.faces[ f ];
  6127. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  6128. n.copy( face.vertexNormals[ i ] );
  6129. vertexIndex = face[ faceIndex[ i ] ];
  6130. t = tan1[ vertexIndex ];
  6131. // Gram-Schmidt orthogonalize
  6132. tmp.copy( t );
  6133. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6134. // Calculate handedness
  6135. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6136. test = tmp2.dot( tan2[ vertexIndex ] );
  6137. w = (test < 0.0) ? -1.0 : 1.0;
  6138. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6139. }
  6140. }
  6141. this.hasTangents = true;
  6142. },
  6143. computeLineDistances: function ( ) {
  6144. var d = 0;
  6145. var vertices = this.vertices;
  6146. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6147. if ( i > 0 ) {
  6148. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6149. }
  6150. this.lineDistances[ i ] = d;
  6151. }
  6152. },
  6153. computeBoundingBox: function () {
  6154. if ( this.boundingBox === null ) {
  6155. this.boundingBox = new THREE.Box3();
  6156. }
  6157. this.boundingBox.setFromPoints( this.vertices );
  6158. },
  6159. computeBoundingSphere: function () {
  6160. if ( this.boundingSphere === null ) {
  6161. this.boundingSphere = new THREE.Sphere();
  6162. }
  6163. this.boundingSphere.setFromPoints( this.vertices );
  6164. },
  6165. merge: function ( geometry, matrix, materialIndexOffset ) {
  6166. if ( geometry instanceof THREE.Geometry === false ) {
  6167. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6168. return;
  6169. }
  6170. var normalMatrix,
  6171. vertexOffset = this.vertices.length,
  6172. uvPosition = this.faceVertexUvs[ 0 ].length,
  6173. vertices1 = this.vertices,
  6174. vertices2 = geometry.vertices,
  6175. faces1 = this.faces,
  6176. faces2 = geometry.faces,
  6177. uvs1 = this.faceVertexUvs[ 0 ],
  6178. uvs2 = geometry.faceVertexUvs[ 0 ];
  6179. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6180. if ( matrix !== undefined ) {
  6181. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6182. }
  6183. // vertices
  6184. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6185. var vertex = vertices2[ i ];
  6186. var vertexCopy = vertex.clone();
  6187. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6188. vertices1.push( vertexCopy );
  6189. }
  6190. // faces
  6191. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6192. var face = faces2[ i ], faceCopy, normal, color,
  6193. faceVertexNormals = face.vertexNormals,
  6194. faceVertexColors = face.vertexColors;
  6195. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6196. faceCopy.normal.copy( face.normal );
  6197. if ( normalMatrix !== undefined ) {
  6198. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6199. }
  6200. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6201. normal = faceVertexNormals[ j ].clone();
  6202. if ( normalMatrix !== undefined ) {
  6203. normal.applyMatrix3( normalMatrix ).normalize();
  6204. }
  6205. faceCopy.vertexNormals.push( normal );
  6206. }
  6207. faceCopy.color.copy( face.color );
  6208. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6209. color = faceVertexColors[ j ];
  6210. faceCopy.vertexColors.push( color.clone() );
  6211. }
  6212. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6213. faces1.push( faceCopy );
  6214. }
  6215. // uvs
  6216. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6217. var uv = uvs2[ i ], uvCopy = [];
  6218. if ( uv === undefined ) {
  6219. continue;
  6220. }
  6221. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6222. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6223. }
  6224. uvs1.push( uvCopy );
  6225. }
  6226. },
  6227. /*
  6228. * Checks for duplicate vertices with hashmap.
  6229. * Duplicated vertices are removed
  6230. * and faces' vertices are updated.
  6231. */
  6232. mergeVertices: function () {
  6233. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6234. var unique = [], changes = [];
  6235. var v, key;
  6236. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6237. var precision = Math.pow( 10, precisionPoints );
  6238. var i,il, face;
  6239. var indices, k, j, jl, u;
  6240. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6241. v = this.vertices[ i ];
  6242. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6243. if ( verticesMap[ key ] === undefined ) {
  6244. verticesMap[ key ] = i;
  6245. unique.push( this.vertices[ i ] );
  6246. changes[ i ] = unique.length - 1;
  6247. } else {
  6248. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6249. changes[ i ] = changes[ verticesMap[ key ] ];
  6250. }
  6251. };
  6252. // if faces are completely degenerate after merging vertices, we
  6253. // have to remove them from the geometry.
  6254. var faceIndicesToRemove = [];
  6255. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6256. face = this.faces[ i ];
  6257. face.a = changes[ face.a ];
  6258. face.b = changes[ face.b ];
  6259. face.c = changes[ face.c ];
  6260. indices = [ face.a, face.b, face.c ];
  6261. var dupIndex = -1;
  6262. // if any duplicate vertices are found in a Face3
  6263. // we have to remove the face as nothing can be saved
  6264. for ( var n = 0; n < 3; n ++ ) {
  6265. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6266. dupIndex = n;
  6267. faceIndicesToRemove.push( i );
  6268. break;
  6269. }
  6270. }
  6271. }
  6272. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6273. var idx = faceIndicesToRemove[ i ];
  6274. this.faces.splice( idx, 1 );
  6275. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6276. this.faceVertexUvs[ j ].splice( idx, 1 );
  6277. }
  6278. }
  6279. // Use unique set of vertices
  6280. var diff = this.vertices.length - unique.length;
  6281. this.vertices = unique;
  6282. return diff;
  6283. },
  6284. // Geometry splitting
  6285. makeGroups: ( function () {
  6286. var geometryGroupCounter = 0;
  6287. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6288. var f, fl, face, materialIndex,
  6289. groupHash, hash_map = {};
  6290. var numMorphTargets = this.morphTargets.length;
  6291. var numMorphNormals = this.morphNormals.length;
  6292. this.geometryGroups = {};
  6293. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6294. face = this.faces[ f ];
  6295. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6296. if ( ! ( materialIndex in hash_map ) ) {
  6297. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6298. }
  6299. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6300. if ( ! ( groupHash in this.geometryGroups ) ) {
  6301. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6302. }
  6303. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6304. hash_map[ materialIndex ].counter += 1;
  6305. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6306. if ( ! ( groupHash in this.geometryGroups ) ) {
  6307. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6308. }
  6309. }
  6310. this.geometryGroups[ groupHash ].faces3.push( f );
  6311. this.geometryGroups[ groupHash ].vertices += 3;
  6312. }
  6313. this.geometryGroupsList = [];
  6314. for ( var g in this.geometryGroups ) {
  6315. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6316. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6317. }
  6318. };
  6319. } )(),
  6320. clone: function () {
  6321. var geometry = new THREE.Geometry();
  6322. var vertices = this.vertices;
  6323. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6324. geometry.vertices.push( vertices[ i ].clone() );
  6325. }
  6326. var faces = this.faces;
  6327. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6328. geometry.faces.push( faces[ i ].clone() );
  6329. }
  6330. var uvs = this.faceVertexUvs[ 0 ];
  6331. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6332. var uv = uvs[ i ], uvCopy = [];
  6333. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6334. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6335. }
  6336. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6337. }
  6338. return geometry;
  6339. },
  6340. dispose: function () {
  6341. this.dispatchEvent( { type: 'dispose' } );
  6342. }
  6343. };
  6344. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6345. THREE.GeometryIdCount = 0;
  6346. /**
  6347. * @author mrdoob / http://mrdoob.com/
  6348. * @author mikael emtinger / http://gomo.se/
  6349. * @author WestLangley / http://github.com/WestLangley
  6350. */
  6351. THREE.Camera = function () {
  6352. THREE.Object3D.call( this );
  6353. this.matrixWorldInverse = new THREE.Matrix4();
  6354. this.projectionMatrix = new THREE.Matrix4();
  6355. };
  6356. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6357. THREE.Camera.prototype.lookAt = function () {
  6358. // This routine does not support cameras with rotated and/or translated parent(s)
  6359. var m1 = new THREE.Matrix4();
  6360. return function ( vector ) {
  6361. m1.lookAt( this.position, vector, this.up );
  6362. this.quaternion.setFromRotationMatrix( m1 );
  6363. };
  6364. }();
  6365. THREE.Camera.prototype.clone = function (camera) {
  6366. if ( camera === undefined ) camera = new THREE.Camera();
  6367. THREE.Object3D.prototype.clone.call( this, camera );
  6368. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6369. camera.projectionMatrix.copy( this.projectionMatrix );
  6370. return camera;
  6371. };
  6372. /**
  6373. * @author alteredq / http://alteredqualia.com/
  6374. */
  6375. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6376. THREE.Camera.call( this );
  6377. this.left = left;
  6378. this.right = right;
  6379. this.top = top;
  6380. this.bottom = bottom;
  6381. this.near = ( near !== undefined ) ? near : 0.1;
  6382. this.far = ( far !== undefined ) ? far : 2000;
  6383. this.updateProjectionMatrix();
  6384. };
  6385. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6386. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6387. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6388. };
  6389. THREE.OrthographicCamera.prototype.clone = function () {
  6390. var camera = new THREE.OrthographicCamera();
  6391. THREE.Camera.prototype.clone.call( this, camera );
  6392. camera.left = this.left;
  6393. camera.right = this.right;
  6394. camera.top = this.top;
  6395. camera.bottom = this.bottom;
  6396. camera.near = this.near;
  6397. camera.far = this.far;
  6398. return camera;
  6399. };
  6400. /**
  6401. * @author mrdoob / http://mrdoob.com/
  6402. * @author greggman / http://games.greggman.com/
  6403. * @author zz85 / http://www.lab4games.net/zz85/blog
  6404. */
  6405. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6406. THREE.Camera.call( this );
  6407. this.fov = fov !== undefined ? fov : 50;
  6408. this.aspect = aspect !== undefined ? aspect : 1;
  6409. this.near = near !== undefined ? near : 0.1;
  6410. this.far = far !== undefined ? far : 2000;
  6411. this.updateProjectionMatrix();
  6412. };
  6413. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6414. /**
  6415. * Uses Focal Length (in mm) to estimate and set FOV
  6416. * 35mm (fullframe) camera is used if frame size is not specified;
  6417. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6418. */
  6419. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6420. if ( frameHeight === undefined ) frameHeight = 24;
  6421. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6422. this.updateProjectionMatrix();
  6423. }
  6424. /**
  6425. * Sets an offset in a larger frustum. This is useful for multi-window or
  6426. * multi-monitor/multi-machine setups.
  6427. *
  6428. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6429. * the monitors are in grid like this
  6430. *
  6431. * +---+---+---+
  6432. * | A | B | C |
  6433. * +---+---+---+
  6434. * | D | E | F |
  6435. * +---+---+---+
  6436. *
  6437. * then for each monitor you would call it like this
  6438. *
  6439. * var w = 1920;
  6440. * var h = 1080;
  6441. * var fullWidth = w * 3;
  6442. * var fullHeight = h * 2;
  6443. *
  6444. * --A--
  6445. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6446. * --B--
  6447. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6448. * --C--
  6449. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6450. * --D--
  6451. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6452. * --E--
  6453. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6454. * --F--
  6455. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6456. *
  6457. * Note there is no reason monitors have to be the same size or in a grid.
  6458. */
  6459. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6460. this.fullWidth = fullWidth;
  6461. this.fullHeight = fullHeight;
  6462. this.x = x;
  6463. this.y = y;
  6464. this.width = width;
  6465. this.height = height;
  6466. this.updateProjectionMatrix();
  6467. };
  6468. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6469. if ( this.fullWidth ) {
  6470. var aspect = this.fullWidth / this.fullHeight;
  6471. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6472. var bottom = -top;
  6473. var left = aspect * bottom;
  6474. var right = aspect * top;
  6475. var width = Math.abs( right - left );
  6476. var height = Math.abs( top - bottom );
  6477. this.projectionMatrix.makeFrustum(
  6478. left + this.x * width / this.fullWidth,
  6479. left + ( this.x + this.width ) * width / this.fullWidth,
  6480. top - ( this.y + this.height ) * height / this.fullHeight,
  6481. top - this.y * height / this.fullHeight,
  6482. this.near,
  6483. this.far
  6484. );
  6485. } else {
  6486. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6487. }
  6488. };
  6489. THREE.PerspectiveCamera.prototype.clone = function () {
  6490. var camera = new THREE.PerspectiveCamera();
  6491. THREE.Camera.prototype.clone.call( this, camera );
  6492. camera.fov = this.fov;
  6493. camera.aspect = this.aspect;
  6494. camera.near = this.near;
  6495. camera.far = this.far;
  6496. return camera;
  6497. };
  6498. /**
  6499. * @author mrdoob / http://mrdoob.com/
  6500. * @author alteredq / http://alteredqualia.com/
  6501. */
  6502. THREE.Light = function ( color ) {
  6503. THREE.Object3D.call( this );
  6504. this.color = new THREE.Color( color );
  6505. };
  6506. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6507. THREE.Light.prototype.clone = function ( light ) {
  6508. if ( light === undefined ) light = new THREE.Light();
  6509. THREE.Object3D.prototype.clone.call( this, light );
  6510. light.color.copy( this.color );
  6511. return light;
  6512. };
  6513. /**
  6514. * @author mrdoob / http://mrdoob.com/
  6515. */
  6516. THREE.AmbientLight = function ( color ) {
  6517. THREE.Light.call( this, color );
  6518. };
  6519. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6520. THREE.AmbientLight.prototype.clone = function () {
  6521. var light = new THREE.AmbientLight();
  6522. THREE.Light.prototype.clone.call( this, light );
  6523. return light;
  6524. };
  6525. /**
  6526. * @author MPanknin / http://www.redplant.de/
  6527. * @author alteredq / http://alteredqualia.com/
  6528. */
  6529. THREE.AreaLight = function ( color, intensity ) {
  6530. THREE.Light.call( this, color );
  6531. this.normal = new THREE.Vector3( 0, -1, 0 );
  6532. this.right = new THREE.Vector3( 1, 0, 0 );
  6533. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6534. this.width = 1.0;
  6535. this.height = 1.0;
  6536. this.constantAttenuation = 1.5;
  6537. this.linearAttenuation = 0.5;
  6538. this.quadraticAttenuation = 0.1;
  6539. };
  6540. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6541. /**
  6542. * @author mrdoob / http://mrdoob.com/
  6543. * @author alteredq / http://alteredqualia.com/
  6544. */
  6545. THREE.DirectionalLight = function ( color, intensity ) {
  6546. THREE.Light.call( this, color );
  6547. this.position.set( 0, 1, 0 );
  6548. this.target = new THREE.Object3D();
  6549. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6550. this.castShadow = false;
  6551. this.onlyShadow = false;
  6552. //
  6553. this.shadowCameraNear = 50;
  6554. this.shadowCameraFar = 5000;
  6555. this.shadowCameraLeft = -500;
  6556. this.shadowCameraRight = 500;
  6557. this.shadowCameraTop = 500;
  6558. this.shadowCameraBottom = -500;
  6559. this.shadowCameraVisible = false;
  6560. this.shadowBias = 0;
  6561. this.shadowDarkness = 0.5;
  6562. this.shadowMapWidth = 512;
  6563. this.shadowMapHeight = 512;
  6564. //
  6565. this.shadowCascade = false;
  6566. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6567. this.shadowCascadeCount = 2;
  6568. this.shadowCascadeBias = [ 0, 0, 0 ];
  6569. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6570. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6571. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6572. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6573. this.shadowCascadeArray = [];
  6574. //
  6575. this.shadowMap = null;
  6576. this.shadowMapSize = null;
  6577. this.shadowCamera = null;
  6578. this.shadowMatrix = null;
  6579. };
  6580. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6581. THREE.DirectionalLight.prototype.clone = function () {
  6582. var light = new THREE.DirectionalLight();
  6583. THREE.Light.prototype.clone.call( this, light );
  6584. light.target = this.target.clone();
  6585. light.intensity = this.intensity;
  6586. light.castShadow = this.castShadow;
  6587. light.onlyShadow = this.onlyShadow;
  6588. //
  6589. light.shadowCameraNear = this.shadowCameraNear;
  6590. light.shadowCameraFar = this.shadowCameraFar;
  6591. light.shadowCameraLeft = this.shadowCameraLeft;
  6592. light.shadowCameraRight = this.shadowCameraRight;
  6593. light.shadowCameraTop = this.shadowCameraTop;
  6594. light.shadowCameraBottom = this.shadowCameraBottom;
  6595. light.shadowCameraVisible = this.shadowCameraVisible;
  6596. light.shadowBias = this.shadowBias;
  6597. light.shadowDarkness = this.shadowDarkness;
  6598. light.shadowMapWidth = this.shadowMapWidth;
  6599. light.shadowMapHeight = this.shadowMapHeight;
  6600. //
  6601. light.shadowCascade = this.shadowCascade;
  6602. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6603. light.shadowCascadeCount = this.shadowCascadeCount;
  6604. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6605. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6606. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6607. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6608. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6609. return light;
  6610. };
  6611. /**
  6612. * @author alteredq / http://alteredqualia.com/
  6613. */
  6614. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6615. THREE.Light.call( this, skyColor );
  6616. this.position.set( 0, 100, 0 );
  6617. this.groundColor = new THREE.Color( groundColor );
  6618. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6619. };
  6620. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6621. THREE.HemisphereLight.prototype.clone = function () {
  6622. var light = new THREE.HemisphereLight();
  6623. THREE.Light.prototype.clone.call( this, light );
  6624. light.groundColor.copy( this.groundColor );
  6625. light.intensity = this.intensity;
  6626. return light;
  6627. };
  6628. /**
  6629. * @author mrdoob / http://mrdoob.com/
  6630. */
  6631. THREE.PointLight = function ( color, intensity, distance ) {
  6632. THREE.Light.call( this, color );
  6633. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6634. this.distance = ( distance !== undefined ) ? distance : 0;
  6635. };
  6636. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6637. THREE.PointLight.prototype.clone = function () {
  6638. var light = new THREE.PointLight();
  6639. THREE.Light.prototype.clone.call( this, light );
  6640. light.intensity = this.intensity;
  6641. light.distance = this.distance;
  6642. return light;
  6643. };
  6644. /**
  6645. * @author alteredq / http://alteredqualia.com/
  6646. */
  6647. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6648. THREE.Light.call( this, color );
  6649. this.position.set( 0, 1, 0 );
  6650. this.target = new THREE.Object3D();
  6651. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6652. this.distance = ( distance !== undefined ) ? distance : 0;
  6653. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6654. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6655. this.castShadow = false;
  6656. this.onlyShadow = false;
  6657. //
  6658. this.shadowCameraNear = 50;
  6659. this.shadowCameraFar = 5000;
  6660. this.shadowCameraFov = 50;
  6661. this.shadowCameraVisible = false;
  6662. this.shadowBias = 0;
  6663. this.shadowDarkness = 0.5;
  6664. this.shadowMapWidth = 512;
  6665. this.shadowMapHeight = 512;
  6666. //
  6667. this.shadowMap = null;
  6668. this.shadowMapSize = null;
  6669. this.shadowCamera = null;
  6670. this.shadowMatrix = null;
  6671. };
  6672. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6673. THREE.SpotLight.prototype.clone = function () {
  6674. var light = new THREE.SpotLight();
  6675. THREE.Light.prototype.clone.call( this, light );
  6676. light.target = this.target.clone();
  6677. light.intensity = this.intensity;
  6678. light.distance = this.distance;
  6679. light.angle = this.angle;
  6680. light.exponent = this.exponent;
  6681. light.castShadow = this.castShadow;
  6682. light.onlyShadow = this.onlyShadow;
  6683. //
  6684. light.shadowCameraNear = this.shadowCameraNear;
  6685. light.shadowCameraFar = this.shadowCameraFar;
  6686. light.shadowCameraFov = this.shadowCameraFov;
  6687. light.shadowCameraVisible = this.shadowCameraVisible;
  6688. light.shadowBias = this.shadowBias;
  6689. light.shadowDarkness = this.shadowDarkness;
  6690. light.shadowMapWidth = this.shadowMapWidth;
  6691. light.shadowMapHeight = this.shadowMapHeight;
  6692. return light;
  6693. };
  6694. /**
  6695. * @author mrdoob / http://mrdoob.com/
  6696. */
  6697. THREE.Cache = function () {
  6698. this.files = {};
  6699. };
  6700. THREE.Cache.prototype = {
  6701. constructor: THREE.Cache,
  6702. add: function ( key, file ) {
  6703. // console.log( 'THREE.Cache', 'Adding key:', key );
  6704. this.files[ key ] = file;
  6705. },
  6706. get: function ( key ) {
  6707. // console.log( 'THREE.Cache', 'Checking key:', key );
  6708. return this.files[ key ];
  6709. },
  6710. remove: function ( key ) {
  6711. delete this.files[ key ];
  6712. },
  6713. clear: function () {
  6714. this.files = {}
  6715. }
  6716. };
  6717. /**
  6718. * @author alteredq / http://alteredqualia.com/
  6719. */
  6720. THREE.Loader = function ( showStatus ) {
  6721. this.showStatus = showStatus;
  6722. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6723. this.imageLoader = new THREE.ImageLoader();
  6724. this.onLoadStart = function () {};
  6725. this.onLoadProgress = function () {};
  6726. this.onLoadComplete = function () {};
  6727. };
  6728. THREE.Loader.prototype = {
  6729. constructor: THREE.Loader,
  6730. crossOrigin: undefined,
  6731. addStatusElement: function () {
  6732. var e = document.createElement( "div" );
  6733. e.style.position = "absolute";
  6734. e.style.right = "0px";
  6735. e.style.top = "0px";
  6736. e.style.fontSize = "0.8em";
  6737. e.style.textAlign = "left";
  6738. e.style.background = "rgba(0,0,0,0.25)";
  6739. e.style.color = "#fff";
  6740. e.style.width = "120px";
  6741. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6742. e.style.zIndex = 1000;
  6743. e.innerHTML = "Loading ...";
  6744. return e;
  6745. },
  6746. updateProgress: function ( progress ) {
  6747. var message = "Loaded ";
  6748. if ( progress.total ) {
  6749. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6750. } else {
  6751. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6752. }
  6753. this.statusDomElement.innerHTML = message;
  6754. },
  6755. extractUrlBase: function ( url ) {
  6756. var parts = url.split( '/' );
  6757. if ( parts.length === 1 ) return './';
  6758. parts.pop();
  6759. return parts.join( '/' ) + '/';
  6760. },
  6761. initMaterials: function ( materials, texturePath ) {
  6762. var array = [];
  6763. for ( var i = 0; i < materials.length; ++ i ) {
  6764. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6765. }
  6766. return array;
  6767. },
  6768. needsTangents: function ( materials ) {
  6769. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6770. var m = materials[ i ];
  6771. if ( m instanceof THREE.ShaderMaterial ) return true;
  6772. }
  6773. return false;
  6774. },
  6775. createMaterial: function ( m, texturePath ) {
  6776. var scope = this;
  6777. function nearest_pow2( n ) {
  6778. var l = Math.log( n ) / Math.LN2;
  6779. return Math.pow( 2, Math.round( l ) );
  6780. }
  6781. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6782. var isCompressed = /\.dds$/i.test( sourceFile );
  6783. var fullPath = texturePath + sourceFile;
  6784. if ( isCompressed ) {
  6785. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6786. where[ name ] = texture;
  6787. } else {
  6788. var texture = document.createElement( 'canvas' );
  6789. where[ name ] = new THREE.Texture( texture );
  6790. }
  6791. where[ name ].sourceFile = sourceFile;
  6792. if( repeat ) {
  6793. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6794. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6795. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6796. }
  6797. if ( offset ) {
  6798. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6799. }
  6800. if ( wrap ) {
  6801. var wrapMap = {
  6802. "repeat": THREE.RepeatWrapping,
  6803. "mirror": THREE.MirroredRepeatWrapping
  6804. }
  6805. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6806. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6807. }
  6808. if ( anisotropy ) {
  6809. where[ name ].anisotropy = anisotropy;
  6810. }
  6811. if ( ! isCompressed ) {
  6812. var texture = where[ name ];
  6813. scope.imageLoader.crossOrigin = scope.crossOrigin;
  6814. scope.imageLoader.load( fullPath, function ( image ) {
  6815. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6816. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6817. var width = nearest_pow2( image.width );
  6818. var height = nearest_pow2( image.height );
  6819. texture.image.width = width;
  6820. texture.image.height = height;
  6821. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  6822. } else {
  6823. texture.image = image;
  6824. }
  6825. texture.needsUpdate = true;
  6826. } );
  6827. }
  6828. }
  6829. function rgb2hex( rgb ) {
  6830. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6831. }
  6832. // defaults
  6833. var mtype = "MeshLambertMaterial";
  6834. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6835. // parameters from model file
  6836. if ( m.shading ) {
  6837. var shading = m.shading.toLowerCase();
  6838. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6839. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6840. }
  6841. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6842. mpars.blending = THREE[ m.blending ];
  6843. }
  6844. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6845. mpars.transparent = m.transparent;
  6846. }
  6847. if ( m.depthTest !== undefined ) {
  6848. mpars.depthTest = m.depthTest;
  6849. }
  6850. if ( m.depthWrite !== undefined ) {
  6851. mpars.depthWrite = m.depthWrite;
  6852. }
  6853. if ( m.visible !== undefined ) {
  6854. mpars.visible = m.visible;
  6855. }
  6856. if ( m.flipSided !== undefined ) {
  6857. mpars.side = THREE.BackSide;
  6858. }
  6859. if ( m.doubleSided !== undefined ) {
  6860. mpars.side = THREE.DoubleSide;
  6861. }
  6862. if ( m.wireframe !== undefined ) {
  6863. mpars.wireframe = m.wireframe;
  6864. }
  6865. if ( m.vertexColors !== undefined ) {
  6866. if ( m.vertexColors === "face" ) {
  6867. mpars.vertexColors = THREE.FaceColors;
  6868. } else if ( m.vertexColors ) {
  6869. mpars.vertexColors = THREE.VertexColors;
  6870. }
  6871. }
  6872. // colors
  6873. if ( m.colorDiffuse ) {
  6874. mpars.color = rgb2hex( m.colorDiffuse );
  6875. } else if ( m.DbgColor ) {
  6876. mpars.color = m.DbgColor;
  6877. }
  6878. if ( m.colorSpecular ) {
  6879. mpars.specular = rgb2hex( m.colorSpecular );
  6880. }
  6881. if ( m.colorAmbient ) {
  6882. mpars.ambient = rgb2hex( m.colorAmbient );
  6883. }
  6884. if ( m.colorEmissive ) {
  6885. mpars.emissive = rgb2hex( m.colorEmissive );
  6886. }
  6887. // modifiers
  6888. if ( m.transparency ) {
  6889. mpars.opacity = m.transparency;
  6890. }
  6891. if ( m.specularCoef ) {
  6892. mpars.shininess = m.specularCoef;
  6893. }
  6894. // textures
  6895. if ( m.mapDiffuse && texturePath ) {
  6896. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6897. }
  6898. if ( m.mapLight && texturePath ) {
  6899. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6900. }
  6901. if ( m.mapBump && texturePath ) {
  6902. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6903. }
  6904. if ( m.mapNormal && texturePath ) {
  6905. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6906. }
  6907. if ( m.mapSpecular && texturePath ) {
  6908. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6909. }
  6910. //
  6911. if ( m.mapBumpScale ) {
  6912. mpars.bumpScale = m.mapBumpScale;
  6913. }
  6914. // special case for normal mapped material
  6915. if ( m.mapNormal ) {
  6916. var shader = THREE.ShaderLib[ "normalmap" ];
  6917. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6918. uniforms[ "tNormal" ].value = mpars.normalMap;
  6919. if ( m.mapNormalFactor ) {
  6920. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6921. }
  6922. if ( mpars.map ) {
  6923. uniforms[ "tDiffuse" ].value = mpars.map;
  6924. uniforms[ "enableDiffuse" ].value = true;
  6925. }
  6926. if ( mpars.specularMap ) {
  6927. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6928. uniforms[ "enableSpecular" ].value = true;
  6929. }
  6930. if ( mpars.lightMap ) {
  6931. uniforms[ "tAO" ].value = mpars.lightMap;
  6932. uniforms[ "enableAO" ].value = true;
  6933. }
  6934. // for the moment don't handle displacement texture
  6935. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6936. uniforms[ "specular" ].value.setHex( mpars.specular );
  6937. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6938. uniforms[ "shininess" ].value = mpars.shininess;
  6939. if ( mpars.opacity !== undefined ) {
  6940. uniforms[ "opacity" ].value = mpars.opacity;
  6941. }
  6942. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6943. var material = new THREE.ShaderMaterial( parameters );
  6944. if ( mpars.transparent ) {
  6945. material.transparent = true;
  6946. }
  6947. } else {
  6948. var material = new THREE[ mtype ]( mpars );
  6949. }
  6950. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6951. return material;
  6952. }
  6953. };
  6954. /**
  6955. * @author mrdoob / http://mrdoob.com/
  6956. */
  6957. THREE.XHRLoader = function ( manager ) {
  6958. this.cache = new THREE.Cache();
  6959. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6960. };
  6961. THREE.XHRLoader.prototype = {
  6962. constructor: THREE.XHRLoader,
  6963. load: function ( url, onLoad, onProgress, onError ) {
  6964. var scope = this;
  6965. var cached = scope.cache.get( url );
  6966. if ( cached !== undefined ) {
  6967. onLoad( cached );
  6968. return;
  6969. }
  6970. var request = new XMLHttpRequest();
  6971. if ( onLoad !== undefined ) {
  6972. request.addEventListener( 'load', function ( event ) {
  6973. scope.cache.add( url, event.target.responseText );
  6974. onLoad( event.target.responseText );
  6975. scope.manager.itemEnd( url );
  6976. }, false );
  6977. }
  6978. if ( onProgress !== undefined ) {
  6979. request.addEventListener( 'progress', function ( event ) {
  6980. onProgress( event );
  6981. }, false );
  6982. }
  6983. if ( onError !== undefined ) {
  6984. request.addEventListener( 'error', function ( event ) {
  6985. onError( event );
  6986. }, false );
  6987. }
  6988. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6989. request.open( 'GET', url, true );
  6990. request.send( null );
  6991. scope.manager.itemStart( url );
  6992. },
  6993. setCrossOrigin: function ( value ) {
  6994. this.crossOrigin = value;
  6995. }
  6996. };
  6997. /**
  6998. * @author mrdoob / http://mrdoob.com/
  6999. */
  7000. THREE.ImageLoader = function ( manager ) {
  7001. this.cache = new THREE.Cache();
  7002. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7003. };
  7004. THREE.ImageLoader.prototype = {
  7005. constructor: THREE.ImageLoader,
  7006. load: function ( url, onLoad, onProgress, onError ) {
  7007. var scope = this;
  7008. var cached = scope.cache.get( url );
  7009. if ( cached !== undefined ) {
  7010. onLoad( cached );
  7011. return;
  7012. }
  7013. var image = document.createElement( 'img' );
  7014. if ( onLoad !== undefined ) {
  7015. image.addEventListener( 'load', function ( event ) {
  7016. scope.cache.add( url, this );
  7017. onLoad( this );
  7018. scope.manager.itemEnd( url );
  7019. }, false );
  7020. }
  7021. if ( onProgress !== undefined ) {
  7022. image.addEventListener( 'progress', function ( event ) {
  7023. onProgress( event );
  7024. }, false );
  7025. }
  7026. if ( onError !== undefined ) {
  7027. image.addEventListener( 'error', function ( event ) {
  7028. onError( event );
  7029. }, false );
  7030. }
  7031. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7032. image.src = url;
  7033. scope.manager.itemStart( url );
  7034. return image;
  7035. },
  7036. setCrossOrigin: function ( value ) {
  7037. this.crossOrigin = value;
  7038. }
  7039. }
  7040. /**
  7041. * @author mrdoob / http://mrdoob.com/
  7042. * @author alteredq / http://alteredqualia.com/
  7043. */
  7044. THREE.JSONLoader = function ( showStatus ) {
  7045. THREE.Loader.call( this, showStatus );
  7046. this.withCredentials = false;
  7047. };
  7048. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7049. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7050. var scope = this;
  7051. // todo: unify load API to for easier SceneLoader use
  7052. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  7053. this.onLoadStart();
  7054. this.loadAjaxJSON( this, url, callback, texturePath );
  7055. };
  7056. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7057. var xhr = new XMLHttpRequest();
  7058. var length = 0;
  7059. xhr.onreadystatechange = function () {
  7060. if ( xhr.readyState === xhr.DONE ) {
  7061. if ( xhr.status === 200 || xhr.status === 0 ) {
  7062. if ( xhr.responseText ) {
  7063. var json = JSON.parse( xhr.responseText );
  7064. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7065. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7066. return;
  7067. }
  7068. var result = context.parse( json, texturePath );
  7069. callback( result.geometry, result.materials );
  7070. } else {
  7071. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7072. }
  7073. // in context of more complex asset initialization
  7074. // do not block on single failed file
  7075. // maybe should go even one more level up
  7076. context.onLoadComplete();
  7077. } else {
  7078. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7079. }
  7080. } else if ( xhr.readyState === xhr.LOADING ) {
  7081. if ( callbackProgress ) {
  7082. if ( length === 0 ) {
  7083. length = xhr.getResponseHeader( 'Content-Length' );
  7084. }
  7085. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7086. }
  7087. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7088. if ( callbackProgress !== undefined ) {
  7089. length = xhr.getResponseHeader( "Content-Length" );
  7090. }
  7091. }
  7092. };
  7093. xhr.open( "GET", url, true );
  7094. xhr.withCredentials = this.withCredentials;
  7095. xhr.send( null );
  7096. };
  7097. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7098. var scope = this,
  7099. geometry = new THREE.Geometry(),
  7100. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7101. parseModel( scale );
  7102. parseSkin();
  7103. parseMorphing( scale );
  7104. geometry.computeFaceNormals();
  7105. geometry.computeBoundingSphere();
  7106. function parseModel( scale ) {
  7107. function isBitSet( value, position ) {
  7108. return value & ( 1 << position );
  7109. }
  7110. var i, j, fi,
  7111. offset, zLength,
  7112. colorIndex, normalIndex, uvIndex, materialIndex,
  7113. type,
  7114. isQuad,
  7115. hasMaterial,
  7116. hasFaceVertexUv,
  7117. hasFaceNormal, hasFaceVertexNormal,
  7118. hasFaceColor, hasFaceVertexColor,
  7119. vertex, face, faceA, faceB, color, hex, normal,
  7120. uvLayer, uv, u, v,
  7121. faces = json.faces,
  7122. vertices = json.vertices,
  7123. normals = json.normals,
  7124. colors = json.colors,
  7125. nUvLayers = 0;
  7126. if ( json.uvs !== undefined ) {
  7127. // disregard empty arrays
  7128. for ( i = 0; i < json.uvs.length; i++ ) {
  7129. if ( json.uvs[ i ].length ) nUvLayers ++;
  7130. }
  7131. for ( i = 0; i < nUvLayers; i++ ) {
  7132. geometry.faceVertexUvs[ i ] = [];
  7133. }
  7134. }
  7135. offset = 0;
  7136. zLength = vertices.length;
  7137. while ( offset < zLength ) {
  7138. vertex = new THREE.Vector3();
  7139. vertex.x = vertices[ offset ++ ] * scale;
  7140. vertex.y = vertices[ offset ++ ] * scale;
  7141. vertex.z = vertices[ offset ++ ] * scale;
  7142. geometry.vertices.push( vertex );
  7143. }
  7144. offset = 0;
  7145. zLength = faces.length;
  7146. while ( offset < zLength ) {
  7147. type = faces[ offset ++ ];
  7148. isQuad = isBitSet( type, 0 );
  7149. hasMaterial = isBitSet( type, 1 );
  7150. hasFaceVertexUv = isBitSet( type, 3 );
  7151. hasFaceNormal = isBitSet( type, 4 );
  7152. hasFaceVertexNormal = isBitSet( type, 5 );
  7153. hasFaceColor = isBitSet( type, 6 );
  7154. hasFaceVertexColor = isBitSet( type, 7 );
  7155. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7156. if ( isQuad ) {
  7157. faceA = new THREE.Face3();
  7158. faceA.a = faces[ offset ];
  7159. faceA.b = faces[ offset + 1 ];
  7160. faceA.c = faces[ offset + 3 ];
  7161. faceB = new THREE.Face3();
  7162. faceB.a = faces[ offset + 1 ];
  7163. faceB.b = faces[ offset + 2 ];
  7164. faceB.c = faces[ offset + 3 ];
  7165. offset += 4;
  7166. if ( hasMaterial ) {
  7167. materialIndex = faces[ offset ++ ];
  7168. faceA.materialIndex = materialIndex;
  7169. faceB.materialIndex = materialIndex;
  7170. }
  7171. // to get face <=> uv index correspondence
  7172. fi = geometry.faces.length;
  7173. if ( hasFaceVertexUv ) {
  7174. for ( i = 0; i < nUvLayers; i++ ) {
  7175. uvLayer = json.uvs[ i ];
  7176. geometry.faceVertexUvs[ i ][ fi ] = [];
  7177. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7178. for ( j = 0; j < 4; j ++ ) {
  7179. uvIndex = faces[ offset ++ ];
  7180. u = uvLayer[ uvIndex * 2 ];
  7181. v = uvLayer[ uvIndex * 2 + 1 ];
  7182. uv = new THREE.Vector2( u, v );
  7183. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7184. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7185. }
  7186. }
  7187. }
  7188. if ( hasFaceNormal ) {
  7189. normalIndex = faces[ offset ++ ] * 3;
  7190. faceA.normal.set(
  7191. normals[ normalIndex ++ ],
  7192. normals[ normalIndex ++ ],
  7193. normals[ normalIndex ]
  7194. );
  7195. faceB.normal.copy( faceA.normal );
  7196. }
  7197. if ( hasFaceVertexNormal ) {
  7198. for ( i = 0; i < 4; i++ ) {
  7199. normalIndex = faces[ offset ++ ] * 3;
  7200. normal = new THREE.Vector3(
  7201. normals[ normalIndex ++ ],
  7202. normals[ normalIndex ++ ],
  7203. normals[ normalIndex ]
  7204. );
  7205. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7206. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7207. }
  7208. }
  7209. if ( hasFaceColor ) {
  7210. colorIndex = faces[ offset ++ ];
  7211. hex = colors[ colorIndex ];
  7212. faceA.color.setHex( hex );
  7213. faceB.color.setHex( hex );
  7214. }
  7215. if ( hasFaceVertexColor ) {
  7216. for ( i = 0; i < 4; i++ ) {
  7217. colorIndex = faces[ offset ++ ];
  7218. hex = colors[ colorIndex ];
  7219. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7220. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7221. }
  7222. }
  7223. geometry.faces.push( faceA );
  7224. geometry.faces.push( faceB );
  7225. } else {
  7226. face = new THREE.Face3();
  7227. face.a = faces[ offset ++ ];
  7228. face.b = faces[ offset ++ ];
  7229. face.c = faces[ offset ++ ];
  7230. if ( hasMaterial ) {
  7231. materialIndex = faces[ offset ++ ];
  7232. face.materialIndex = materialIndex;
  7233. }
  7234. // to get face <=> uv index correspondence
  7235. fi = geometry.faces.length;
  7236. if ( hasFaceVertexUv ) {
  7237. for ( i = 0; i < nUvLayers; i++ ) {
  7238. uvLayer = json.uvs[ i ];
  7239. geometry.faceVertexUvs[ i ][ fi ] = [];
  7240. for ( j = 0; j < 3; j ++ ) {
  7241. uvIndex = faces[ offset ++ ];
  7242. u = uvLayer[ uvIndex * 2 ];
  7243. v = uvLayer[ uvIndex * 2 + 1 ];
  7244. uv = new THREE.Vector2( u, v );
  7245. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7246. }
  7247. }
  7248. }
  7249. if ( hasFaceNormal ) {
  7250. normalIndex = faces[ offset ++ ] * 3;
  7251. face.normal.set(
  7252. normals[ normalIndex ++ ],
  7253. normals[ normalIndex ++ ],
  7254. normals[ normalIndex ]
  7255. );
  7256. }
  7257. if ( hasFaceVertexNormal ) {
  7258. for ( i = 0; i < 3; i++ ) {
  7259. normalIndex = faces[ offset ++ ] * 3;
  7260. normal = new THREE.Vector3(
  7261. normals[ normalIndex ++ ],
  7262. normals[ normalIndex ++ ],
  7263. normals[ normalIndex ]
  7264. );
  7265. face.vertexNormals.push( normal );
  7266. }
  7267. }
  7268. if ( hasFaceColor ) {
  7269. colorIndex = faces[ offset ++ ];
  7270. face.color.setHex( colors[ colorIndex ] );
  7271. }
  7272. if ( hasFaceVertexColor ) {
  7273. for ( i = 0; i < 3; i++ ) {
  7274. colorIndex = faces[ offset ++ ];
  7275. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7276. }
  7277. }
  7278. geometry.faces.push( face );
  7279. }
  7280. }
  7281. };
  7282. function parseSkin() {
  7283. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7284. if ( json.skinWeights ) {
  7285. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7286. var x = json.skinWeights[ i ];
  7287. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7288. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7289. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7290. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7291. }
  7292. }
  7293. if ( json.skinIndices ) {
  7294. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7295. var a = json.skinIndices[ i ];
  7296. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7297. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7298. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7299. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7300. }
  7301. }
  7302. geometry.bones = json.bones;
  7303. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7304. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7305. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7306. }
  7307. // could change this to json.animations[0] or remove completely
  7308. geometry.animation = json.animation;
  7309. geometry.animations = json.animations;
  7310. };
  7311. function parseMorphing( scale ) {
  7312. if ( json.morphTargets !== undefined ) {
  7313. var i, l, v, vl, dstVertices, srcVertices;
  7314. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7315. geometry.morphTargets[ i ] = {};
  7316. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7317. geometry.morphTargets[ i ].vertices = [];
  7318. dstVertices = geometry.morphTargets[ i ].vertices;
  7319. srcVertices = json.morphTargets [ i ].vertices;
  7320. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7321. var vertex = new THREE.Vector3();
  7322. vertex.x = srcVertices[ v ] * scale;
  7323. vertex.y = srcVertices[ v + 1 ] * scale;
  7324. vertex.z = srcVertices[ v + 2 ] * scale;
  7325. dstVertices.push( vertex );
  7326. }
  7327. }
  7328. }
  7329. if ( json.morphColors !== undefined ) {
  7330. var i, l, c, cl, dstColors, srcColors, color;
  7331. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7332. geometry.morphColors[ i ] = {};
  7333. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7334. geometry.morphColors[ i ].colors = [];
  7335. dstColors = geometry.morphColors[ i ].colors;
  7336. srcColors = json.morphColors [ i ].colors;
  7337. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7338. color = new THREE.Color( 0xffaa00 );
  7339. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7340. dstColors.push( color );
  7341. }
  7342. }
  7343. }
  7344. };
  7345. if ( json.materials === undefined || json.materials.length === 0 ) {
  7346. return { geometry: geometry };
  7347. } else {
  7348. var materials = this.initMaterials( json.materials, texturePath );
  7349. if ( this.needsTangents( materials ) ) {
  7350. geometry.computeTangents();
  7351. }
  7352. return { geometry: geometry, materials: materials };
  7353. }
  7354. };
  7355. /**
  7356. * @author mrdoob / http://mrdoob.com/
  7357. */
  7358. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7359. var scope = this;
  7360. var loaded = 0, total = 0;
  7361. this.onLoad = onLoad;
  7362. this.onProgress = onProgress;
  7363. this.onError = onError;
  7364. this.itemStart = function ( url ) {
  7365. total ++;
  7366. };
  7367. this.itemEnd = function ( url ) {
  7368. loaded ++;
  7369. if ( scope.onProgress !== undefined ) {
  7370. scope.onProgress( url, loaded, total );
  7371. }
  7372. if ( loaded === total && scope.onLoad !== undefined ) {
  7373. scope.onLoad();
  7374. }
  7375. };
  7376. };
  7377. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7378. /**
  7379. * @author mrdoob / http://mrdoob.com/
  7380. */
  7381. THREE.BufferGeometryLoader = function ( manager ) {
  7382. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7383. };
  7384. THREE.BufferGeometryLoader.prototype = {
  7385. constructor: THREE.BufferGeometryLoader,
  7386. load: function ( url, onLoad, onProgress, onError ) {
  7387. var scope = this;
  7388. var loader = new THREE.XHRLoader();
  7389. loader.setCrossOrigin( this.crossOrigin );
  7390. loader.load( url, function ( text ) {
  7391. onLoad( scope.parse( JSON.parse( text ) ) );
  7392. } );
  7393. },
  7394. setCrossOrigin: function ( value ) {
  7395. this.crossOrigin = value;
  7396. },
  7397. parse: function ( json ) {
  7398. var geometry = new THREE.BufferGeometry();
  7399. var attributes = json.attributes;
  7400. var offsets = json.offsets;
  7401. var boundingSphere = json.boundingSphere;
  7402. for ( var key in attributes ) {
  7403. var attribute = attributes[ key ];
  7404. geometry.attributes[ key ] = {
  7405. itemSize: attribute.itemSize,
  7406. array: new self[ attribute.type ]( attribute.array )
  7407. }
  7408. }
  7409. if ( offsets !== undefined ) {
  7410. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7411. }
  7412. if ( boundingSphere !== undefined ) {
  7413. geometry.boundingSphere = new THREE.Sphere(
  7414. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7415. boundingSphere.radius
  7416. );
  7417. }
  7418. return geometry;
  7419. }
  7420. };
  7421. /**
  7422. * @author mrdoob / http://mrdoob.com/
  7423. */
  7424. THREE.MaterialLoader = function ( manager ) {
  7425. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7426. };
  7427. THREE.MaterialLoader.prototype = {
  7428. constructor: THREE.MaterialLoader,
  7429. load: function ( url, onLoad, onProgress, onError ) {
  7430. var scope = this;
  7431. var loader = new THREE.XHRLoader();
  7432. loader.setCrossOrigin( this.crossOrigin );
  7433. loader.load( url, function ( text ) {
  7434. onLoad( scope.parse( JSON.parse( text ) ) );
  7435. } );
  7436. },
  7437. setCrossOrigin: function ( value ) {
  7438. this.crossOrigin = value;
  7439. },
  7440. parse: function ( json ) {
  7441. var material = new THREE[ json.type ];
  7442. if ( json.color !== undefined ) material.color.setHex( json.color );
  7443. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7444. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7445. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7446. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7447. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7448. if ( json.blending !== undefined ) material.blending = json.blending;
  7449. if ( json.side !== undefined ) material.side = json.side;
  7450. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7451. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7452. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7453. if ( json.materials !== undefined ) {
  7454. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7455. material.materials.push( this.parse( json.materials[ i ] ) );
  7456. }
  7457. }
  7458. return material;
  7459. }
  7460. };
  7461. /**
  7462. * @author mrdoob / http://mrdoob.com/
  7463. */
  7464. THREE.ObjectLoader = function ( manager ) {
  7465. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7466. };
  7467. THREE.ObjectLoader.prototype = {
  7468. constructor: THREE.ObjectLoader,
  7469. load: function ( url, onLoad, onProgress, onError ) {
  7470. var scope = this;
  7471. var loader = new THREE.XHRLoader( scope.manager );
  7472. loader.setCrossOrigin( this.crossOrigin );
  7473. loader.load( url, function ( text ) {
  7474. onLoad( scope.parse( JSON.parse( text ) ) );
  7475. } );
  7476. },
  7477. setCrossOrigin: function ( value ) {
  7478. this.crossOrigin = value;
  7479. },
  7480. parse: function ( json ) {
  7481. var geometries = this.parseGeometries( json.geometries );
  7482. var materials = this.parseMaterials( json.materials );
  7483. var object = this.parseObject( json.object, geometries, materials );
  7484. return object;
  7485. },
  7486. parseGeometries: function ( json ) {
  7487. var geometries = {};
  7488. if ( json !== undefined ) {
  7489. var geometryLoader = new THREE.JSONLoader();
  7490. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7491. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7492. var geometry;
  7493. var data = json[ i ];
  7494. switch ( data.type ) {
  7495. case 'PlaneGeometry':
  7496. geometry = new THREE.PlaneGeometry(
  7497. data.width,
  7498. data.height,
  7499. data.widthSegments,
  7500. data.heightSegments
  7501. );
  7502. break;
  7503. case 'BoxGeometry':
  7504. case 'CubeGeometry': // DEPRECATED
  7505. geometry = new THREE.BoxGeometry(
  7506. data.width,
  7507. data.height,
  7508. data.depth,
  7509. data.widthSegments,
  7510. data.heightSegments,
  7511. data.depthSegments
  7512. );
  7513. break;
  7514. case 'CircleGeometry':
  7515. geometry = new THREE.CircleGeometry(
  7516. data.radius,
  7517. data.segments
  7518. );
  7519. break;
  7520. case 'CylinderGeometry':
  7521. geometry = new THREE.CylinderGeometry(
  7522. data.radiusTop,
  7523. data.radiusBottom,
  7524. data.height,
  7525. data.radialSegments,
  7526. data.heightSegments,
  7527. data.openEnded
  7528. );
  7529. break;
  7530. case 'SphereGeometry':
  7531. geometry = new THREE.SphereGeometry(
  7532. data.radius,
  7533. data.widthSegments,
  7534. data.heightSegments,
  7535. data.phiStart,
  7536. data.phiLength,
  7537. data.thetaStart,
  7538. data.thetaLength
  7539. );
  7540. break;
  7541. case 'IcosahedronGeometry':
  7542. geometry = new THREE.IcosahedronGeometry(
  7543. data.radius,
  7544. data.detail
  7545. );
  7546. break;
  7547. case 'TorusGeometry':
  7548. geometry = new THREE.TorusGeometry(
  7549. data.radius,
  7550. data.tube,
  7551. data.radialSegments,
  7552. data.tubularSegments,
  7553. data.arc
  7554. );
  7555. break;
  7556. case 'TorusKnotGeometry':
  7557. geometry = new THREE.TorusKnotGeometry(
  7558. data.radius,
  7559. data.tube,
  7560. data.radialSegments,
  7561. data.tubularSegments,
  7562. data.p,
  7563. data.q,
  7564. data.heightScale
  7565. );
  7566. break;
  7567. case 'BufferGeometry':
  7568. geometry = bufferGeometryLoader.parse( data.data );
  7569. break;
  7570. case 'Geometry':
  7571. geometry = geometryLoader.parse( data.data ).geometry;
  7572. break;
  7573. }
  7574. geometry.uuid = data.uuid;
  7575. if ( data.name !== undefined ) geometry.name = data.name;
  7576. geometries[ data.uuid ] = geometry;
  7577. }
  7578. }
  7579. return geometries;
  7580. },
  7581. parseMaterials: function ( json ) {
  7582. var materials = {};
  7583. if ( json !== undefined ) {
  7584. var loader = new THREE.MaterialLoader();
  7585. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7586. var data = json[ i ];
  7587. var material = loader.parse( data );
  7588. material.uuid = data.uuid;
  7589. if ( data.name !== undefined ) material.name = data.name;
  7590. materials[ data.uuid ] = material;
  7591. }
  7592. }
  7593. return materials;
  7594. },
  7595. parseObject: function () {
  7596. var matrix = new THREE.Matrix4();
  7597. return function ( data, geometries, materials ) {
  7598. var object;
  7599. switch ( data.type ) {
  7600. case 'Scene':
  7601. object = new THREE.Scene();
  7602. break;
  7603. case 'PerspectiveCamera':
  7604. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7605. break;
  7606. case 'OrthographicCamera':
  7607. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7608. break;
  7609. case 'AmbientLight':
  7610. object = new THREE.AmbientLight( data.color );
  7611. break;
  7612. case 'DirectionalLight':
  7613. object = new THREE.DirectionalLight( data.color, data.intensity );
  7614. break;
  7615. case 'PointLight':
  7616. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7617. break;
  7618. case 'SpotLight':
  7619. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7620. break;
  7621. case 'HemisphereLight':
  7622. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7623. break;
  7624. case 'Mesh':
  7625. var geometry = geometries[ data.geometry ];
  7626. var material = materials[ data.material ];
  7627. if ( geometry === undefined ) {
  7628. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7629. }
  7630. if ( material === undefined ) {
  7631. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7632. }
  7633. object = new THREE.Mesh( geometry, material );
  7634. break;
  7635. case 'Sprite':
  7636. var material = materials[ data.material ];
  7637. if ( material === undefined ) {
  7638. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7639. }
  7640. object = new THREE.Sprite( material );
  7641. break;
  7642. default:
  7643. object = new THREE.Object3D();
  7644. }
  7645. object.uuid = data.uuid;
  7646. if ( data.name !== undefined ) object.name = data.name;
  7647. if ( data.matrix !== undefined ) {
  7648. matrix.fromArray( data.matrix );
  7649. matrix.decompose( object.position, object.quaternion, object.scale );
  7650. } else {
  7651. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7652. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7653. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7654. }
  7655. if ( data.visible !== undefined ) object.visible = data.visible;
  7656. if ( data.userData !== undefined ) object.userData = data.userData;
  7657. if ( data.children !== undefined ) {
  7658. for ( var child in data.children ) {
  7659. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7660. }
  7661. }
  7662. return object;
  7663. }
  7664. }()
  7665. };
  7666. /**
  7667. * @author mrdoob / http://mrdoob.com/
  7668. */
  7669. THREE.TextureLoader = function ( manager ) {
  7670. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7671. };
  7672. THREE.TextureLoader.prototype = {
  7673. constructor: THREE.TextureLoader,
  7674. load: function ( url, onLoad, onProgress, onError ) {
  7675. var scope = this;
  7676. var loader = new THREE.ImageLoader( scope.manager );
  7677. loader.setCrossOrigin( this.crossOrigin );
  7678. loader.load( url, function ( image ) {
  7679. var texture = new THREE.Texture( image );
  7680. texture.needsUpdate = true;
  7681. if ( onLoad !== undefined ) {
  7682. onLoad( texture );
  7683. }
  7684. } );
  7685. },
  7686. setCrossOrigin: function ( value ) {
  7687. this.crossOrigin = value;
  7688. }
  7689. };
  7690. /**
  7691. * @author mrdoob / http://mrdoob.com/
  7692. * @author alteredq / http://alteredqualia.com/
  7693. */
  7694. THREE.Material = function () {
  7695. this.id = THREE.MaterialIdCount ++;
  7696. this.uuid = THREE.Math.generateUUID();
  7697. this.name = '';
  7698. this.side = THREE.FrontSide;
  7699. this.opacity = 1;
  7700. this.transparent = false;
  7701. this.blending = THREE.NormalBlending;
  7702. this.blendSrc = THREE.SrcAlphaFactor;
  7703. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7704. this.blendEquation = THREE.AddEquation;
  7705. this.depthTest = true;
  7706. this.depthWrite = true;
  7707. this.polygonOffset = false;
  7708. this.polygonOffsetFactor = 0;
  7709. this.polygonOffsetUnits = 0;
  7710. this.alphaTest = 0;
  7711. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7712. this.visible = true;
  7713. this.needsUpdate = true;
  7714. };
  7715. THREE.Material.prototype = {
  7716. constructor: THREE.Material,
  7717. setValues: function ( values ) {
  7718. if ( values === undefined ) return;
  7719. for ( var key in values ) {
  7720. var newValue = values[ key ];
  7721. if ( newValue === undefined ) {
  7722. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7723. continue;
  7724. }
  7725. if ( key in this ) {
  7726. var currentValue = this[ key ];
  7727. if ( currentValue instanceof THREE.Color ) {
  7728. currentValue.set( newValue );
  7729. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7730. currentValue.copy( newValue );
  7731. } else if ( key == 'overdraw') {
  7732. // ensure overdraw is backwards-compatable with legacy boolean type
  7733. this[ key ] = Number(newValue);
  7734. } else {
  7735. this[ key ] = newValue;
  7736. }
  7737. }
  7738. }
  7739. },
  7740. clone: function ( material ) {
  7741. if ( material === undefined ) material = new THREE.Material();
  7742. material.name = this.name;
  7743. material.side = this.side;
  7744. material.opacity = this.opacity;
  7745. material.transparent = this.transparent;
  7746. material.blending = this.blending;
  7747. material.blendSrc = this.blendSrc;
  7748. material.blendDst = this.blendDst;
  7749. material.blendEquation = this.blendEquation;
  7750. material.depthTest = this.depthTest;
  7751. material.depthWrite = this.depthWrite;
  7752. material.polygonOffset = this.polygonOffset;
  7753. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7754. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7755. material.alphaTest = this.alphaTest;
  7756. material.overdraw = this.overdraw;
  7757. material.visible = this.visible;
  7758. return material;
  7759. },
  7760. dispose: function () {
  7761. this.dispatchEvent( { type: 'dispose' } );
  7762. }
  7763. };
  7764. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7765. THREE.MaterialIdCount = 0;
  7766. /**
  7767. * @author mrdoob / http://mrdoob.com/
  7768. * @author alteredq / http://alteredqualia.com/
  7769. *
  7770. * parameters = {
  7771. * color: <hex>,
  7772. * opacity: <float>,
  7773. *
  7774. * blending: THREE.NormalBlending,
  7775. * depthTest: <bool>,
  7776. * depthWrite: <bool>,
  7777. *
  7778. * linewidth: <float>,
  7779. * linecap: "round",
  7780. * linejoin: "round",
  7781. *
  7782. * vertexColors: <bool>
  7783. *
  7784. * fog: <bool>
  7785. * }
  7786. */
  7787. THREE.LineBasicMaterial = function ( parameters ) {
  7788. THREE.Material.call( this );
  7789. this.color = new THREE.Color( 0xffffff );
  7790. this.linewidth = 1;
  7791. this.linecap = 'round';
  7792. this.linejoin = 'round';
  7793. this.vertexColors = false;
  7794. this.fog = true;
  7795. this.setValues( parameters );
  7796. };
  7797. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7798. THREE.LineBasicMaterial.prototype.clone = function () {
  7799. var material = new THREE.LineBasicMaterial();
  7800. THREE.Material.prototype.clone.call( this, material );
  7801. material.color.copy( this.color );
  7802. material.linewidth = this.linewidth;
  7803. material.linecap = this.linecap;
  7804. material.linejoin = this.linejoin;
  7805. material.vertexColors = this.vertexColors;
  7806. material.fog = this.fog;
  7807. return material;
  7808. };
  7809. /**
  7810. * @author alteredq / http://alteredqualia.com/
  7811. *
  7812. * parameters = {
  7813. * color: <hex>,
  7814. * opacity: <float>,
  7815. *
  7816. * blending: THREE.NormalBlending,
  7817. * depthTest: <bool>,
  7818. * depthWrite: <bool>,
  7819. *
  7820. * linewidth: <float>,
  7821. *
  7822. * scale: <float>,
  7823. * dashSize: <float>,
  7824. * gapSize: <float>,
  7825. *
  7826. * vertexColors: <bool>
  7827. *
  7828. * fog: <bool>
  7829. * }
  7830. */
  7831. THREE.LineDashedMaterial = function ( parameters ) {
  7832. THREE.Material.call( this );
  7833. this.color = new THREE.Color( 0xffffff );
  7834. this.linewidth = 1;
  7835. this.scale = 1;
  7836. this.dashSize = 3;
  7837. this.gapSize = 1;
  7838. this.vertexColors = false;
  7839. this.fog = true;
  7840. this.setValues( parameters );
  7841. };
  7842. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7843. THREE.LineDashedMaterial.prototype.clone = function () {
  7844. var material = new THREE.LineDashedMaterial();
  7845. THREE.Material.prototype.clone.call( this, material );
  7846. material.color.copy( this.color );
  7847. material.linewidth = this.linewidth;
  7848. material.scale = this.scale;
  7849. material.dashSize = this.dashSize;
  7850. material.gapSize = this.gapSize;
  7851. material.vertexColors = this.vertexColors;
  7852. material.fog = this.fog;
  7853. return material;
  7854. };
  7855. /**
  7856. * @author mrdoob / http://mrdoob.com/
  7857. * @author alteredq / http://alteredqualia.com/
  7858. *
  7859. * parameters = {
  7860. * color: <hex>,
  7861. * opacity: <float>,
  7862. * map: new THREE.Texture( <Image> ),
  7863. *
  7864. * lightMap: new THREE.Texture( <Image> ),
  7865. *
  7866. * specularMap: new THREE.Texture( <Image> ),
  7867. *
  7868. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7869. * combine: THREE.Multiply,
  7870. * reflectivity: <float>,
  7871. * refractionRatio: <float>,
  7872. *
  7873. * shading: THREE.SmoothShading,
  7874. * blending: THREE.NormalBlending,
  7875. * depthTest: <bool>,
  7876. * depthWrite: <bool>,
  7877. *
  7878. * wireframe: <boolean>,
  7879. * wireframeLinewidth: <float>,
  7880. *
  7881. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7882. *
  7883. * skinning: <bool>,
  7884. * morphTargets: <bool>,
  7885. *
  7886. * fog: <bool>
  7887. * }
  7888. */
  7889. THREE.MeshBasicMaterial = function ( parameters ) {
  7890. THREE.Material.call( this );
  7891. this.color = new THREE.Color( 0xffffff ); // emissive
  7892. this.map = null;
  7893. this.lightMap = null;
  7894. this.specularMap = null;
  7895. this.envMap = null;
  7896. this.combine = THREE.MultiplyOperation;
  7897. this.reflectivity = 1;
  7898. this.refractionRatio = 0.98;
  7899. this.fog = true;
  7900. this.shading = THREE.SmoothShading;
  7901. this.wireframe = false;
  7902. this.wireframeLinewidth = 1;
  7903. this.wireframeLinecap = 'round';
  7904. this.wireframeLinejoin = 'round';
  7905. this.vertexColors = THREE.NoColors;
  7906. this.skinning = false;
  7907. this.morphTargets = false;
  7908. this.setValues( parameters );
  7909. };
  7910. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7911. THREE.MeshBasicMaterial.prototype.clone = function () {
  7912. var material = new THREE.MeshBasicMaterial();
  7913. THREE.Material.prototype.clone.call( this, material );
  7914. material.color.copy( this.color );
  7915. material.map = this.map;
  7916. material.lightMap = this.lightMap;
  7917. material.specularMap = this.specularMap;
  7918. material.envMap = this.envMap;
  7919. material.combine = this.combine;
  7920. material.reflectivity = this.reflectivity;
  7921. material.refractionRatio = this.refractionRatio;
  7922. material.fog = this.fog;
  7923. material.shading = this.shading;
  7924. material.wireframe = this.wireframe;
  7925. material.wireframeLinewidth = this.wireframeLinewidth;
  7926. material.wireframeLinecap = this.wireframeLinecap;
  7927. material.wireframeLinejoin = this.wireframeLinejoin;
  7928. material.vertexColors = this.vertexColors;
  7929. material.skinning = this.skinning;
  7930. material.morphTargets = this.morphTargets;
  7931. return material;
  7932. };
  7933. /**
  7934. * @author mrdoob / http://mrdoob.com/
  7935. * @author alteredq / http://alteredqualia.com/
  7936. *
  7937. * parameters = {
  7938. * color: <hex>,
  7939. * ambient: <hex>,
  7940. * emissive: <hex>,
  7941. * opacity: <float>,
  7942. *
  7943. * map: new THREE.Texture( <Image> ),
  7944. *
  7945. * lightMap: new THREE.Texture( <Image> ),
  7946. *
  7947. * specularMap: new THREE.Texture( <Image> ),
  7948. *
  7949. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7950. * combine: THREE.Multiply,
  7951. * reflectivity: <float>,
  7952. * refractionRatio: <float>,
  7953. *
  7954. * shading: THREE.SmoothShading,
  7955. * blending: THREE.NormalBlending,
  7956. * depthTest: <bool>,
  7957. * depthWrite: <bool>,
  7958. *
  7959. * wireframe: <boolean>,
  7960. * wireframeLinewidth: <float>,
  7961. *
  7962. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7963. *
  7964. * skinning: <bool>,
  7965. * morphTargets: <bool>,
  7966. * morphNormals: <bool>,
  7967. *
  7968. * fog: <bool>
  7969. * }
  7970. */
  7971. THREE.MeshLambertMaterial = function ( parameters ) {
  7972. THREE.Material.call( this );
  7973. this.color = new THREE.Color( 0xffffff ); // diffuse
  7974. this.ambient = new THREE.Color( 0xffffff );
  7975. this.emissive = new THREE.Color( 0x000000 );
  7976. this.wrapAround = false;
  7977. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7978. this.map = null;
  7979. this.lightMap = null;
  7980. this.specularMap = null;
  7981. this.envMap = null;
  7982. this.combine = THREE.MultiplyOperation;
  7983. this.reflectivity = 1;
  7984. this.refractionRatio = 0.98;
  7985. this.fog = true;
  7986. this.shading = THREE.SmoothShading;
  7987. this.wireframe = false;
  7988. this.wireframeLinewidth = 1;
  7989. this.wireframeLinecap = 'round';
  7990. this.wireframeLinejoin = 'round';
  7991. this.vertexColors = THREE.NoColors;
  7992. this.skinning = false;
  7993. this.morphTargets = false;
  7994. this.morphNormals = false;
  7995. this.setValues( parameters );
  7996. };
  7997. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7998. THREE.MeshLambertMaterial.prototype.clone = function () {
  7999. var material = new THREE.MeshLambertMaterial();
  8000. THREE.Material.prototype.clone.call( this, material );
  8001. material.color.copy( this.color );
  8002. material.ambient.copy( this.ambient );
  8003. material.emissive.copy( this.emissive );
  8004. material.wrapAround = this.wrapAround;
  8005. material.wrapRGB.copy( this.wrapRGB );
  8006. material.map = this.map;
  8007. material.lightMap = this.lightMap;
  8008. material.specularMap = this.specularMap;
  8009. material.envMap = this.envMap;
  8010. material.combine = this.combine;
  8011. material.reflectivity = this.reflectivity;
  8012. material.refractionRatio = this.refractionRatio;
  8013. material.fog = this.fog;
  8014. material.shading = this.shading;
  8015. material.wireframe = this.wireframe;
  8016. material.wireframeLinewidth = this.wireframeLinewidth;
  8017. material.wireframeLinecap = this.wireframeLinecap;
  8018. material.wireframeLinejoin = this.wireframeLinejoin;
  8019. material.vertexColors = this.vertexColors;
  8020. material.skinning = this.skinning;
  8021. material.morphTargets = this.morphTargets;
  8022. material.morphNormals = this.morphNormals;
  8023. return material;
  8024. };
  8025. /**
  8026. * @author mrdoob / http://mrdoob.com/
  8027. * @author alteredq / http://alteredqualia.com/
  8028. *
  8029. * parameters = {
  8030. * color: <hex>,
  8031. * ambient: <hex>,
  8032. * emissive: <hex>,
  8033. * specular: <hex>,
  8034. * shininess: <float>,
  8035. * opacity: <float>,
  8036. *
  8037. * map: new THREE.Texture( <Image> ),
  8038. *
  8039. * lightMap: new THREE.Texture( <Image> ),
  8040. *
  8041. * bumpMap: new THREE.Texture( <Image> ),
  8042. * bumpScale: <float>,
  8043. *
  8044. * normalMap: new THREE.Texture( <Image> ),
  8045. * normalScale: <Vector2>,
  8046. *
  8047. * specularMap: new THREE.Texture( <Image> ),
  8048. *
  8049. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8050. * combine: THREE.Multiply,
  8051. * reflectivity: <float>,
  8052. * refractionRatio: <float>,
  8053. *
  8054. * shading: THREE.SmoothShading,
  8055. * blending: THREE.NormalBlending,
  8056. * depthTest: <bool>,
  8057. * depthWrite: <bool>,
  8058. *
  8059. * wireframe: <boolean>,
  8060. * wireframeLinewidth: <float>,
  8061. *
  8062. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8063. *
  8064. * skinning: <bool>,
  8065. * morphTargets: <bool>,
  8066. * morphNormals: <bool>,
  8067. *
  8068. * fog: <bool>
  8069. * }
  8070. */
  8071. THREE.MeshPhongMaterial = function ( parameters ) {
  8072. THREE.Material.call( this );
  8073. this.color = new THREE.Color( 0xffffff ); // diffuse
  8074. this.ambient = new THREE.Color( 0xffffff );
  8075. this.emissive = new THREE.Color( 0x000000 );
  8076. this.specular = new THREE.Color( 0x111111 );
  8077. this.shininess = 30;
  8078. this.metal = false;
  8079. this.wrapAround = false;
  8080. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8081. this.map = null;
  8082. this.lightMap = null;
  8083. this.bumpMap = null;
  8084. this.bumpScale = 1;
  8085. this.normalMap = null;
  8086. this.normalScale = new THREE.Vector2( 1, 1 );
  8087. this.specularMap = null;
  8088. this.envMap = null;
  8089. this.combine = THREE.MultiplyOperation;
  8090. this.reflectivity = 1;
  8091. this.refractionRatio = 0.98;
  8092. this.fog = true;
  8093. this.shading = THREE.SmoothShading;
  8094. this.wireframe = false;
  8095. this.wireframeLinewidth = 1;
  8096. this.wireframeLinecap = 'round';
  8097. this.wireframeLinejoin = 'round';
  8098. this.vertexColors = THREE.NoColors;
  8099. this.skinning = false;
  8100. this.morphTargets = false;
  8101. this.morphNormals = false;
  8102. this.setValues( parameters );
  8103. };
  8104. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8105. THREE.MeshPhongMaterial.prototype.clone = function () {
  8106. var material = new THREE.MeshPhongMaterial();
  8107. THREE.Material.prototype.clone.call( this, material );
  8108. material.color.copy( this.color );
  8109. material.ambient.copy( this.ambient );
  8110. material.emissive.copy( this.emissive );
  8111. material.specular.copy( this.specular );
  8112. material.shininess = this.shininess;
  8113. material.metal = this.metal;
  8114. material.wrapAround = this.wrapAround;
  8115. material.wrapRGB.copy( this.wrapRGB );
  8116. material.map = this.map;
  8117. material.lightMap = this.lightMap;
  8118. material.bumpMap = this.bumpMap;
  8119. material.bumpScale = this.bumpScale;
  8120. material.normalMap = this.normalMap;
  8121. material.normalScale.copy( this.normalScale );
  8122. material.specularMap = this.specularMap;
  8123. material.envMap = this.envMap;
  8124. material.combine = this.combine;
  8125. material.reflectivity = this.reflectivity;
  8126. material.refractionRatio = this.refractionRatio;
  8127. material.fog = this.fog;
  8128. material.shading = this.shading;
  8129. material.wireframe = this.wireframe;
  8130. material.wireframeLinewidth = this.wireframeLinewidth;
  8131. material.wireframeLinecap = this.wireframeLinecap;
  8132. material.wireframeLinejoin = this.wireframeLinejoin;
  8133. material.vertexColors = this.vertexColors;
  8134. material.skinning = this.skinning;
  8135. material.morphTargets = this.morphTargets;
  8136. material.morphNormals = this.morphNormals;
  8137. return material;
  8138. };
  8139. /**
  8140. * @author mrdoob / http://mrdoob.com/
  8141. * @author alteredq / http://alteredqualia.com/
  8142. *
  8143. * parameters = {
  8144. * opacity: <float>,
  8145. *
  8146. * blending: THREE.NormalBlending,
  8147. * depthTest: <bool>,
  8148. * depthWrite: <bool>,
  8149. *
  8150. * wireframe: <boolean>,
  8151. * wireframeLinewidth: <float>
  8152. * }
  8153. */
  8154. THREE.MeshDepthMaterial = function ( parameters ) {
  8155. THREE.Material.call( this );
  8156. this.morphTargets = false;
  8157. this.wireframe = false;
  8158. this.wireframeLinewidth = 1;
  8159. this.setValues( parameters );
  8160. };
  8161. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8162. THREE.MeshDepthMaterial.prototype.clone = function () {
  8163. var material = new THREE.MeshDepthMaterial();
  8164. THREE.Material.prototype.clone.call( this, material );
  8165. material.wireframe = this.wireframe;
  8166. material.wireframeLinewidth = this.wireframeLinewidth;
  8167. return material;
  8168. };
  8169. /**
  8170. * @author mrdoob / http://mrdoob.com/
  8171. *
  8172. * parameters = {
  8173. * opacity: <float>,
  8174. *
  8175. * shading: THREE.FlatShading,
  8176. * blending: THREE.NormalBlending,
  8177. * depthTest: <bool>,
  8178. * depthWrite: <bool>,
  8179. *
  8180. * wireframe: <boolean>,
  8181. * wireframeLinewidth: <float>
  8182. * }
  8183. */
  8184. THREE.MeshNormalMaterial = function ( parameters ) {
  8185. THREE.Material.call( this, parameters );
  8186. this.shading = THREE.FlatShading;
  8187. this.wireframe = false;
  8188. this.wireframeLinewidth = 1;
  8189. this.morphTargets = false;
  8190. this.setValues( parameters );
  8191. };
  8192. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8193. THREE.MeshNormalMaterial.prototype.clone = function () {
  8194. var material = new THREE.MeshNormalMaterial();
  8195. THREE.Material.prototype.clone.call( this, material );
  8196. material.shading = this.shading;
  8197. material.wireframe = this.wireframe;
  8198. material.wireframeLinewidth = this.wireframeLinewidth;
  8199. return material;
  8200. };
  8201. /**
  8202. * @author mrdoob / http://mrdoob.com/
  8203. */
  8204. THREE.MeshFaceMaterial = function ( materials ) {
  8205. this.materials = materials instanceof Array ? materials : [];
  8206. };
  8207. THREE.MeshFaceMaterial.prototype.clone = function () {
  8208. var material = new THREE.MeshFaceMaterial();
  8209. for ( var i = 0; i < this.materials.length; i ++ ) {
  8210. material.materials.push( this.materials[ i ].clone() );
  8211. }
  8212. return material;
  8213. };
  8214. /**
  8215. * @author mrdoob / http://mrdoob.com/
  8216. * @author alteredq / http://alteredqualia.com/
  8217. *
  8218. * parameters = {
  8219. * color: <hex>,
  8220. * opacity: <float>,
  8221. * map: new THREE.Texture( <Image> ),
  8222. *
  8223. * size: <float>,
  8224. *
  8225. * blending: THREE.NormalBlending,
  8226. * depthTest: <bool>,
  8227. * depthWrite: <bool>,
  8228. *
  8229. * vertexColors: <bool>,
  8230. *
  8231. * fog: <bool>
  8232. * }
  8233. */
  8234. THREE.PointCloudMaterial = function ( parameters ) {
  8235. THREE.Material.call( this );
  8236. this.color = new THREE.Color( 0xffffff );
  8237. this.map = null;
  8238. this.size = 1;
  8239. this.sizeAttenuation = true;
  8240. this.vertexColors = false;
  8241. this.fog = true;
  8242. this.setValues( parameters );
  8243. };
  8244. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8245. THREE.PointCloudMaterial.prototype.clone = function () {
  8246. var material = new THREE.PointCloudMaterial();
  8247. THREE.Material.prototype.clone.call( this, material );
  8248. material.color.copy( this.color );
  8249. material.map = this.map;
  8250. material.size = this.size;
  8251. material.sizeAttenuation = this.sizeAttenuation;
  8252. material.vertexColors = this.vertexColors;
  8253. material.fog = this.fog;
  8254. return material;
  8255. };
  8256. // backwards compatibility
  8257. THREE.ParticleSystemMaterial = function ( parameters ) {
  8258. console.warn( 'THREE.ParticleSystemMaterial has been DEPRECATED. Use THREE.PointCloudMaterial instead.' );
  8259. return new THREE.PointCloudMaterial( parameters );
  8260. }
  8261. /**
  8262. * @author alteredq / http://alteredqualia.com/
  8263. *
  8264. * parameters = {
  8265. * fragmentShader: <string>,
  8266. * vertexShader: <string>,
  8267. *
  8268. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8269. *
  8270. * defines: { "label" : "value" },
  8271. *
  8272. * shading: THREE.SmoothShading,
  8273. * blending: THREE.NormalBlending,
  8274. * depthTest: <bool>,
  8275. * depthWrite: <bool>,
  8276. *
  8277. * wireframe: <boolean>,
  8278. * wireframeLinewidth: <float>,
  8279. *
  8280. * lights: <bool>,
  8281. *
  8282. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8283. *
  8284. * skinning: <bool>,
  8285. * morphTargets: <bool>,
  8286. * morphNormals: <bool>,
  8287. *
  8288. * fog: <bool>
  8289. * }
  8290. */
  8291. THREE.ShaderMaterial = function ( parameters ) {
  8292. THREE.Material.call( this );
  8293. this.fragmentShader = "void main() {}";
  8294. this.vertexShader = "void main() {}";
  8295. this.uniforms = {};
  8296. this.defines = {};
  8297. this.attributes = null;
  8298. this.shading = THREE.SmoothShading;
  8299. this.linewidth = 1;
  8300. this.wireframe = false;
  8301. this.wireframeLinewidth = 1;
  8302. this.fog = false; // set to use scene fog
  8303. this.lights = false; // set to use scene lights
  8304. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8305. this.skinning = false; // set to use skinning attribute streams
  8306. this.morphTargets = false; // set to use morph targets
  8307. this.morphNormals = false; // set to use morph normals
  8308. // When rendered geometry doesn't include these attributes but the material does,
  8309. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8310. this.defaultAttributeValues = {
  8311. "color" : [ 1, 1, 1 ],
  8312. "uv" : [ 0, 0 ],
  8313. "uv2" : [ 0, 0 ]
  8314. };
  8315. this.index0AttributeName = undefined;
  8316. this.setValues( parameters );
  8317. };
  8318. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8319. THREE.ShaderMaterial.prototype.clone = function () {
  8320. var material = new THREE.ShaderMaterial();
  8321. THREE.Material.prototype.clone.call( this, material );
  8322. material.fragmentShader = this.fragmentShader;
  8323. material.vertexShader = this.vertexShader;
  8324. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8325. material.attributes = this.attributes;
  8326. material.defines = this.defines;
  8327. material.shading = this.shading;
  8328. material.wireframe = this.wireframe;
  8329. material.wireframeLinewidth = this.wireframeLinewidth;
  8330. material.fog = this.fog;
  8331. material.lights = this.lights;
  8332. material.vertexColors = this.vertexColors;
  8333. material.skinning = this.skinning;
  8334. material.morphTargets = this.morphTargets;
  8335. material.morphNormals = this.morphNormals;
  8336. return material;
  8337. };
  8338. /**
  8339. * @author mrdoob / http://mrdoob.com/
  8340. */
  8341. THREE.RawShaderMaterial = function ( parameters ) {
  8342. THREE.ShaderMaterial.call( this, parameters );
  8343. };
  8344. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8345. THREE.RawShaderMaterial.prototype.clone = function () {
  8346. var material = new THREE.RawShaderMaterial();
  8347. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8348. return material;
  8349. };
  8350. /**
  8351. * @author alteredq / http://alteredqualia.com/
  8352. *
  8353. * parameters = {
  8354. * color: <hex>,
  8355. * opacity: <float>,
  8356. * map: new THREE.Texture( <Image> ),
  8357. *
  8358. * blending: THREE.NormalBlending,
  8359. * depthTest: <bool>,
  8360. * depthWrite: <bool>,
  8361. *
  8362. * uvOffset: new THREE.Vector2(),
  8363. * uvScale: new THREE.Vector2(),
  8364. *
  8365. * fog: <bool>
  8366. * }
  8367. */
  8368. THREE.SpriteMaterial = function ( parameters ) {
  8369. THREE.Material.call( this );
  8370. // defaults
  8371. this.color = new THREE.Color( 0xffffff );
  8372. this.map = null;
  8373. this.rotation = 0;
  8374. this.fog = false;
  8375. // set parameters
  8376. this.setValues( parameters );
  8377. };
  8378. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8379. THREE.SpriteMaterial.prototype.clone = function () {
  8380. var material = new THREE.SpriteMaterial();
  8381. THREE.Material.prototype.clone.call( this, material );
  8382. material.color.copy( this.color );
  8383. material.map = this.map;
  8384. material.rotation = this.rotation;
  8385. material.fog = this.fog;
  8386. return material;
  8387. };
  8388. /**
  8389. * @author mrdoob / http://mrdoob.com/
  8390. *
  8391. * parameters = {
  8392. * color: <hex>,
  8393. * program: <function>,
  8394. * opacity: <float>,
  8395. * blending: THREE.NormalBlending
  8396. * }
  8397. */
  8398. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8399. THREE.Material.call( this );
  8400. this.color = new THREE.Color( 0xffffff );
  8401. this.program = function ( context, color ) {};
  8402. this.setValues( parameters );
  8403. };
  8404. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8405. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8406. var material = new THREE.SpriteCanvasMaterial();
  8407. THREE.Material.prototype.clone.call( this, material );
  8408. material.color.copy( this.color );
  8409. material.program = this.program;
  8410. return material;
  8411. };
  8412. // backwards compatibility
  8413. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8414. /**
  8415. * @author mrdoob / http://mrdoob.com/
  8416. * @author alteredq / http://alteredqualia.com/
  8417. * @author szimek / https://github.com/szimek/
  8418. */
  8419. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8420. this.id = THREE.TextureIdCount ++;
  8421. this.uuid = THREE.Math.generateUUID();
  8422. this.name = '';
  8423. this.image = image;
  8424. this.mipmaps = [];
  8425. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8426. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8427. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8428. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8429. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8430. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8431. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8432. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8433. this.offset = new THREE.Vector2( 0, 0 );
  8434. this.repeat = new THREE.Vector2( 1, 1 );
  8435. this.generateMipmaps = true;
  8436. this.premultiplyAlpha = false;
  8437. this.flipY = true;
  8438. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8439. this._needsUpdate = false;
  8440. this.onUpdate = null;
  8441. };
  8442. THREE.Texture.prototype = {
  8443. constructor: THREE.Texture,
  8444. get needsUpdate () {
  8445. return this._needsUpdate;
  8446. },
  8447. set needsUpdate ( value ) {
  8448. if ( value === true ) this.update();
  8449. this._needsUpdate = value;
  8450. },
  8451. clone: function ( texture ) {
  8452. if ( texture === undefined ) texture = new THREE.Texture();
  8453. texture.image = this.image;
  8454. texture.mipmaps = this.mipmaps.slice(0);
  8455. texture.mapping = this.mapping;
  8456. texture.wrapS = this.wrapS;
  8457. texture.wrapT = this.wrapT;
  8458. texture.magFilter = this.magFilter;
  8459. texture.minFilter = this.minFilter;
  8460. texture.anisotropy = this.anisotropy;
  8461. texture.format = this.format;
  8462. texture.type = this.type;
  8463. texture.offset.copy( this.offset );
  8464. texture.repeat.copy( this.repeat );
  8465. texture.generateMipmaps = this.generateMipmaps;
  8466. texture.premultiplyAlpha = this.premultiplyAlpha;
  8467. texture.flipY = this.flipY;
  8468. texture.unpackAlignment = this.unpackAlignment;
  8469. return texture;
  8470. },
  8471. update: function () {
  8472. this.dispatchEvent( { type: 'update' } );
  8473. },
  8474. dispose: function () {
  8475. this.dispatchEvent( { type: 'dispose' } );
  8476. }
  8477. };
  8478. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8479. THREE.TextureIdCount = 0;
  8480. /**
  8481. * @author alteredq / http://alteredqualia.com/
  8482. */
  8483. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8484. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8485. this.image = { width: width, height: height };
  8486. this.mipmaps = mipmaps;
  8487. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8488. };
  8489. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8490. THREE.CompressedTexture.prototype.clone = function () {
  8491. var texture = new THREE.CompressedTexture();
  8492. THREE.Texture.prototype.clone.call( this, texture );
  8493. return texture;
  8494. };
  8495. /**
  8496. * @author alteredq / http://alteredqualia.com/
  8497. */
  8498. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8499. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8500. this.image = { data: data, width: width, height: height };
  8501. };
  8502. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8503. THREE.DataTexture.prototype.clone = function () {
  8504. var texture = new THREE.DataTexture();
  8505. THREE.Texture.prototype.clone.call( this, texture );
  8506. return texture;
  8507. };
  8508. /**
  8509. * @author alteredq / http://alteredqualia.com/
  8510. */
  8511. THREE.PointCloud = 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.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8515. this.sortParticles = false;
  8516. };
  8517. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8518. THREE.PointCloud.prototype.clone = function ( object ) {
  8519. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8520. object.sortParticles = this.sortParticles;
  8521. THREE.Object3D.prototype.clone.call( this, object );
  8522. return object;
  8523. };
  8524. // Backwards compatibility
  8525. THREE.ParticleSystem = function ( geometry, material ) {
  8526. console.warn( 'THREE.ParticleSystem has been DEPRECATED. Use THREE.PointCloud instead.' );
  8527. return new THREE.PointCloud( geometry, material );
  8528. };
  8529. /**
  8530. * @author mrdoob / http://mrdoob.com/
  8531. */
  8532. THREE.Line = function ( geometry, material, type ) {
  8533. THREE.Object3D.call( this );
  8534. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8535. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8536. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8537. };
  8538. THREE.LineStrip = 0;
  8539. THREE.LinePieces = 1;
  8540. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8541. THREE.Line.prototype.clone = function ( object ) {
  8542. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8543. THREE.Object3D.prototype.clone.call( this, object );
  8544. return object;
  8545. };
  8546. /**
  8547. * @author mrdoob / http://mrdoob.com/
  8548. * @author alteredq / http://alteredqualia.com/
  8549. * @author mikael emtinger / http://gomo.se/
  8550. * @author jonobr1 / http://jonobr1.com/
  8551. */
  8552. THREE.Mesh = function ( geometry, material ) {
  8553. THREE.Object3D.call( this );
  8554. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8555. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8556. this.updateMorphTargets();
  8557. };
  8558. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8559. THREE.Mesh.prototype.updateMorphTargets = function () {
  8560. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8561. this.morphTargetBase = -1;
  8562. this.morphTargetForcedOrder = [];
  8563. this.morphTargetInfluences = [];
  8564. this.morphTargetDictionary = {};
  8565. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8566. this.morphTargetInfluences.push( 0 );
  8567. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8568. }
  8569. }
  8570. };
  8571. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8572. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8573. return this.morphTargetDictionary[ name ];
  8574. }
  8575. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8576. return 0;
  8577. };
  8578. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  8579. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8580. THREE.Object3D.prototype.clone.call( this, object, recursive );
  8581. return object;
  8582. };
  8583. /**
  8584. * @author mikael emtinger / http://gomo.se/
  8585. * @author alteredq / http://alteredqualia.com/
  8586. */
  8587. THREE.Bone = function( belongsToSkin ) {
  8588. THREE.Object3D.call( this );
  8589. this.skin = belongsToSkin;
  8590. this.skinMatrix = new THREE.Matrix4();
  8591. this.accumulatedRotWeight = 0;
  8592. this.accumulatedPosWeight = 0;
  8593. this.accumulatedSclWeight = 0;
  8594. };
  8595. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8596. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8597. // update local
  8598. if ( this.matrixAutoUpdate ) {
  8599. forceUpdate |= this.updateMatrix();
  8600. }
  8601. // update skin matrix
  8602. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8603. if ( parentSkinMatrix ) {
  8604. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8605. } else {
  8606. this.skinMatrix.copy( this.matrix );
  8607. }
  8608. this.matrixWorldNeedsUpdate = false;
  8609. forceUpdate = true;
  8610. // Reset weights to be re-accumulated in the next frame
  8611. this.accumulatedRotWeight = 0;
  8612. this.accumulatedPosWeight = 0;
  8613. this.accumulatedSclWeight = 0;
  8614. }
  8615. // update children
  8616. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8617. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8618. }
  8619. };
  8620. /**
  8621. * @author mikael emtinger / http://gomo.se/
  8622. * @author alteredq / http://alteredqualia.com/
  8623. * @author michael guerrero / http://realitymeltdown.com
  8624. */
  8625. THREE.Skeleton = function ( boneList, useVertexTexture ) {
  8626. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8627. // init bones
  8628. this.bones = [];
  8629. this.boneMatrices = [];
  8630. var bone, gbone, p, q, s;
  8631. if ( boneList !== undefined ) {
  8632. for ( var b = 0; b < boneList.length; ++b ) {
  8633. gbone = boneList[ b ];
  8634. p = gbone.pos;
  8635. q = gbone.rotq;
  8636. s = gbone.scl;
  8637. bone = this.addBone();
  8638. bone.name = gbone.name;
  8639. bone.position.set( p[0], p[1], p[2] );
  8640. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8641. if ( s !== undefined ) {
  8642. bone.scale.set( s[0], s[1], s[2] );
  8643. } else {
  8644. bone.scale.set( 1, 1, 1 );
  8645. }
  8646. }
  8647. for ( var b = 0; b < boneList.length; ++b ) {
  8648. gbone = boneList[ b ];
  8649. if ( gbone.parent !== -1 ) {
  8650. this.bones[ gbone.parent ].add( this.bones[ b ] );
  8651. }
  8652. }
  8653. //
  8654. var nBones = this.bones.length;
  8655. if ( this.useVertexTexture ) {
  8656. // layout (1 matrix = 4 pixels)
  8657. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8658. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8659. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8660. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8661. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8662. var size;
  8663. if ( nBones > 256 )
  8664. size = 64;
  8665. else if ( nBones > 64 )
  8666. size = 32;
  8667. else if ( nBones > 16 )
  8668. size = 16;
  8669. else
  8670. size = 8;
  8671. this.boneTextureWidth = size;
  8672. this.boneTextureHeight = size;
  8673. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8674. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8675. this.boneTexture.minFilter = THREE.NearestFilter;
  8676. this.boneTexture.magFilter = THREE.NearestFilter;
  8677. this.boneTexture.generateMipmaps = false;
  8678. this.boneTexture.flipY = false;
  8679. } else {
  8680. this.boneMatrices = new Float32Array( 16 * nBones );
  8681. }
  8682. }
  8683. };
  8684. THREE.Skeleton.prototype = Object.create( THREE.Mesh.prototype );
  8685. THREE.Skeleton.prototype.addBone = function( bone ) {
  8686. if ( bone === undefined ) {
  8687. bone = new THREE.Bone( this );
  8688. }
  8689. this.bones.push( bone );
  8690. return bone;
  8691. };
  8692. THREE.Skeleton.prototype.calculateInverses = function( bone ) {
  8693. this.boneInverses = [];
  8694. for ( var b = 0, bl = this.bones.length; b < bl; ++b ) {
  8695. var inverse = new THREE.Matrix4();
  8696. inverse.getInverse( this.bones[ b ].skinMatrix );
  8697. this.boneInverses.push( inverse );
  8698. }
  8699. };
  8700. /**
  8701. * @author mikael emtinger / http://gomo.se/
  8702. * @author alteredq / http://alteredqualia.com/
  8703. */
  8704. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8705. THREE.Mesh.call( this, geometry, material );
  8706. this.skeleton = new THREE.Skeleton( this.geometry && this.geometry.bones, useVertexTexture );
  8707. // Add root level bones as children of the mesh
  8708. for ( var b = 0; b < this.skeleton.bones.length; ++b ) {
  8709. var bone = this.skeleton.bones[ b ];
  8710. if ( bone.parent === undefined ) {
  8711. this.add( bone );
  8712. }
  8713. }
  8714. this.identityMatrix = new THREE.Matrix4();
  8715. this.pose();
  8716. };
  8717. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8718. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8719. var offsetMatrix = new THREE.Matrix4();
  8720. return function ( force ) {
  8721. this.matrixAutoUpdate && this.updateMatrix();
  8722. // update matrixWorld
  8723. if ( this.matrixWorldNeedsUpdate || force ) {
  8724. if ( this.parent ) {
  8725. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8726. } else {
  8727. this.matrixWorld.copy( this.matrix );
  8728. }
  8729. this.matrixWorldNeedsUpdate = false;
  8730. force = true;
  8731. }
  8732. // update children
  8733. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8734. var child = this.children[ i ];
  8735. if ( child instanceof THREE.Bone ) {
  8736. child.update( this.identityMatrix, false );
  8737. } else {
  8738. child.updateMatrixWorld( true );
  8739. }
  8740. }
  8741. // make a snapshot of the bones' rest position
  8742. if ( this.skeleton.boneInverses === undefined ) {
  8743. this.skeleton.calculateInverses();
  8744. }
  8745. // flatten bone matrices to array
  8746. for ( var b = 0, bl = this.skeleton.bones.length; b < bl; b ++ ) {
  8747. // compute the offset between the current and the original transform;
  8748. // TODO: we could get rid of this multiplication step if the skinMatrix
  8749. // was already representing the offset; however, this requires some
  8750. // major changes to the animation system
  8751. offsetMatrix.multiplyMatrices( this.skeleton.bones[ b ].skinMatrix, this.skeleton.boneInverses[ b ] );
  8752. offsetMatrix.flattenToArrayOffset( this.skeleton.boneMatrices, b * 16 );
  8753. }
  8754. if ( this.skeleton.useVertexTexture ) {
  8755. this.skeleton.boneTexture.needsUpdate = true;
  8756. }
  8757. };
  8758. }();
  8759. THREE.SkinnedMesh.prototype.pose = function () {
  8760. this.updateMatrixWorld( true );
  8761. this.normalizeSkinWeights();
  8762. };
  8763. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8764. if ( this.geometry instanceof THREE.Geometry ) {
  8765. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8766. var sw = this.geometry.skinWeights[ i ];
  8767. var scale = 1.0 / sw.lengthManhattan();
  8768. if ( scale !== Infinity ) {
  8769. sw.multiplyScalar( scale );
  8770. } else {
  8771. sw.set( 1 ); // this will be normalized by the shader anyway
  8772. }
  8773. }
  8774. } else {
  8775. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8776. }
  8777. };
  8778. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8779. if ( object === undefined ) {
  8780. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8781. }
  8782. THREE.Mesh.prototype.clone.call( this, object );
  8783. return object;
  8784. };
  8785. /**
  8786. * @author alteredq / http://alteredqualia.com/
  8787. */
  8788. THREE.MorphAnimMesh = function ( geometry, material ) {
  8789. THREE.Mesh.call( this, geometry, material );
  8790. // API
  8791. this.duration = 1000; // milliseconds
  8792. this.mirroredLoop = false;
  8793. this.time = 0;
  8794. // internals
  8795. this.lastKeyframe = 0;
  8796. this.currentKeyframe = 0;
  8797. this.direction = 1;
  8798. this.directionBackwards = false;
  8799. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8800. };
  8801. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8802. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8803. this.startKeyframe = start;
  8804. this.endKeyframe = end;
  8805. this.length = this.endKeyframe - this.startKeyframe + 1;
  8806. };
  8807. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8808. this.direction = 1;
  8809. this.directionBackwards = false;
  8810. };
  8811. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8812. this.direction = -1;
  8813. this.directionBackwards = true;
  8814. };
  8815. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8816. var geometry = this.geometry;
  8817. if ( ! geometry.animations ) geometry.animations = {};
  8818. var firstAnimation, animations = geometry.animations;
  8819. var pattern = /([a-z]+)(\d+)/;
  8820. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8821. var morph = geometry.morphTargets[ i ];
  8822. var parts = morph.name.match( pattern );
  8823. if ( parts && parts.length > 1 ) {
  8824. var label = parts[ 1 ];
  8825. var num = parts[ 2 ];
  8826. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8827. var animation = animations[ label ];
  8828. if ( i < animation.start ) animation.start = i;
  8829. if ( i > animation.end ) animation.end = i;
  8830. if ( ! firstAnimation ) firstAnimation = label;
  8831. }
  8832. }
  8833. geometry.firstAnimation = firstAnimation;
  8834. };
  8835. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8836. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8837. this.geometry.animations[ label ] = { start: start, end: end };
  8838. };
  8839. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8840. var animation = this.geometry.animations[ label ];
  8841. if ( animation ) {
  8842. this.setFrameRange( animation.start, animation.end );
  8843. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8844. this.time = 0;
  8845. } else {
  8846. console.warn( "animation[" + label + "] undefined" );
  8847. }
  8848. };
  8849. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8850. var frameTime = this.duration / this.length;
  8851. this.time += this.direction * delta;
  8852. if ( this.mirroredLoop ) {
  8853. if ( this.time > this.duration || this.time < 0 ) {
  8854. this.direction *= -1;
  8855. if ( this.time > this.duration ) {
  8856. this.time = this.duration;
  8857. this.directionBackwards = true;
  8858. }
  8859. if ( this.time < 0 ) {
  8860. this.time = 0;
  8861. this.directionBackwards = false;
  8862. }
  8863. }
  8864. } else {
  8865. this.time = this.time % this.duration;
  8866. if ( this.time < 0 ) this.time += this.duration;
  8867. }
  8868. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8869. if ( keyframe !== this.currentKeyframe ) {
  8870. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8871. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8872. this.morphTargetInfluences[ keyframe ] = 0;
  8873. this.lastKeyframe = this.currentKeyframe;
  8874. this.currentKeyframe = keyframe;
  8875. }
  8876. var mix = ( this.time % frameTime ) / frameTime;
  8877. if ( this.directionBackwards ) {
  8878. mix = 1 - mix;
  8879. }
  8880. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8881. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8882. };
  8883. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8884. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8885. object.duration = this.duration;
  8886. object.mirroredLoop = this.mirroredLoop;
  8887. object.time = this.time;
  8888. object.lastKeyframe = this.lastKeyframe;
  8889. object.currentKeyframe = this.currentKeyframe;
  8890. object.direction = this.direction;
  8891. object.directionBackwards = this.directionBackwards;
  8892. THREE.Mesh.prototype.clone.call( this, object );
  8893. return object;
  8894. };
  8895. /**
  8896. * @author mikael emtinger / http://gomo.se/
  8897. * @author alteredq / http://alteredqualia.com/
  8898. * @author mrdoob / http://mrdoob.com/
  8899. */
  8900. THREE.LOD = function () {
  8901. THREE.Object3D.call( this );
  8902. this.objects = [];
  8903. };
  8904. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8905. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8906. if ( distance === undefined ) distance = 0;
  8907. distance = Math.abs( distance );
  8908. for ( var l = 0; l < this.objects.length; l ++ ) {
  8909. if ( distance < this.objects[ l ].distance ) {
  8910. break;
  8911. }
  8912. }
  8913. this.objects.splice( l, 0, { distance: distance, object: object } );
  8914. this.add( object );
  8915. };
  8916. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8917. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8918. if ( distance < this.objects[ i ].distance ) {
  8919. break;
  8920. }
  8921. }
  8922. return this.objects[ i - 1 ].object;
  8923. };
  8924. THREE.LOD.prototype.update = function () {
  8925. var v1 = new THREE.Vector3();
  8926. var v2 = new THREE.Vector3();
  8927. return function ( camera ) {
  8928. if ( this.objects.length > 1 ) {
  8929. v1.setFromMatrixPosition( camera.matrixWorld );
  8930. v2.setFromMatrixPosition( this.matrixWorld );
  8931. var distance = v1.distanceTo( v2 );
  8932. this.objects[ 0 ].object.visible = true;
  8933. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8934. if ( distance >= this.objects[ i ].distance ) {
  8935. this.objects[ i - 1 ].object.visible = false;
  8936. this.objects[ i ].object.visible = true;
  8937. } else {
  8938. break;
  8939. }
  8940. }
  8941. for( ; i < l; i ++ ) {
  8942. this.objects[ i ].object.visible = false;
  8943. }
  8944. }
  8945. };
  8946. }();
  8947. THREE.LOD.prototype.clone = function ( object ) {
  8948. if ( object === undefined ) object = new THREE.LOD();
  8949. THREE.Object3D.prototype.clone.call( this, object );
  8950. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  8951. var x = this.objects[i].object.clone();
  8952. x.visible = i === 0;
  8953. object.addLevel( x, this.objects[i].distance );
  8954. }
  8955. return object;
  8956. };
  8957. /**
  8958. * @author mikael emtinger / http://gomo.se/
  8959. * @author alteredq / http://alteredqualia.com/
  8960. */
  8961. THREE.Sprite = ( function () {
  8962. var vertices = new THREE.Float32Attribute( 3 * 3, 3 );
  8963. vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  8964. var geometry = new THREE.BufferGeometry();
  8965. geometry.addAttribute( 'position', vertices );
  8966. return function ( material ) {
  8967. THREE.Object3D.call( this );
  8968. this.geometry = geometry;
  8969. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8970. };
  8971. } )();
  8972. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8973. /*
  8974. * Custom update matrix
  8975. */
  8976. THREE.Sprite.prototype.updateMatrix = function () {
  8977. this.matrix.compose( this.position, this.quaternion, this.scale );
  8978. this.matrixWorldNeedsUpdate = true;
  8979. };
  8980. THREE.Sprite.prototype.clone = function ( object ) {
  8981. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8982. THREE.Object3D.prototype.clone.call( this, object );
  8983. return object;
  8984. };
  8985. // Backwards compatibility
  8986. THREE.Particle = THREE.Sprite;
  8987. /**
  8988. * @author mrdoob / http://mrdoob.com/
  8989. */
  8990. THREE.Scene = function () {
  8991. THREE.Object3D.call( this );
  8992. this.fog = null;
  8993. this.overrideMaterial = null;
  8994. this.autoUpdate = true; // checked by the renderer
  8995. this.matrixAutoUpdate = false;
  8996. this.__lights = [];
  8997. this.__objectsAdded = [];
  8998. this.__objectsRemoved = [];
  8999. };
  9000. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9001. THREE.Scene.prototype.__addObject = function ( object ) {
  9002. if ( object instanceof THREE.Light ) {
  9003. if ( this.__lights.indexOf( object ) === - 1 ) {
  9004. this.__lights.push( object );
  9005. }
  9006. if ( object.target && object.target.parent === undefined ) {
  9007. this.add( object.target );
  9008. }
  9009. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9010. this.__objectsAdded.push( object );
  9011. // check if previously removed
  9012. var i = this.__objectsRemoved.indexOf( object );
  9013. if ( i !== -1 ) {
  9014. this.__objectsRemoved.splice( i, 1 );
  9015. }
  9016. }
  9017. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9018. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9019. for ( var c = 0; c < object.children.length; c ++ ) {
  9020. this.__addObject( object.children[ c ] );
  9021. }
  9022. };
  9023. THREE.Scene.prototype.__removeObject = function ( object ) {
  9024. if ( object instanceof THREE.Light ) {
  9025. var i = this.__lights.indexOf( object );
  9026. if ( i !== -1 ) {
  9027. this.__lights.splice( i, 1 );
  9028. }
  9029. if ( object.shadowCascadeArray ) {
  9030. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9031. this.__removeObject( object.shadowCascadeArray[ x ] );
  9032. }
  9033. }
  9034. } else if ( !( object instanceof THREE.Camera ) ) {
  9035. this.__objectsRemoved.push( object );
  9036. // check if previously added
  9037. var i = this.__objectsAdded.indexOf( object );
  9038. if ( i !== -1 ) {
  9039. this.__objectsAdded.splice( i, 1 );
  9040. }
  9041. }
  9042. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9043. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9044. for ( var c = 0; c < object.children.length; c ++ ) {
  9045. this.__removeObject( object.children[ c ] );
  9046. }
  9047. };
  9048. THREE.Scene.prototype.clone = function ( object ) {
  9049. if ( object === undefined ) object = new THREE.Scene();
  9050. THREE.Object3D.prototype.clone.call(this, object);
  9051. if ( this.fog !== null ) object.fog = this.fog.clone();
  9052. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9053. object.autoUpdate = this.autoUpdate;
  9054. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9055. return object;
  9056. };
  9057. /**
  9058. * @author mrdoob / http://mrdoob.com/
  9059. * @author alteredq / http://alteredqualia.com/
  9060. */
  9061. THREE.Fog = function ( color, near, far ) {
  9062. this.name = '';
  9063. this.color = new THREE.Color( color );
  9064. this.near = ( near !== undefined ) ? near : 1;
  9065. this.far = ( far !== undefined ) ? far : 1000;
  9066. };
  9067. THREE.Fog.prototype.clone = function () {
  9068. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9069. };
  9070. /**
  9071. * @author mrdoob / http://mrdoob.com/
  9072. * @author alteredq / http://alteredqualia.com/
  9073. */
  9074. THREE.FogExp2 = function ( color, density ) {
  9075. this.name = '';
  9076. this.color = new THREE.Color( color );
  9077. this.density = ( density !== undefined ) ? density : 0.00025;
  9078. };
  9079. THREE.FogExp2.prototype.clone = function () {
  9080. return new THREE.FogExp2( this.color.getHex(), this.density );
  9081. };
  9082. /**
  9083. * @author mrdoob / http://mrdoob.com/
  9084. */
  9085. THREE.CanvasRenderer = function ( parameters ) {
  9086. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9087. var smoothstep = THREE.Math.smoothstep;
  9088. parameters = parameters || {};
  9089. var _this = this,
  9090. _renderData, _elements, _lights,
  9091. _projector = new THREE.Projector(),
  9092. _canvas = parameters.canvas !== undefined
  9093. ? parameters.canvas
  9094. : document.createElement( 'canvas' ),
  9095. _canvasWidth = _canvas.width,
  9096. _canvasHeight = _canvas.height,
  9097. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9098. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9099. _context = _canvas.getContext( '2d', {
  9100. alpha: parameters.alpha === true
  9101. } ),
  9102. _clearColor = new THREE.Color( 0x000000 ),
  9103. _clearAlpha = 0,
  9104. _contextGlobalAlpha = 1,
  9105. _contextGlobalCompositeOperation = 0,
  9106. _contextStrokeStyle = null,
  9107. _contextFillStyle = null,
  9108. _contextLineWidth = null,
  9109. _contextLineCap = null,
  9110. _contextLineJoin = null,
  9111. _contextDashSize = null,
  9112. _contextGapSize = 0,
  9113. _camera,
  9114. _v1, _v2, _v3, _v4,
  9115. _v5 = new THREE.RenderableVertex(),
  9116. _v6 = new THREE.RenderableVertex(),
  9117. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9118. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9119. _color = new THREE.Color(),
  9120. _color1 = new THREE.Color(),
  9121. _color2 = new THREE.Color(),
  9122. _color3 = new THREE.Color(),
  9123. _color4 = new THREE.Color(),
  9124. _diffuseColor = new THREE.Color(),
  9125. _emissiveColor = new THREE.Color(),
  9126. _lightColor = new THREE.Color(),
  9127. _patterns = {},
  9128. _image, _uvs,
  9129. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9130. _clipBox = new THREE.Box2(),
  9131. _clearBox = new THREE.Box2(),
  9132. _elemBox = new THREE.Box2(),
  9133. _ambientLight = new THREE.Color(),
  9134. _directionalLights = new THREE.Color(),
  9135. _pointLights = new THREE.Color(),
  9136. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9137. _centroid = new THREE.Vector3(),
  9138. _normal = new THREE.Vector3(),
  9139. _normalViewMatrix = new THREE.Matrix3();
  9140. // dash+gap fallbacks for Firefox and everything else
  9141. if ( _context.setLineDash === undefined ) {
  9142. _context.setLineDash = function () {}
  9143. }
  9144. this.domElement = _canvas;
  9145. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9146. ? parameters.devicePixelRatio
  9147. : self.devicePixelRatio !== undefined
  9148. ? self.devicePixelRatio
  9149. : 1;
  9150. this.autoClear = true;
  9151. this.sortObjects = true;
  9152. this.sortElements = true;
  9153. this.info = {
  9154. render: {
  9155. vertices: 0,
  9156. faces: 0
  9157. }
  9158. }
  9159. // WebGLRenderer compatibility
  9160. this.supportsVertexTextures = function () {};
  9161. this.setFaceCulling = function () {};
  9162. this.setSize = function ( width, height, updateStyle ) {
  9163. _canvasWidth = width * this.devicePixelRatio;
  9164. _canvasHeight = height * this.devicePixelRatio;
  9165. _canvas.width = _canvasWidth;
  9166. _canvas.height = _canvasHeight;
  9167. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9168. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9169. if ( updateStyle !== false ) {
  9170. _canvas.style.width = width + 'px';
  9171. _canvas.style.height = height + 'px';
  9172. }
  9173. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9174. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9175. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9176. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9177. _contextGlobalAlpha = 1;
  9178. _contextGlobalCompositeOperation = 0;
  9179. _contextStrokeStyle = null;
  9180. _contextFillStyle = null;
  9181. _contextLineWidth = null;
  9182. _contextLineCap = null;
  9183. _contextLineJoin = null;
  9184. this.setViewport( 0, 0, width, height );
  9185. };
  9186. this.setViewport = function ( x, y, width, height ) {
  9187. var viewportX = x * this.devicePixelRatio;
  9188. var viewportY = y * this.devicePixelRatio;
  9189. var viewportWidth = width * this.devicePixelRatio;
  9190. var viewportHeight = height * this.devicePixelRatio;
  9191. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  9192. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9193. };
  9194. this.setScissor = function () {};
  9195. this.enableScissorTest = function () {};
  9196. this.setClearColor = function ( color, alpha ) {
  9197. _clearColor.set( color );
  9198. _clearAlpha = alpha !== undefined ? alpha : 1;
  9199. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9200. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9201. };
  9202. this.setClearColorHex = function ( hex, alpha ) {
  9203. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9204. this.setClearColor( hex, alpha );
  9205. };
  9206. this.getMaxAnisotropy = function () {
  9207. return 0;
  9208. };
  9209. this.clear = function () {
  9210. if ( _clearBox.empty() === false ) {
  9211. _clearBox.intersect( _clipBox );
  9212. _clearBox.expandByScalar( 2 );
  9213. if ( _clearAlpha < 1 ) {
  9214. _context.clearRect(
  9215. _clearBox.min.x | 0,
  9216. _clearBox.min.y | 0,
  9217. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9218. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9219. );
  9220. }
  9221. if ( _clearAlpha > 0 ) {
  9222. setBlending( THREE.NormalBlending );
  9223. setOpacity( 1 );
  9224. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9225. _context.fillRect(
  9226. _clearBox.min.x | 0,
  9227. _clearBox.min.y | 0,
  9228. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9229. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9230. );
  9231. }
  9232. _clearBox.makeEmpty();
  9233. }
  9234. };
  9235. // compatibility
  9236. this.clearColor = function () {};
  9237. this.clearDepth = function () {};
  9238. this.clearStencil = function () {};
  9239. this.render = function ( scene, camera ) {
  9240. if ( camera instanceof THREE.Camera === false ) {
  9241. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9242. return;
  9243. }
  9244. if ( this.autoClear === true ) this.clear();
  9245. _this.info.render.vertices = 0;
  9246. _this.info.render.faces = 0;
  9247. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9248. _elements = _renderData.elements;
  9249. _lights = _renderData.lights;
  9250. _camera = camera;
  9251. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9252. /* DEBUG
  9253. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9254. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9255. */
  9256. calculateLights();
  9257. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9258. var element = _elements[ e ];
  9259. var material = element.material;
  9260. if ( material === undefined || material.opacity === 0 ) continue;
  9261. _elemBox.makeEmpty();
  9262. if ( element instanceof THREE.RenderableSprite ) {
  9263. _v1 = element;
  9264. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9265. renderSprite( _v1, element, material );
  9266. } else if ( element instanceof THREE.RenderableLine ) {
  9267. _v1 = element.v1; _v2 = element.v2;
  9268. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9269. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9270. _elemBox.setFromPoints( [
  9271. _v1.positionScreen,
  9272. _v2.positionScreen
  9273. ] );
  9274. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9275. renderLine( _v1, _v2, element, material );
  9276. }
  9277. } else if ( element instanceof THREE.RenderableFace ) {
  9278. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9279. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9280. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9281. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9282. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9283. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9284. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9285. if ( material.overdraw > 0 ) {
  9286. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9287. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9288. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9289. }
  9290. _elemBox.setFromPoints( [
  9291. _v1.positionScreen,
  9292. _v2.positionScreen,
  9293. _v3.positionScreen
  9294. ] );
  9295. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9296. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9297. }
  9298. }
  9299. /* DEBUG
  9300. setLineWidth( 1 );
  9301. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9302. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9303. */
  9304. _clearBox.union( _elemBox );
  9305. }
  9306. /* DEBUG
  9307. setLineWidth( 1 );
  9308. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9309. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9310. */
  9311. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9312. };
  9313. //
  9314. function calculateLights() {
  9315. _ambientLight.setRGB( 0, 0, 0 );
  9316. _directionalLights.setRGB( 0, 0, 0 );
  9317. _pointLights.setRGB( 0, 0, 0 );
  9318. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9319. var light = _lights[ l ];
  9320. var lightColor = light.color;
  9321. if ( light instanceof THREE.AmbientLight ) {
  9322. _ambientLight.add( lightColor );
  9323. } else if ( light instanceof THREE.DirectionalLight ) {
  9324. // for sprites
  9325. _directionalLights.add( lightColor );
  9326. } else if ( light instanceof THREE.PointLight ) {
  9327. // for sprites
  9328. _pointLights.add( lightColor );
  9329. }
  9330. }
  9331. }
  9332. function calculateLight( position, normal, color ) {
  9333. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9334. var light = _lights[ l ];
  9335. _lightColor.copy( light.color );
  9336. if ( light instanceof THREE.DirectionalLight ) {
  9337. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9338. var amount = normal.dot( lightPosition );
  9339. if ( amount <= 0 ) continue;
  9340. amount *= light.intensity;
  9341. color.add( _lightColor.multiplyScalar( amount ) );
  9342. } else if ( light instanceof THREE.PointLight ) {
  9343. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9344. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9345. if ( amount <= 0 ) continue;
  9346. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9347. if ( amount == 0 ) continue;
  9348. amount *= light.intensity;
  9349. color.add( _lightColor.multiplyScalar( amount ) );
  9350. }
  9351. }
  9352. }
  9353. function renderSprite( v1, element, material ) {
  9354. setOpacity( material.opacity );
  9355. setBlending( material.blending );
  9356. var scaleX = element.scale.x * _canvasWidthHalf;
  9357. var scaleY = element.scale.y * _canvasHeightHalf;
  9358. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9359. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9360. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9361. if ( material instanceof THREE.SpriteMaterial ) {
  9362. var texture = material.map;
  9363. if ( texture !== null ) {
  9364. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9365. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9366. textureToPattern( texture );
  9367. }
  9368. texture.addEventListener( 'update', onTextureUpdate );
  9369. }
  9370. var pattern = _patterns[ texture.id ];
  9371. if ( pattern !== undefined ) {
  9372. setFillStyle( pattern );
  9373. } else {
  9374. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9375. }
  9376. //
  9377. var bitmap = texture.image;
  9378. var ox = bitmap.width * texture.offset.x;
  9379. var oy = bitmap.height * texture.offset.y;
  9380. var sx = bitmap.width * texture.repeat.x;
  9381. var sy = bitmap.height * texture.repeat.y;
  9382. var cx = scaleX / sx;
  9383. var cy = scaleY / sy;
  9384. _context.save();
  9385. _context.translate( v1.x, v1.y );
  9386. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9387. _context.translate( - scaleX / 2, - scaleY / 2 );
  9388. _context.scale( cx, cy );
  9389. _context.translate( - ox, - oy );
  9390. _context.fillRect( ox, oy, sx, sy );
  9391. _context.restore();
  9392. } else {
  9393. // no texture
  9394. setFillStyle( material.color.getStyle() );
  9395. _context.save();
  9396. _context.translate( v1.x, v1.y );
  9397. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9398. _context.scale( scaleX, - scaleY );
  9399. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9400. _context.restore();
  9401. }
  9402. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9403. setStrokeStyle( material.color.getStyle() );
  9404. setFillStyle( material.color.getStyle() );
  9405. _context.save();
  9406. _context.translate( v1.x, v1.y );
  9407. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9408. _context.scale( scaleX, scaleY );
  9409. material.program( _context );
  9410. _context.restore();
  9411. }
  9412. /* DEBUG
  9413. setStrokeStyle( 'rgb(255,255,0)' );
  9414. _context.beginPath();
  9415. _context.moveTo( v1.x - 10, v1.y );
  9416. _context.lineTo( v1.x + 10, v1.y );
  9417. _context.moveTo( v1.x, v1.y - 10 );
  9418. _context.lineTo( v1.x, v1.y + 10 );
  9419. _context.stroke();
  9420. */
  9421. }
  9422. function renderLine( v1, v2, element, material ) {
  9423. setOpacity( material.opacity );
  9424. setBlending( material.blending );
  9425. _context.beginPath();
  9426. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9427. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9428. if ( material instanceof THREE.LineBasicMaterial ) {
  9429. setLineWidth( material.linewidth );
  9430. setLineCap( material.linecap );
  9431. setLineJoin( material.linejoin );
  9432. if ( material.vertexColors !== THREE.VertexColors ) {
  9433. setStrokeStyle( material.color.getStyle() );
  9434. } else {
  9435. var colorStyle1 = element.vertexColors[0].getStyle();
  9436. var colorStyle2 = element.vertexColors[1].getStyle();
  9437. if ( colorStyle1 === colorStyle2 ) {
  9438. setStrokeStyle( colorStyle1 );
  9439. } else {
  9440. try {
  9441. var grad = _context.createLinearGradient(
  9442. v1.positionScreen.x,
  9443. v1.positionScreen.y,
  9444. v2.positionScreen.x,
  9445. v2.positionScreen.y
  9446. );
  9447. grad.addColorStop( 0, colorStyle1 );
  9448. grad.addColorStop( 1, colorStyle2 );
  9449. } catch ( exception ) {
  9450. grad = colorStyle1;
  9451. }
  9452. setStrokeStyle( grad );
  9453. }
  9454. }
  9455. _context.stroke();
  9456. _elemBox.expandByScalar( material.linewidth * 2 );
  9457. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9458. setLineWidth( material.linewidth );
  9459. setLineCap( material.linecap );
  9460. setLineJoin( material.linejoin );
  9461. setStrokeStyle( material.color.getStyle() );
  9462. setDashAndGap( material.dashSize, material.gapSize );
  9463. _context.stroke();
  9464. _elemBox.expandByScalar( material.linewidth * 2 );
  9465. setDashAndGap( null, null );
  9466. }
  9467. }
  9468. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9469. _this.info.render.vertices += 3;
  9470. _this.info.render.faces ++;
  9471. setOpacity( material.opacity );
  9472. setBlending( material.blending );
  9473. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9474. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9475. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9476. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9477. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9478. _diffuseColor.copy( material.color );
  9479. _emissiveColor.copy( material.emissive );
  9480. if ( material.vertexColors === THREE.FaceColors ) {
  9481. _diffuseColor.multiply( element.color );
  9482. }
  9483. _color.copy( _ambientLight );
  9484. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  9485. calculateLight( _centroid, element.normalModel, _color );
  9486. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9487. material.wireframe === true
  9488. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9489. : fillPath( _color );
  9490. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9491. if ( material.map !== null ) {
  9492. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9493. _uvs = element.uvs;
  9494. 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 );
  9495. }
  9496. } else if ( material.envMap !== null ) {
  9497. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9498. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9499. _uv1x = 0.5 * _normal.x + 0.5;
  9500. _uv1y = 0.5 * _normal.y + 0.5;
  9501. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9502. _uv2x = 0.5 * _normal.x + 0.5;
  9503. _uv2y = 0.5 * _normal.y + 0.5;
  9504. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9505. _uv3x = 0.5 * _normal.x + 0.5;
  9506. _uv3y = 0.5 * _normal.y + 0.5;
  9507. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9508. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  9509. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9510. _uv1x = - 0.5 * _normal.x + 0.5;
  9511. _uv1y = - 0.5 * _normal.y + 0.5;
  9512. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9513. _uv2x = - 0.5 * _normal.x + 0.5;
  9514. _uv2y = - 0.5 * _normal.y + 0.5;
  9515. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9516. _uv3x = - 0.5 * _normal.x + 0.5;
  9517. _uv3y = - 0.5 * _normal.y + 0.5;
  9518. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9519. }
  9520. } else {
  9521. _color.copy( material.color );
  9522. if ( material.vertexColors === THREE.FaceColors ) {
  9523. _color.multiply( element.color );
  9524. }
  9525. material.wireframe === true
  9526. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9527. : fillPath( _color );
  9528. }
  9529. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9530. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  9531. material.wireframe === true
  9532. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9533. : fillPath( _color );
  9534. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9535. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9536. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9537. material.wireframe === true
  9538. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9539. : fillPath( _color );
  9540. } else {
  9541. _color.setRGB( 1, 1, 1 );
  9542. material.wireframe === true
  9543. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9544. : fillPath( _color );
  9545. }
  9546. }
  9547. //
  9548. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9549. _context.beginPath();
  9550. _context.moveTo( x0, y0 );
  9551. _context.lineTo( x1, y1 );
  9552. _context.lineTo( x2, y2 );
  9553. _context.closePath();
  9554. }
  9555. function strokePath( color, linewidth, linecap, linejoin ) {
  9556. setLineWidth( linewidth );
  9557. setLineCap( linecap );
  9558. setLineJoin( linejoin );
  9559. setStrokeStyle( color.getStyle() );
  9560. _context.stroke();
  9561. _elemBox.expandByScalar( linewidth * 2 );
  9562. }
  9563. function fillPath( color ) {
  9564. setFillStyle( color.getStyle() );
  9565. _context.fill();
  9566. }
  9567. function onTextureUpdate ( event ) {
  9568. textureToPattern( event.target );
  9569. }
  9570. function textureToPattern( texture ) {
  9571. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9572. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9573. var image = texture.image;
  9574. var canvas = document.createElement( 'canvas' );
  9575. canvas.width = image.width;
  9576. canvas.height = image.height;
  9577. var context = canvas.getContext( '2d' );
  9578. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9579. context.drawImage( image, 0, 0 );
  9580. _patterns[ texture.id ] = _context.createPattern(
  9581. canvas, repeatX === true && repeatY === true
  9582. ? 'repeat'
  9583. : repeatX === true && repeatY === false
  9584. ? 'repeat-x'
  9585. : repeatX === false && repeatY === true
  9586. ? 'repeat-y'
  9587. : 'no-repeat'
  9588. );
  9589. }
  9590. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9591. if ( texture instanceof THREE.DataTexture ) return;
  9592. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9593. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9594. textureToPattern( texture );
  9595. }
  9596. texture.addEventListener( 'update', onTextureUpdate );
  9597. }
  9598. var pattern = _patterns[ texture.id ];
  9599. if ( pattern !== undefined ) {
  9600. setFillStyle( pattern );
  9601. } else {
  9602. setFillStyle( 'rgba(0,0,0,1)' );
  9603. _context.fill();
  9604. return;
  9605. }
  9606. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9607. var a, b, c, d, e, f, det, idet,
  9608. offsetX = texture.offset.x / texture.repeat.x,
  9609. offsetY = texture.offset.y / texture.repeat.y,
  9610. width = texture.image.width * texture.repeat.x,
  9611. height = texture.image.height * texture.repeat.y;
  9612. u0 = ( u0 + offsetX ) * width;
  9613. v0 = ( v0 + offsetY ) * height;
  9614. u1 = ( u1 + offsetX ) * width;
  9615. v1 = ( v1 + offsetY ) * height;
  9616. u2 = ( u2 + offsetX ) * width;
  9617. v2 = ( v2 + offsetY ) * height;
  9618. x1 -= x0; y1 -= y0;
  9619. x2 -= x0; y2 -= y0;
  9620. u1 -= u0; v1 -= v0;
  9621. u2 -= u0; v2 -= v0;
  9622. det = u1 * v2 - u2 * v1;
  9623. if ( det === 0 ) return;
  9624. idet = 1 / det;
  9625. a = ( v2 * x1 - v1 * x2 ) * idet;
  9626. b = ( v2 * y1 - v1 * y2 ) * idet;
  9627. c = ( u1 * x2 - u2 * x1 ) * idet;
  9628. d = ( u1 * y2 - u2 * y1 ) * idet;
  9629. e = x0 - a * u0 - c * v0;
  9630. f = y0 - b * u0 - d * v0;
  9631. _context.save();
  9632. _context.transform( a, b, c, d, e, f );
  9633. _context.fill();
  9634. _context.restore();
  9635. }
  9636. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9637. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9638. var a, b, c, d, e, f, det, idet,
  9639. width = image.width - 1,
  9640. height = image.height - 1;
  9641. u0 *= width; v0 *= height;
  9642. u1 *= width; v1 *= height;
  9643. u2 *= width; v2 *= height;
  9644. x1 -= x0; y1 -= y0;
  9645. x2 -= x0; y2 -= y0;
  9646. u1 -= u0; v1 -= v0;
  9647. u2 -= u0; v2 -= v0;
  9648. det = u1 * v2 - u2 * v1;
  9649. idet = 1 / det;
  9650. a = ( v2 * x1 - v1 * x2 ) * idet;
  9651. b = ( v2 * y1 - v1 * y2 ) * idet;
  9652. c = ( u1 * x2 - u2 * x1 ) * idet;
  9653. d = ( u1 * y2 - u2 * y1 ) * idet;
  9654. e = x0 - a * u0 - c * v0;
  9655. f = y0 - b * u0 - d * v0;
  9656. _context.save();
  9657. _context.transform( a, b, c, d, e, f );
  9658. _context.clip();
  9659. _context.drawImage( image, 0, 0 );
  9660. _context.restore();
  9661. }
  9662. // Hide anti-alias gaps
  9663. function expand( v1, v2, pixels ) {
  9664. var x = v2.x - v1.x, y = v2.y - v1.y,
  9665. det = x * x + y * y, idet;
  9666. if ( det === 0 ) return;
  9667. idet = pixels / Math.sqrt( det );
  9668. x *= idet; y *= idet;
  9669. v2.x += x; v2.y += y;
  9670. v1.x -= x; v1.y -= y;
  9671. }
  9672. // Context cached methods.
  9673. function setOpacity( value ) {
  9674. if ( _contextGlobalAlpha !== value ) {
  9675. _context.globalAlpha = value;
  9676. _contextGlobalAlpha = value;
  9677. }
  9678. }
  9679. function setBlending( value ) {
  9680. if ( _contextGlobalCompositeOperation !== value ) {
  9681. if ( value === THREE.NormalBlending ) {
  9682. _context.globalCompositeOperation = 'source-over';
  9683. } else if ( value === THREE.AdditiveBlending ) {
  9684. _context.globalCompositeOperation = 'lighter';
  9685. } else if ( value === THREE.SubtractiveBlending ) {
  9686. _context.globalCompositeOperation = 'darker';
  9687. }
  9688. _contextGlobalCompositeOperation = value;
  9689. }
  9690. }
  9691. function setLineWidth( value ) {
  9692. if ( _contextLineWidth !== value ) {
  9693. _context.lineWidth = value;
  9694. _contextLineWidth = value;
  9695. }
  9696. }
  9697. function setLineCap( value ) {
  9698. // "butt", "round", "square"
  9699. if ( _contextLineCap !== value ) {
  9700. _context.lineCap = value;
  9701. _contextLineCap = value;
  9702. }
  9703. }
  9704. function setLineJoin( value ) {
  9705. // "round", "bevel", "miter"
  9706. if ( _contextLineJoin !== value ) {
  9707. _context.lineJoin = value;
  9708. _contextLineJoin = value;
  9709. }
  9710. }
  9711. function setStrokeStyle( value ) {
  9712. if ( _contextStrokeStyle !== value ) {
  9713. _context.strokeStyle = value;
  9714. _contextStrokeStyle = value;
  9715. }
  9716. }
  9717. function setFillStyle( value ) {
  9718. if ( _contextFillStyle !== value ) {
  9719. _context.fillStyle = value;
  9720. _contextFillStyle = value;
  9721. }
  9722. }
  9723. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9724. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9725. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9726. _contextDashSize = dashSizeValue;
  9727. _contextGapSize = gapSizeValue;
  9728. }
  9729. }
  9730. };
  9731. /**
  9732. * Shader chunks for WebLG Shader library
  9733. *
  9734. * @author alteredq / http://alteredqualia.com/
  9735. * @author mrdoob / http://mrdoob.com/
  9736. * @author mikael emtinger / http://gomo.se/
  9737. */
  9738. THREE.ShaderChunk = {
  9739. // FOG
  9740. fog_pars_fragment: [
  9741. "#ifdef USE_FOG",
  9742. " uniform vec3 fogColor;",
  9743. " #ifdef FOG_EXP2",
  9744. " uniform float fogDensity;",
  9745. " #else",
  9746. " uniform float fogNear;",
  9747. " uniform float fogFar;",
  9748. " #endif",
  9749. "#endif"
  9750. ].join("\n"),
  9751. fog_fragment: [
  9752. "#ifdef USE_FOG",
  9753. " #ifdef USE_LOGDEPTHBUF_EXT",
  9754. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  9755. " #else",
  9756. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9757. " #endif",
  9758. " #ifdef FOG_EXP2",
  9759. " const float LOG2 = 1.442695;",
  9760. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9761. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9762. " #else",
  9763. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9764. " #endif",
  9765. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9766. "#endif"
  9767. ].join("\n"),
  9768. // ENVIRONMENT MAP
  9769. envmap_pars_fragment: [
  9770. "#ifdef USE_ENVMAP",
  9771. " uniform float reflectivity;",
  9772. " uniform samplerCube envMap;",
  9773. " uniform float flipEnvMap;",
  9774. " uniform int combine;",
  9775. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9776. " uniform bool useRefract;",
  9777. " uniform float refractionRatio;",
  9778. " #else",
  9779. " varying vec3 vReflect;",
  9780. " #endif",
  9781. "#endif"
  9782. ].join("\n"),
  9783. envmap_fragment: [
  9784. "#ifdef USE_ENVMAP",
  9785. " vec3 reflectVec;",
  9786. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9787. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9788. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  9789. // "Transforming Normal Vectors with the Inverse Transformation"
  9790. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  9791. " if ( useRefract ) {",
  9792. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  9793. " } else { ",
  9794. " reflectVec = reflect( cameraToVertex, worldNormal );",
  9795. " }",
  9796. " #else",
  9797. " reflectVec = vReflect;",
  9798. " #endif",
  9799. " #ifdef DOUBLE_SIDED",
  9800. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9801. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9802. " #else",
  9803. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9804. " #endif",
  9805. " #ifdef GAMMA_INPUT",
  9806. " cubeColor.xyz *= cubeColor.xyz;",
  9807. " #endif",
  9808. " if ( combine == 1 ) {",
  9809. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9810. " } else if ( combine == 2 ) {",
  9811. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9812. " } else {",
  9813. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9814. " }",
  9815. "#endif"
  9816. ].join("\n"),
  9817. envmap_pars_vertex: [
  9818. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9819. " varying vec3 vReflect;",
  9820. " uniform float refractionRatio;",
  9821. " uniform bool useRefract;",
  9822. "#endif"
  9823. ].join("\n"),
  9824. worldpos_vertex : [
  9825. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9826. " #ifdef USE_SKINNING",
  9827. " vec4 worldPosition = modelMatrix * skinned;",
  9828. " #endif",
  9829. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9830. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9831. " #endif",
  9832. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9833. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9834. " #endif",
  9835. "#endif"
  9836. ].join("\n"),
  9837. envmap_vertex : [
  9838. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9839. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9840. " worldNormal = normalize( worldNormal );",
  9841. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9842. " if ( useRefract ) {",
  9843. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9844. " } else {",
  9845. " vReflect = reflect( cameraToVertex, worldNormal );",
  9846. " }",
  9847. "#endif"
  9848. ].join("\n"),
  9849. // COLOR MAP (particles)
  9850. map_particle_pars_fragment: [
  9851. "#ifdef USE_MAP",
  9852. " uniform sampler2D map;",
  9853. "#endif"
  9854. ].join("\n"),
  9855. map_particle_fragment: [
  9856. "#ifdef USE_MAP",
  9857. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9858. "#endif"
  9859. ].join("\n"),
  9860. // COLOR MAP (triangles)
  9861. map_pars_vertex: [
  9862. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9863. " varying vec2 vUv;",
  9864. " uniform vec4 offsetRepeat;",
  9865. "#endif"
  9866. ].join("\n"),
  9867. map_pars_fragment: [
  9868. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9869. " varying vec2 vUv;",
  9870. "#endif",
  9871. "#ifdef USE_MAP",
  9872. " uniform sampler2D map;",
  9873. "#endif"
  9874. ].join("\n"),
  9875. map_vertex: [
  9876. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9877. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9878. "#endif"
  9879. ].join("\n"),
  9880. map_fragment: [
  9881. "#ifdef USE_MAP",
  9882. " vec4 texelColor = texture2D( map, vUv );",
  9883. " #ifdef GAMMA_INPUT",
  9884. " texelColor.xyz *= texelColor.xyz;",
  9885. " #endif",
  9886. " gl_FragColor = gl_FragColor * texelColor;",
  9887. "#endif"
  9888. ].join("\n"),
  9889. // LIGHT MAP
  9890. lightmap_pars_fragment: [
  9891. "#ifdef USE_LIGHTMAP",
  9892. " varying vec2 vUv2;",
  9893. " uniform sampler2D lightMap;",
  9894. "#endif"
  9895. ].join("\n"),
  9896. lightmap_pars_vertex: [
  9897. "#ifdef USE_LIGHTMAP",
  9898. " varying vec2 vUv2;",
  9899. "#endif"
  9900. ].join("\n"),
  9901. lightmap_fragment: [
  9902. "#ifdef USE_LIGHTMAP",
  9903. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9904. "#endif"
  9905. ].join("\n"),
  9906. lightmap_vertex: [
  9907. "#ifdef USE_LIGHTMAP",
  9908. " vUv2 = uv2;",
  9909. "#endif"
  9910. ].join("\n"),
  9911. // BUMP MAP
  9912. bumpmap_pars_fragment: [
  9913. "#ifdef USE_BUMPMAP",
  9914. " uniform sampler2D bumpMap;",
  9915. " uniform float bumpScale;",
  9916. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9917. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9918. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9919. " vec2 dHdxy_fwd() {",
  9920. " vec2 dSTdx = dFdx( vUv );",
  9921. " vec2 dSTdy = dFdy( vUv );",
  9922. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9923. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9924. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9925. " return vec2( dBx, dBy );",
  9926. " }",
  9927. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9928. " vec3 vSigmaX = dFdx( surf_pos );",
  9929. " vec3 vSigmaY = dFdy( surf_pos );",
  9930. " vec3 vN = surf_norm;", // normalized
  9931. " vec3 R1 = cross( vSigmaY, vN );",
  9932. " vec3 R2 = cross( vN, vSigmaX );",
  9933. " float fDet = dot( vSigmaX, R1 );",
  9934. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9935. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  9936. " }",
  9937. "#endif"
  9938. ].join("\n"),
  9939. // NORMAL MAP
  9940. normalmap_pars_fragment: [
  9941. "#ifdef USE_NORMALMAP",
  9942. " uniform sampler2D normalMap;",
  9943. " uniform vec2 normalScale;",
  9944. // Per-Pixel Tangent Space Normal Mapping
  9945. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9946. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9947. " vec3 q0 = dFdx( eye_pos.xyz );",
  9948. " vec3 q1 = dFdy( eye_pos.xyz );",
  9949. " vec2 st0 = dFdx( vUv.st );",
  9950. " vec2 st1 = dFdy( vUv.st );",
  9951. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9952. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9953. " vec3 N = normalize( surf_norm );",
  9954. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9955. " mapN.xy = normalScale * mapN.xy;",
  9956. " mat3 tsn = mat3( S, T, N );",
  9957. " return normalize( tsn * mapN );",
  9958. " }",
  9959. "#endif"
  9960. ].join("\n"),
  9961. // SPECULAR MAP
  9962. specularmap_pars_fragment: [
  9963. "#ifdef USE_SPECULARMAP",
  9964. " uniform sampler2D specularMap;",
  9965. "#endif"
  9966. ].join("\n"),
  9967. specularmap_fragment: [
  9968. "float specularStrength;",
  9969. "#ifdef USE_SPECULARMAP",
  9970. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  9971. " specularStrength = texelSpecular.r;",
  9972. "#else",
  9973. " specularStrength = 1.0;",
  9974. "#endif"
  9975. ].join("\n"),
  9976. // LIGHTS LAMBERT
  9977. lights_lambert_pars_vertex: [
  9978. "uniform vec3 ambient;",
  9979. "uniform vec3 diffuse;",
  9980. "uniform vec3 emissive;",
  9981. "uniform vec3 ambientLightColor;",
  9982. "#if MAX_DIR_LIGHTS > 0",
  9983. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9984. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9985. "#endif",
  9986. "#if MAX_HEMI_LIGHTS > 0",
  9987. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9988. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9989. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9990. "#endif",
  9991. "#if MAX_POINT_LIGHTS > 0",
  9992. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9993. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9994. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9995. "#endif",
  9996. "#if MAX_SPOT_LIGHTS > 0",
  9997. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9998. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9999. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10000. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10001. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10002. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10003. "#endif",
  10004. "#ifdef WRAP_AROUND",
  10005. " uniform vec3 wrapRGB;",
  10006. "#endif"
  10007. ].join("\n"),
  10008. lights_lambert_vertex: [
  10009. "vLightFront = vec3( 0.0 );",
  10010. "#ifdef DOUBLE_SIDED",
  10011. " vLightBack = vec3( 0.0 );",
  10012. "#endif",
  10013. "transformedNormal = normalize( transformedNormal );",
  10014. "#if MAX_DIR_LIGHTS > 0",
  10015. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10016. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10017. " vec3 dirVector = normalize( lDirection.xyz );",
  10018. " float dotProduct = dot( transformedNormal, dirVector );",
  10019. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10020. " #ifdef DOUBLE_SIDED",
  10021. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10022. " #ifdef WRAP_AROUND",
  10023. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10024. " #endif",
  10025. " #endif",
  10026. " #ifdef WRAP_AROUND",
  10027. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10028. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10029. " #ifdef DOUBLE_SIDED",
  10030. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10031. " #endif",
  10032. " #endif",
  10033. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10034. " #ifdef DOUBLE_SIDED",
  10035. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10036. " #endif",
  10037. "}",
  10038. "#endif",
  10039. "#if MAX_POINT_LIGHTS > 0",
  10040. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10041. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10042. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10043. " float lDistance = 1.0;",
  10044. " if ( pointLightDistance[ i ] > 0.0 )",
  10045. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10046. " lVector = normalize( lVector );",
  10047. " float dotProduct = dot( transformedNormal, lVector );",
  10048. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10049. " #ifdef DOUBLE_SIDED",
  10050. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10051. " #ifdef WRAP_AROUND",
  10052. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10053. " #endif",
  10054. " #endif",
  10055. " #ifdef WRAP_AROUND",
  10056. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10057. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10058. " #ifdef DOUBLE_SIDED",
  10059. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10060. " #endif",
  10061. " #endif",
  10062. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10063. " #ifdef DOUBLE_SIDED",
  10064. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10065. " #endif",
  10066. " }",
  10067. "#endif",
  10068. "#if MAX_SPOT_LIGHTS > 0",
  10069. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10070. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10071. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10072. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10073. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10074. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10075. " float lDistance = 1.0;",
  10076. " if ( spotLightDistance[ i ] > 0.0 )",
  10077. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10078. " lVector = normalize( lVector );",
  10079. " float dotProduct = dot( transformedNormal, lVector );",
  10080. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10081. " #ifdef DOUBLE_SIDED",
  10082. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10083. " #ifdef WRAP_AROUND",
  10084. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10085. " #endif",
  10086. " #endif",
  10087. " #ifdef WRAP_AROUND",
  10088. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10089. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10090. " #ifdef DOUBLE_SIDED",
  10091. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10092. " #endif",
  10093. " #endif",
  10094. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10095. " #ifdef DOUBLE_SIDED",
  10096. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10097. " #endif",
  10098. " }",
  10099. " }",
  10100. "#endif",
  10101. "#if MAX_HEMI_LIGHTS > 0",
  10102. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10103. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10104. " vec3 lVector = normalize( lDirection.xyz );",
  10105. " float dotProduct = dot( transformedNormal, lVector );",
  10106. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10107. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10108. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10109. " #ifdef DOUBLE_SIDED",
  10110. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10111. " #endif",
  10112. " }",
  10113. "#endif",
  10114. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10115. "#ifdef DOUBLE_SIDED",
  10116. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10117. "#endif"
  10118. ].join("\n"),
  10119. // LIGHTS PHONG
  10120. lights_phong_pars_vertex: [
  10121. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10122. " varying vec3 vWorldPosition;",
  10123. "#endif"
  10124. ].join("\n"),
  10125. lights_phong_vertex: [
  10126. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10127. " vWorldPosition = worldPosition.xyz;",
  10128. "#endif"
  10129. ].join("\n"),
  10130. lights_phong_pars_fragment: [
  10131. "uniform vec3 ambientLightColor;",
  10132. "#if MAX_DIR_LIGHTS > 0",
  10133. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10134. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10135. "#endif",
  10136. "#if MAX_HEMI_LIGHTS > 0",
  10137. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10138. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10139. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10140. "#endif",
  10141. "#if MAX_POINT_LIGHTS > 0",
  10142. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10143. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10144. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10145. "#endif",
  10146. "#if MAX_SPOT_LIGHTS > 0",
  10147. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10148. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10149. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10150. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10151. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10152. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10153. "#endif",
  10154. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10155. " varying vec3 vWorldPosition;",
  10156. "#endif",
  10157. "#ifdef WRAP_AROUND",
  10158. " uniform vec3 wrapRGB;",
  10159. "#endif",
  10160. "varying vec3 vViewPosition;",
  10161. "varying vec3 vNormal;"
  10162. ].join("\n"),
  10163. lights_phong_fragment: [
  10164. "vec3 normal = normalize( vNormal );",
  10165. "vec3 viewPosition = normalize( vViewPosition );",
  10166. "#ifdef DOUBLE_SIDED",
  10167. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10168. "#endif",
  10169. "#ifdef USE_NORMALMAP",
  10170. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10171. "#elif defined( USE_BUMPMAP )",
  10172. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10173. "#endif",
  10174. "#if MAX_POINT_LIGHTS > 0",
  10175. " vec3 pointDiffuse = vec3( 0.0 );",
  10176. " vec3 pointSpecular = vec3( 0.0 );",
  10177. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10178. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10179. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10180. " float lDistance = 1.0;",
  10181. " if ( pointLightDistance[ i ] > 0.0 )",
  10182. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10183. " lVector = normalize( lVector );",
  10184. // diffuse
  10185. " float dotProduct = dot( normal, lVector );",
  10186. " #ifdef WRAP_AROUND",
  10187. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10188. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10189. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10190. " #else",
  10191. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10192. " #endif",
  10193. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10194. // specular
  10195. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10196. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10197. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10198. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10199. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10200. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10201. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10202. " }",
  10203. "#endif",
  10204. "#if MAX_SPOT_LIGHTS > 0",
  10205. " vec3 spotDiffuse = vec3( 0.0 );",
  10206. " vec3 spotSpecular = vec3( 0.0 );",
  10207. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10208. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10209. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10210. " float lDistance = 1.0;",
  10211. " if ( spotLightDistance[ i ] > 0.0 )",
  10212. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10213. " lVector = normalize( lVector );",
  10214. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10215. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10216. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10217. // diffuse
  10218. " float dotProduct = dot( normal, lVector );",
  10219. " #ifdef WRAP_AROUND",
  10220. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10221. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10222. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10223. " #else",
  10224. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10225. " #endif",
  10226. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10227. // specular
  10228. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10229. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10230. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10231. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10232. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10233. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10234. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10235. " }",
  10236. " }",
  10237. "#endif",
  10238. "#if MAX_DIR_LIGHTS > 0",
  10239. " vec3 dirDiffuse = vec3( 0.0 );",
  10240. " vec3 dirSpecular = vec3( 0.0 );" ,
  10241. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10242. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10243. " vec3 dirVector = normalize( lDirection.xyz );",
  10244. // diffuse
  10245. " float dotProduct = dot( normal, dirVector );",
  10246. " #ifdef WRAP_AROUND",
  10247. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10248. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10249. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10250. " #else",
  10251. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10252. " #endif",
  10253. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10254. // specular
  10255. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10256. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10257. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10258. /*
  10259. // fresnel term from skin shader
  10260. " const float F0 = 0.128;",
  10261. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10262. " float exponential = pow( base, 5.0 );",
  10263. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10264. */
  10265. /*
  10266. // fresnel term from fresnel shader
  10267. " const float mFresnelBias = 0.08;",
  10268. " const float mFresnelScale = 0.3;",
  10269. " const float mFresnelPower = 5.0;",
  10270. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10271. */
  10272. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10273. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10274. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10275. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10276. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10277. " }",
  10278. "#endif",
  10279. "#if MAX_HEMI_LIGHTS > 0",
  10280. " vec3 hemiDiffuse = vec3( 0.0 );",
  10281. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10282. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10283. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10284. " vec3 lVector = normalize( lDirection.xyz );",
  10285. // diffuse
  10286. " float dotProduct = dot( normal, lVector );",
  10287. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10288. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10289. " hemiDiffuse += diffuse * hemiColor;",
  10290. // specular (sky light)
  10291. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10292. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10293. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10294. // specular (ground light)
  10295. " vec3 lVectorGround = -lVector;",
  10296. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10297. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10298. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10299. " float dotProductGround = dot( normal, lVectorGround );",
  10300. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10301. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10302. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10303. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10304. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10305. " }",
  10306. "#endif",
  10307. "vec3 totalDiffuse = vec3( 0.0 );",
  10308. "vec3 totalSpecular = vec3( 0.0 );",
  10309. "#if MAX_DIR_LIGHTS > 0",
  10310. " totalDiffuse += dirDiffuse;",
  10311. " totalSpecular += dirSpecular;",
  10312. "#endif",
  10313. "#if MAX_HEMI_LIGHTS > 0",
  10314. " totalDiffuse += hemiDiffuse;",
  10315. " totalSpecular += hemiSpecular;",
  10316. "#endif",
  10317. "#if MAX_POINT_LIGHTS > 0",
  10318. " totalDiffuse += pointDiffuse;",
  10319. " totalSpecular += pointSpecular;",
  10320. "#endif",
  10321. "#if MAX_SPOT_LIGHTS > 0",
  10322. " totalDiffuse += spotDiffuse;",
  10323. " totalSpecular += spotSpecular;",
  10324. "#endif",
  10325. "#ifdef METAL",
  10326. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10327. "#else",
  10328. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10329. "#endif"
  10330. ].join("\n"),
  10331. // VERTEX COLORS
  10332. color_pars_fragment: [
  10333. "#ifdef USE_COLOR",
  10334. " varying vec3 vColor;",
  10335. "#endif"
  10336. ].join("\n"),
  10337. color_fragment: [
  10338. "#ifdef USE_COLOR",
  10339. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10340. "#endif"
  10341. ].join("\n"),
  10342. color_pars_vertex: [
  10343. "#ifdef USE_COLOR",
  10344. " varying vec3 vColor;",
  10345. "#endif"
  10346. ].join("\n"),
  10347. color_vertex: [
  10348. "#ifdef USE_COLOR",
  10349. " #ifdef GAMMA_INPUT",
  10350. " vColor = color * color;",
  10351. " #else",
  10352. " vColor = color;",
  10353. " #endif",
  10354. "#endif"
  10355. ].join("\n"),
  10356. // SKINNING
  10357. skinning_pars_vertex: [
  10358. "#ifdef USE_SKINNING",
  10359. " #ifdef BONE_TEXTURE",
  10360. " uniform sampler2D boneTexture;",
  10361. " uniform int boneTextureWidth;",
  10362. " uniform int boneTextureHeight;",
  10363. " mat4 getBoneMatrix( const in float i ) {",
  10364. " float j = i * 4.0;",
  10365. " float x = mod( j, float( boneTextureWidth ) );",
  10366. " float y = floor( j / float( boneTextureWidth ) );",
  10367. " float dx = 1.0 / float( boneTextureWidth );",
  10368. " float dy = 1.0 / float( boneTextureHeight );",
  10369. " y = dy * ( y + 0.5 );",
  10370. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10371. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10372. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10373. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10374. " mat4 bone = mat4( v1, v2, v3, v4 );",
  10375. " return bone;",
  10376. " }",
  10377. " #else",
  10378. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10379. " mat4 getBoneMatrix( const in float i ) {",
  10380. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  10381. " return bone;",
  10382. " }",
  10383. " #endif",
  10384. "#endif"
  10385. ].join("\n"),
  10386. skinbase_vertex: [
  10387. "#ifdef USE_SKINNING",
  10388. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10389. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10390. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10391. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10392. "#endif"
  10393. ].join("\n"),
  10394. skinning_vertex: [
  10395. "#ifdef USE_SKINNING",
  10396. " #ifdef USE_MORPHTARGETS",
  10397. " vec4 skinVertex = vec4( morphed, 1.0 );",
  10398. " #else",
  10399. " vec4 skinVertex = vec4( position, 1.0 );",
  10400. " #endif",
  10401. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10402. " skinned += boneMatY * skinVertex * skinWeight.y;",
  10403. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  10404. " skinned += boneMatW * skinVertex * skinWeight.w;",
  10405. "#endif"
  10406. ].join("\n"),
  10407. // MORPHING
  10408. morphtarget_pars_vertex: [
  10409. "#ifdef USE_MORPHTARGETS",
  10410. " #ifndef USE_MORPHNORMALS",
  10411. " uniform float morphTargetInfluences[ 8 ];",
  10412. " #else",
  10413. " uniform float morphTargetInfluences[ 4 ];",
  10414. " #endif",
  10415. "#endif"
  10416. ].join("\n"),
  10417. morphtarget_vertex: [
  10418. "#ifdef USE_MORPHTARGETS",
  10419. " vec3 morphed = vec3( 0.0 );",
  10420. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10421. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10422. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10423. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10424. " #ifndef USE_MORPHNORMALS",
  10425. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10426. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10427. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10428. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10429. " #endif",
  10430. " morphed += position;",
  10431. "#endif"
  10432. ].join("\n"),
  10433. default_vertex : [
  10434. "vec4 mvPosition;",
  10435. "#ifdef USE_SKINNING",
  10436. " mvPosition = modelViewMatrix * skinned;",
  10437. "#endif",
  10438. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10439. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10440. "#endif",
  10441. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10442. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10443. "#endif",
  10444. "gl_Position = projectionMatrix * mvPosition;"
  10445. ].join("\n"),
  10446. morphnormal_vertex: [
  10447. "#ifdef USE_MORPHNORMALS",
  10448. " vec3 morphedNormal = vec3( 0.0 );",
  10449. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10450. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10451. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10452. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10453. " morphedNormal += normal;",
  10454. "#endif"
  10455. ].join("\n"),
  10456. skinnormal_vertex: [
  10457. "#ifdef USE_SKINNING",
  10458. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  10459. " skinMatrix += skinWeight.y * boneMatY;",
  10460. " skinMatrix += skinWeight.z * boneMatZ;",
  10461. " skinMatrix += skinWeight.w * boneMatW;",
  10462. " #ifdef USE_MORPHNORMALS",
  10463. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10464. " #else",
  10465. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10466. " #endif",
  10467. "#endif"
  10468. ].join("\n"),
  10469. defaultnormal_vertex: [
  10470. "vec3 objectNormal;",
  10471. "#ifdef USE_SKINNING",
  10472. " objectNormal = skinnedNormal.xyz;",
  10473. "#endif",
  10474. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10475. " objectNormal = morphedNormal;",
  10476. "#endif",
  10477. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10478. " objectNormal = normal;",
  10479. "#endif",
  10480. "#ifdef FLIP_SIDED",
  10481. " objectNormal = -objectNormal;",
  10482. "#endif",
  10483. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10484. ].join("\n"),
  10485. // SHADOW MAP
  10486. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10487. // http://spidergl.org/example.php?id=6
  10488. // http://fabiensanglard.net/shadowmapping
  10489. shadowmap_pars_fragment: [
  10490. "#ifdef USE_SHADOWMAP",
  10491. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10492. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10493. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  10494. " uniform float shadowBias[ MAX_SHADOWS ];",
  10495. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10496. " float unpackDepth( const in vec4 rgba_depth ) {",
  10497. " 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 );",
  10498. " float depth = dot( rgba_depth, bit_shift );",
  10499. " return depth;",
  10500. " }",
  10501. "#endif"
  10502. ].join("\n"),
  10503. shadowmap_fragment: [
  10504. "#ifdef USE_SHADOWMAP",
  10505. " #ifdef SHADOWMAP_DEBUG",
  10506. " vec3 frustumColors[3];",
  10507. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10508. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10509. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10510. " #endif",
  10511. " #ifdef SHADOWMAP_CASCADE",
  10512. " int inFrustumCount = 0;",
  10513. " #endif",
  10514. " float fDepth;",
  10515. " vec3 shadowColor = vec3( 1.0 );",
  10516. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10517. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10518. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10519. // "if ( all( something, something ) )" using this instead
  10520. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10521. " bool inFrustum = all( inFrustumVec );",
  10522. // don't shadow pixels outside of light frustum
  10523. // use just first frustum (for cascades)
  10524. // don't shadow pixels behind far plane of light frustum
  10525. " #ifdef SHADOWMAP_CASCADE",
  10526. " inFrustumCount += int( inFrustum );",
  10527. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10528. " #else",
  10529. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10530. " #endif",
  10531. " bool frustumTest = all( frustumTestVec );",
  10532. " if ( frustumTest ) {",
  10533. " shadowCoord.z += shadowBias[ i ];",
  10534. " #if defined( SHADOWMAP_TYPE_PCF )",
  10535. // Percentage-close filtering
  10536. // (9 pixel kernel)
  10537. // http://fabiensanglard.net/shadowmappingPCF/
  10538. " float shadow = 0.0;",
  10539. /*
  10540. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10541. // must enroll loop manually
  10542. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10543. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10544. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10545. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10546. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10547. " float fDepth = unpackDepth( rgbaDepth );",
  10548. " if ( fDepth < shadowCoord.z )",
  10549. " shadow += 1.0;",
  10550. " }",
  10551. " shadow /= 9.0;",
  10552. */
  10553. " const float shadowDelta = 1.0 / 9.0;",
  10554. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10555. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10556. " float dx0 = -1.25 * xPixelOffset;",
  10557. " float dy0 = -1.25 * yPixelOffset;",
  10558. " float dx1 = 1.25 * xPixelOffset;",
  10559. " float dy1 = 1.25 * yPixelOffset;",
  10560. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10561. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10562. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10563. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10564. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10565. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10566. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10567. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10568. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10569. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10570. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10571. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10572. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10573. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10574. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10575. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10576. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10577. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10578. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10579. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10580. // Percentage-close filtering
  10581. // (9 pixel kernel)
  10582. // http://fabiensanglard.net/shadowmappingPCF/
  10583. " float shadow = 0.0;",
  10584. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10585. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10586. " float dx0 = -1.0 * xPixelOffset;",
  10587. " float dy0 = -1.0 * yPixelOffset;",
  10588. " float dx1 = 1.0 * xPixelOffset;",
  10589. " float dy1 = 1.0 * yPixelOffset;",
  10590. " mat3 shadowKernel;",
  10591. " mat3 depthKernel;",
  10592. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10593. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10594. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10595. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10596. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10597. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10598. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10599. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10600. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10601. " vec3 shadowZ = vec3( shadowCoord.z );",
  10602. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10603. " shadowKernel[0] *= vec3(0.25);",
  10604. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10605. " shadowKernel[1] *= vec3(0.25);",
  10606. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10607. " shadowKernel[2] *= vec3(0.25);",
  10608. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10609. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10610. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10611. " vec4 shadowValues;",
  10612. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10613. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10614. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10615. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10616. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  10617. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10618. " #else",
  10619. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10620. " float fDepth = unpackDepth( rgbaDepth );",
  10621. " if ( fDepth < shadowCoord.z )",
  10622. // spot with multiple shadows is darker
  10623. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10624. // spot with multiple shadows has the same color as single shadow spot
  10625. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10626. " #endif",
  10627. " }",
  10628. " #ifdef SHADOWMAP_DEBUG",
  10629. " #ifdef SHADOWMAP_CASCADE",
  10630. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10631. " #else",
  10632. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10633. " #endif",
  10634. " #endif",
  10635. " }",
  10636. " #ifdef GAMMA_OUTPUT",
  10637. " shadowColor *= shadowColor;",
  10638. " #endif",
  10639. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10640. "#endif"
  10641. ].join("\n"),
  10642. shadowmap_pars_vertex: [
  10643. "#ifdef USE_SHADOWMAP",
  10644. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10645. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10646. "#endif"
  10647. ].join("\n"),
  10648. shadowmap_vertex: [
  10649. "#ifdef USE_SHADOWMAP",
  10650. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10651. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10652. " }",
  10653. "#endif"
  10654. ].join("\n"),
  10655. // ALPHATEST
  10656. alphatest_fragment: [
  10657. "#ifdef ALPHATEST",
  10658. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  10659. "#endif"
  10660. ].join("\n"),
  10661. // LINEAR SPACE
  10662. linear_to_gamma_fragment: [
  10663. "#ifdef GAMMA_OUTPUT",
  10664. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10665. "#endif"
  10666. ].join("\n"),
  10667. // LOGARITHMIC DEPTH BUFFER
  10668. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  10669. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  10670. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  10671. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  10672. // the camera is near the surface.
  10673. logdepthbuf_pars_vertex: [
  10674. "#ifdef USE_LOGDEPTHBUF",
  10675. " #ifdef USE_LOGDEPTHBUF_EXT",
  10676. " varying float vFragDepth;",
  10677. " #endif",
  10678. " uniform float logDepthBufFC;",
  10679. "#endif",
  10680. ].join('\n'),
  10681. logdepthbuf_vertex: [
  10682. "#ifdef USE_LOGDEPTHBUF",
  10683. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  10684. " #ifdef USE_LOGDEPTHBUF_EXT",
  10685. " vFragDepth = 1.0 + gl_Position.w;",
  10686. "#else",
  10687. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  10688. " #endif",
  10689. "#endif"
  10690. ].join("\n"),
  10691. logdepthbuf_pars_fragment: [
  10692. "#ifdef USE_LOGDEPTHBUF",
  10693. " uniform float logDepthBufFC;",
  10694. " #ifdef USE_LOGDEPTHBUF_EXT",
  10695. " #extension GL_EXT_frag_depth : enable",
  10696. " varying float vFragDepth;",
  10697. " #endif",
  10698. "#endif"
  10699. ].join('\n'),
  10700. logdepthbuf_fragment: [
  10701. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  10702. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  10703. "#endif"
  10704. ].join("\n")
  10705. };
  10706. /**
  10707. * Uniform Utilities
  10708. */
  10709. THREE.UniformsUtils = {
  10710. merge: function ( uniforms ) {
  10711. var u, p, tmp, merged = {};
  10712. for ( u = 0; u < uniforms.length; u ++ ) {
  10713. tmp = this.clone( uniforms[ u ] );
  10714. for ( p in tmp ) {
  10715. merged[ p ] = tmp[ p ];
  10716. }
  10717. }
  10718. return merged;
  10719. },
  10720. clone: function ( uniforms_src ) {
  10721. var u, p, parameter, parameter_src, uniforms_dst = {};
  10722. for ( u in uniforms_src ) {
  10723. uniforms_dst[ u ] = {};
  10724. for ( p in uniforms_src[ u ] ) {
  10725. parameter_src = uniforms_src[ u ][ p ];
  10726. if ( parameter_src instanceof THREE.Color ||
  10727. parameter_src instanceof THREE.Vector2 ||
  10728. parameter_src instanceof THREE.Vector3 ||
  10729. parameter_src instanceof THREE.Vector4 ||
  10730. parameter_src instanceof THREE.Matrix4 ||
  10731. parameter_src instanceof THREE.Texture ) {
  10732. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10733. } else if ( parameter_src instanceof Array ) {
  10734. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10735. } else {
  10736. uniforms_dst[ u ][ p ] = parameter_src;
  10737. }
  10738. }
  10739. }
  10740. return uniforms_dst;
  10741. }
  10742. };
  10743. /**
  10744. * Uniforms library for shared webgl shaders
  10745. */
  10746. THREE.UniformsLib = {
  10747. common: {
  10748. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10749. "opacity" : { type: "f", value: 1.0 },
  10750. "map" : { type: "t", value: null },
  10751. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10752. "lightMap" : { type: "t", value: null },
  10753. "specularMap" : { type: "t", value: null },
  10754. "envMap" : { type: "t", value: null },
  10755. "flipEnvMap" : { type: "f", value: -1 },
  10756. "useRefract" : { type: "i", value: 0 },
  10757. "reflectivity" : { type: "f", value: 1.0 },
  10758. "refractionRatio" : { type: "f", value: 0.98 },
  10759. "combine" : { type: "i", value: 0 },
  10760. "morphTargetInfluences" : { type: "f", value: 0 }
  10761. },
  10762. bump: {
  10763. "bumpMap" : { type: "t", value: null },
  10764. "bumpScale" : { type: "f", value: 1 }
  10765. },
  10766. normalmap: {
  10767. "normalMap" : { type: "t", value: null },
  10768. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10769. },
  10770. fog : {
  10771. "fogDensity" : { type: "f", value: 0.00025 },
  10772. "fogNear" : { type: "f", value: 1 },
  10773. "fogFar" : { type: "f", value: 2000 },
  10774. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10775. },
  10776. lights: {
  10777. "ambientLightColor" : { type: "fv", value: [] },
  10778. "directionalLightDirection" : { type: "fv", value: [] },
  10779. "directionalLightColor" : { type: "fv", value: [] },
  10780. "hemisphereLightDirection" : { type: "fv", value: [] },
  10781. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10782. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10783. "pointLightColor" : { type: "fv", value: [] },
  10784. "pointLightPosition" : { type: "fv", value: [] },
  10785. "pointLightDistance" : { type: "fv1", value: [] },
  10786. "spotLightColor" : { type: "fv", value: [] },
  10787. "spotLightPosition" : { type: "fv", value: [] },
  10788. "spotLightDirection" : { type: "fv", value: [] },
  10789. "spotLightDistance" : { type: "fv1", value: [] },
  10790. "spotLightAngleCos" : { type: "fv1", value: [] },
  10791. "spotLightExponent" : { type: "fv1", value: [] }
  10792. },
  10793. particle: {
  10794. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10795. "opacity" : { type: "f", value: 1.0 },
  10796. "size" : { type: "f", value: 1.0 },
  10797. "scale" : { type: "f", value: 1.0 },
  10798. "map" : { type: "t", value: null },
  10799. "fogDensity" : { type: "f", value: 0.00025 },
  10800. "fogNear" : { type: "f", value: 1 },
  10801. "fogFar" : { type: "f", value: 2000 },
  10802. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10803. },
  10804. shadowmap: {
  10805. "shadowMap": { type: "tv", value: [] },
  10806. "shadowMapSize": { type: "v2v", value: [] },
  10807. "shadowBias" : { type: "fv1", value: [] },
  10808. "shadowDarkness": { type: "fv1", value: [] },
  10809. "shadowMatrix" : { type: "m4v", value: [] }
  10810. }
  10811. };
  10812. /**
  10813. * Webgl Shader Library for three.js
  10814. *
  10815. * @author alteredq / http://alteredqualia.com/
  10816. * @author mrdoob / http://mrdoob.com/
  10817. * @author mikael emtinger / http://gomo.se/
  10818. */
  10819. THREE.ShaderLib = {
  10820. 'basic': {
  10821. uniforms: THREE.UniformsUtils.merge( [
  10822. THREE.UniformsLib[ "common" ],
  10823. THREE.UniformsLib[ "fog" ],
  10824. THREE.UniformsLib[ "shadowmap" ]
  10825. ] ),
  10826. vertexShader: [
  10827. THREE.ShaderChunk[ "map_pars_vertex" ],
  10828. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10829. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10830. THREE.ShaderChunk[ "color_pars_vertex" ],
  10831. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10832. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10833. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10834. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10835. "void main() {",
  10836. THREE.ShaderChunk[ "map_vertex" ],
  10837. THREE.ShaderChunk[ "lightmap_vertex" ],
  10838. THREE.ShaderChunk[ "color_vertex" ],
  10839. THREE.ShaderChunk[ "skinbase_vertex" ],
  10840. " #ifdef USE_ENVMAP",
  10841. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10842. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10843. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10844. " #endif",
  10845. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10846. THREE.ShaderChunk[ "skinning_vertex" ],
  10847. THREE.ShaderChunk[ "default_vertex" ],
  10848. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10849. THREE.ShaderChunk[ "worldpos_vertex" ],
  10850. THREE.ShaderChunk[ "envmap_vertex" ],
  10851. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10852. "}"
  10853. ].join("\n"),
  10854. fragmentShader: [
  10855. "uniform vec3 diffuse;",
  10856. "uniform float opacity;",
  10857. THREE.ShaderChunk[ "color_pars_fragment" ],
  10858. THREE.ShaderChunk[ "map_pars_fragment" ],
  10859. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10860. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10861. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10862. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10863. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10864. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10865. "void main() {",
  10866. " gl_FragColor = vec4( diffuse, opacity );",
  10867. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10868. THREE.ShaderChunk[ "map_fragment" ],
  10869. THREE.ShaderChunk[ "alphatest_fragment" ],
  10870. THREE.ShaderChunk[ "specularmap_fragment" ],
  10871. THREE.ShaderChunk[ "lightmap_fragment" ],
  10872. THREE.ShaderChunk[ "color_fragment" ],
  10873. THREE.ShaderChunk[ "envmap_fragment" ],
  10874. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10875. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10876. THREE.ShaderChunk[ "fog_fragment" ],
  10877. "}"
  10878. ].join("\n")
  10879. },
  10880. 'lambert': {
  10881. uniforms: THREE.UniformsUtils.merge( [
  10882. THREE.UniformsLib[ "common" ],
  10883. THREE.UniformsLib[ "fog" ],
  10884. THREE.UniformsLib[ "lights" ],
  10885. THREE.UniformsLib[ "shadowmap" ],
  10886. {
  10887. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10888. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10889. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10890. }
  10891. ] ),
  10892. vertexShader: [
  10893. "#define LAMBERT",
  10894. "varying vec3 vLightFront;",
  10895. "#ifdef DOUBLE_SIDED",
  10896. " varying vec3 vLightBack;",
  10897. "#endif",
  10898. THREE.ShaderChunk[ "map_pars_vertex" ],
  10899. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10900. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10901. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10902. THREE.ShaderChunk[ "color_pars_vertex" ],
  10903. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10904. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10905. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10906. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10907. "void main() {",
  10908. THREE.ShaderChunk[ "map_vertex" ],
  10909. THREE.ShaderChunk[ "lightmap_vertex" ],
  10910. THREE.ShaderChunk[ "color_vertex" ],
  10911. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10912. THREE.ShaderChunk[ "skinbase_vertex" ],
  10913. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10914. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10915. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10916. THREE.ShaderChunk[ "skinning_vertex" ],
  10917. THREE.ShaderChunk[ "default_vertex" ],
  10918. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10919. THREE.ShaderChunk[ "worldpos_vertex" ],
  10920. THREE.ShaderChunk[ "envmap_vertex" ],
  10921. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10922. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10923. "}"
  10924. ].join("\n"),
  10925. fragmentShader: [
  10926. "uniform float opacity;",
  10927. "varying vec3 vLightFront;",
  10928. "#ifdef DOUBLE_SIDED",
  10929. " varying vec3 vLightBack;",
  10930. "#endif",
  10931. THREE.ShaderChunk[ "color_pars_fragment" ],
  10932. THREE.ShaderChunk[ "map_pars_fragment" ],
  10933. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10934. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10935. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10936. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10937. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10938. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10939. "void main() {",
  10940. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  10941. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10942. THREE.ShaderChunk[ "map_fragment" ],
  10943. THREE.ShaderChunk[ "alphatest_fragment" ],
  10944. THREE.ShaderChunk[ "specularmap_fragment" ],
  10945. " #ifdef DOUBLE_SIDED",
  10946. //"float isFront = float( gl_FrontFacing );",
  10947. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10948. " if ( gl_FrontFacing )",
  10949. " gl_FragColor.xyz *= vLightFront;",
  10950. " else",
  10951. " gl_FragColor.xyz *= vLightBack;",
  10952. " #else",
  10953. " gl_FragColor.xyz *= vLightFront;",
  10954. " #endif",
  10955. THREE.ShaderChunk[ "lightmap_fragment" ],
  10956. THREE.ShaderChunk[ "color_fragment" ],
  10957. THREE.ShaderChunk[ "envmap_fragment" ],
  10958. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10959. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10960. THREE.ShaderChunk[ "fog_fragment" ],
  10961. "}"
  10962. ].join("\n")
  10963. },
  10964. 'phong': {
  10965. uniforms: THREE.UniformsUtils.merge( [
  10966. THREE.UniformsLib[ "common" ],
  10967. THREE.UniformsLib[ "bump" ],
  10968. THREE.UniformsLib[ "normalmap" ],
  10969. THREE.UniformsLib[ "fog" ],
  10970. THREE.UniformsLib[ "lights" ],
  10971. THREE.UniformsLib[ "shadowmap" ],
  10972. {
  10973. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10974. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10975. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10976. "shininess": { type: "f", value: 30 },
  10977. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10978. }
  10979. ] ),
  10980. vertexShader: [
  10981. "#define PHONG",
  10982. "varying vec3 vViewPosition;",
  10983. "varying vec3 vNormal;",
  10984. THREE.ShaderChunk[ "map_pars_vertex" ],
  10985. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10986. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10987. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10988. THREE.ShaderChunk[ "color_pars_vertex" ],
  10989. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10990. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10991. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10992. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10993. "void main() {",
  10994. THREE.ShaderChunk[ "map_vertex" ],
  10995. THREE.ShaderChunk[ "lightmap_vertex" ],
  10996. THREE.ShaderChunk[ "color_vertex" ],
  10997. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10998. THREE.ShaderChunk[ "skinbase_vertex" ],
  10999. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11000. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11001. " vNormal = normalize( transformedNormal );",
  11002. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11003. THREE.ShaderChunk[ "skinning_vertex" ],
  11004. THREE.ShaderChunk[ "default_vertex" ],
  11005. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11006. " vViewPosition = -mvPosition.xyz;",
  11007. THREE.ShaderChunk[ "worldpos_vertex" ],
  11008. THREE.ShaderChunk[ "envmap_vertex" ],
  11009. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11010. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11011. "}"
  11012. ].join("\n"),
  11013. fragmentShader: [
  11014. "uniform vec3 diffuse;",
  11015. "uniform float opacity;",
  11016. "uniform vec3 ambient;",
  11017. "uniform vec3 emissive;",
  11018. "uniform vec3 specular;",
  11019. "uniform float shininess;",
  11020. THREE.ShaderChunk[ "color_pars_fragment" ],
  11021. THREE.ShaderChunk[ "map_pars_fragment" ],
  11022. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11023. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11024. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11025. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11026. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11027. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11028. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11029. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11030. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11031. "void main() {",
  11032. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11033. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11034. THREE.ShaderChunk[ "map_fragment" ],
  11035. THREE.ShaderChunk[ "alphatest_fragment" ],
  11036. THREE.ShaderChunk[ "specularmap_fragment" ],
  11037. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11038. THREE.ShaderChunk[ "lightmap_fragment" ],
  11039. THREE.ShaderChunk[ "color_fragment" ],
  11040. THREE.ShaderChunk[ "envmap_fragment" ],
  11041. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11042. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11043. THREE.ShaderChunk[ "fog_fragment" ],
  11044. "}"
  11045. ].join("\n")
  11046. },
  11047. 'particle_basic': {
  11048. uniforms: THREE.UniformsUtils.merge( [
  11049. THREE.UniformsLib[ "particle" ],
  11050. THREE.UniformsLib[ "shadowmap" ]
  11051. ] ),
  11052. vertexShader: [
  11053. "uniform float size;",
  11054. "uniform float scale;",
  11055. THREE.ShaderChunk[ "color_pars_vertex" ],
  11056. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11057. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11058. "void main() {",
  11059. THREE.ShaderChunk[ "color_vertex" ],
  11060. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11061. " #ifdef USE_SIZEATTENUATION",
  11062. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11063. " #else",
  11064. " gl_PointSize = size;",
  11065. " #endif",
  11066. " gl_Position = projectionMatrix * mvPosition;",
  11067. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11068. THREE.ShaderChunk[ "worldpos_vertex" ],
  11069. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11070. "}"
  11071. ].join("\n"),
  11072. fragmentShader: [
  11073. "uniform vec3 psColor;",
  11074. "uniform float opacity;",
  11075. THREE.ShaderChunk[ "color_pars_fragment" ],
  11076. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11077. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11078. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11079. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11080. "void main() {",
  11081. " gl_FragColor = vec4( psColor, opacity );",
  11082. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11083. THREE.ShaderChunk[ "map_particle_fragment" ],
  11084. THREE.ShaderChunk[ "alphatest_fragment" ],
  11085. THREE.ShaderChunk[ "color_fragment" ],
  11086. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11087. THREE.ShaderChunk[ "fog_fragment" ],
  11088. "}"
  11089. ].join("\n")
  11090. },
  11091. 'dashed': {
  11092. uniforms: THREE.UniformsUtils.merge( [
  11093. THREE.UniformsLib[ "common" ],
  11094. THREE.UniformsLib[ "fog" ],
  11095. {
  11096. "scale": { type: "f", value: 1 },
  11097. "dashSize": { type: "f", value: 1 },
  11098. "totalSize": { type: "f", value: 2 }
  11099. }
  11100. ] ),
  11101. vertexShader: [
  11102. "uniform float scale;",
  11103. "attribute float lineDistance;",
  11104. "varying float vLineDistance;",
  11105. THREE.ShaderChunk[ "color_pars_vertex" ],
  11106. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11107. "void main() {",
  11108. THREE.ShaderChunk[ "color_vertex" ],
  11109. " vLineDistance = scale * lineDistance;",
  11110. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11111. " gl_Position = projectionMatrix * mvPosition;",
  11112. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11113. "}"
  11114. ].join("\n"),
  11115. fragmentShader: [
  11116. "uniform vec3 diffuse;",
  11117. "uniform float opacity;",
  11118. "uniform float dashSize;",
  11119. "uniform float totalSize;",
  11120. "varying float vLineDistance;",
  11121. THREE.ShaderChunk[ "color_pars_fragment" ],
  11122. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11123. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11124. "void main() {",
  11125. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11126. " discard;",
  11127. " }",
  11128. " gl_FragColor = vec4( diffuse, opacity );",
  11129. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11130. THREE.ShaderChunk[ "color_fragment" ],
  11131. THREE.ShaderChunk[ "fog_fragment" ],
  11132. "}"
  11133. ].join("\n")
  11134. },
  11135. 'depth': {
  11136. uniforms: {
  11137. "mNear": { type: "f", value: 1.0 },
  11138. "mFar" : { type: "f", value: 2000.0 },
  11139. "opacity" : { type: "f", value: 1.0 }
  11140. },
  11141. vertexShader: [
  11142. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11143. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11144. "void main() {",
  11145. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11146. THREE.ShaderChunk[ "default_vertex" ],
  11147. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11148. "}"
  11149. ].join("\n"),
  11150. fragmentShader: [
  11151. "uniform float mNear;",
  11152. "uniform float mFar;",
  11153. "uniform float opacity;",
  11154. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11155. "void main() {",
  11156. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11157. " #ifdef USE_LOGDEPTHBUF_EXT",
  11158. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11159. " #else",
  11160. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11161. " #endif",
  11162. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11163. " gl_FragColor = vec4( vec3( color ), opacity );",
  11164. "}"
  11165. ].join("\n")
  11166. },
  11167. 'normal': {
  11168. uniforms: {
  11169. "opacity" : { type: "f", value: 1.0 }
  11170. },
  11171. vertexShader: [
  11172. "varying vec3 vNormal;",
  11173. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11174. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11175. "void main() {",
  11176. " vNormal = normalize( normalMatrix * normal );",
  11177. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11178. THREE.ShaderChunk[ "default_vertex" ],
  11179. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11180. "}"
  11181. ].join("\n"),
  11182. fragmentShader: [
  11183. "uniform float opacity;",
  11184. "varying vec3 vNormal;",
  11185. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11186. "void main() {",
  11187. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11188. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11189. "}"
  11190. ].join("\n")
  11191. },
  11192. /* -------------------------------------------------------------------------
  11193. // Normal map shader
  11194. // - Blinn-Phong
  11195. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11196. // - point and directional lights (use with "lights: true" material option)
  11197. ------------------------------------------------------------------------- */
  11198. 'normalmap' : {
  11199. uniforms: THREE.UniformsUtils.merge( [
  11200. THREE.UniformsLib[ "fog" ],
  11201. THREE.UniformsLib[ "lights" ],
  11202. THREE.UniformsLib[ "shadowmap" ],
  11203. {
  11204. "enableAO" : { type: "i", value: 0 },
  11205. "enableDiffuse" : { type: "i", value: 0 },
  11206. "enableSpecular" : { type: "i", value: 0 },
  11207. "enableReflection": { type: "i", value: 0 },
  11208. "enableDisplacement": { type: "i", value: 0 },
  11209. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11210. "tDiffuse" : { type: "t", value: null },
  11211. "tCube" : { type: "t", value: null },
  11212. "tNormal" : { type: "t", value: null },
  11213. "tSpecular" : { type: "t", value: null },
  11214. "tAO" : { type: "t", value: null },
  11215. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11216. "uDisplacementBias": { type: "f", value: 0.0 },
  11217. "uDisplacementScale": { type: "f", value: 1.0 },
  11218. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11219. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11220. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11221. "shininess": { type: "f", value: 30 },
  11222. "opacity": { type: "f", value: 1 },
  11223. "useRefract": { type: "i", value: 0 },
  11224. "refractionRatio": { type: "f", value: 0.98 },
  11225. "reflectivity": { type: "f", value: 0.5 },
  11226. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11227. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11228. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11229. }
  11230. ] ),
  11231. fragmentShader: [
  11232. "uniform vec3 ambient;",
  11233. "uniform vec3 diffuse;",
  11234. "uniform vec3 specular;",
  11235. "uniform float shininess;",
  11236. "uniform float opacity;",
  11237. "uniform bool enableDiffuse;",
  11238. "uniform bool enableSpecular;",
  11239. "uniform bool enableAO;",
  11240. "uniform bool enableReflection;",
  11241. "uniform sampler2D tDiffuse;",
  11242. "uniform sampler2D tNormal;",
  11243. "uniform sampler2D tSpecular;",
  11244. "uniform sampler2D tAO;",
  11245. "uniform samplerCube tCube;",
  11246. "uniform vec2 uNormalScale;",
  11247. "uniform bool useRefract;",
  11248. "uniform float refractionRatio;",
  11249. "uniform float reflectivity;",
  11250. "varying vec3 vTangent;",
  11251. "varying vec3 vBinormal;",
  11252. "varying vec3 vNormal;",
  11253. "varying vec2 vUv;",
  11254. "uniform vec3 ambientLightColor;",
  11255. "#if MAX_DIR_LIGHTS > 0",
  11256. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11257. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11258. "#endif",
  11259. "#if MAX_HEMI_LIGHTS > 0",
  11260. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11261. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11262. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11263. "#endif",
  11264. "#if MAX_POINT_LIGHTS > 0",
  11265. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11266. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11267. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11268. "#endif",
  11269. "#if MAX_SPOT_LIGHTS > 0",
  11270. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11271. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11272. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11273. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11274. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11275. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11276. "#endif",
  11277. "#ifdef WRAP_AROUND",
  11278. " uniform vec3 wrapRGB;",
  11279. "#endif",
  11280. "varying vec3 vWorldPosition;",
  11281. "varying vec3 vViewPosition;",
  11282. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11283. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11284. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11285. "void main() {",
  11286. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11287. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11288. " vec3 specularTex = vec3( 1.0 );",
  11289. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11290. " normalTex.xy *= uNormalScale;",
  11291. " normalTex = normalize( normalTex );",
  11292. " if( enableDiffuse ) {",
  11293. " #ifdef GAMMA_INPUT",
  11294. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11295. " texelColor.xyz *= texelColor.xyz;",
  11296. " gl_FragColor = gl_FragColor * texelColor;",
  11297. " #else",
  11298. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11299. " #endif",
  11300. " }",
  11301. " if( enableAO ) {",
  11302. " #ifdef GAMMA_INPUT",
  11303. " vec4 aoColor = texture2D( tAO, vUv );",
  11304. " aoColor.xyz *= aoColor.xyz;",
  11305. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11306. " #else",
  11307. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11308. " #endif",
  11309. " }",
  11310. " if( enableSpecular )",
  11311. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11312. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11313. " vec3 finalNormal = tsb * normalTex;",
  11314. " #ifdef FLIP_SIDED",
  11315. " finalNormal = -finalNormal;",
  11316. " #endif",
  11317. " vec3 normal = normalize( finalNormal );",
  11318. " vec3 viewPosition = normalize( vViewPosition );",
  11319. // point lights
  11320. " #if MAX_POINT_LIGHTS > 0",
  11321. " vec3 pointDiffuse = vec3( 0.0 );",
  11322. " vec3 pointSpecular = vec3( 0.0 );",
  11323. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11324. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11325. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11326. " float pointDistance = 1.0;",
  11327. " if ( pointLightDistance[ i ] > 0.0 )",
  11328. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11329. " pointVector = normalize( pointVector );",
  11330. // diffuse
  11331. " #ifdef WRAP_AROUND",
  11332. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11333. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11334. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11335. " #else",
  11336. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11337. " #endif",
  11338. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11339. // specular
  11340. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11341. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11342. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11343. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11344. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11345. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11346. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11347. " }",
  11348. " #endif",
  11349. // spot lights
  11350. " #if MAX_SPOT_LIGHTS > 0",
  11351. " vec3 spotDiffuse = vec3( 0.0 );",
  11352. " vec3 spotSpecular = vec3( 0.0 );",
  11353. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11354. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11355. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11356. " float spotDistance = 1.0;",
  11357. " if ( spotLightDistance[ i ] > 0.0 )",
  11358. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11359. " spotVector = normalize( spotVector );",
  11360. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11361. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11362. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11363. // diffuse
  11364. " #ifdef WRAP_AROUND",
  11365. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11366. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11367. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11368. " #else",
  11369. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11370. " #endif",
  11371. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11372. // specular
  11373. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11374. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11375. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11376. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11377. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11378. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11379. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11380. " }",
  11381. " }",
  11382. " #endif",
  11383. // directional lights
  11384. " #if MAX_DIR_LIGHTS > 0",
  11385. " vec3 dirDiffuse = vec3( 0.0 );",
  11386. " vec3 dirSpecular = vec3( 0.0 );",
  11387. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11388. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11389. " vec3 dirVector = normalize( lDirection.xyz );",
  11390. // diffuse
  11391. " #ifdef WRAP_AROUND",
  11392. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11393. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11394. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11395. " #else",
  11396. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11397. " #endif",
  11398. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11399. // specular
  11400. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11401. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11402. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11403. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11404. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11405. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11406. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11407. " }",
  11408. " #endif",
  11409. // hemisphere lights
  11410. " #if MAX_HEMI_LIGHTS > 0",
  11411. " vec3 hemiDiffuse = vec3( 0.0 );",
  11412. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11413. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11414. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11415. " vec3 lVector = normalize( lDirection.xyz );",
  11416. // diffuse
  11417. " float dotProduct = dot( normal, lVector );",
  11418. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11419. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11420. " hemiDiffuse += diffuse * hemiColor;",
  11421. // specular (sky light)
  11422. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11423. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11424. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11425. // specular (ground light)
  11426. " vec3 lVectorGround = -lVector;",
  11427. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11428. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11429. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11430. " float dotProductGround = dot( normal, lVectorGround );",
  11431. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11432. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11433. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11434. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11435. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11436. " }",
  11437. " #endif",
  11438. // all lights contribution summation
  11439. " vec3 totalDiffuse = vec3( 0.0 );",
  11440. " vec3 totalSpecular = vec3( 0.0 );",
  11441. " #if MAX_DIR_LIGHTS > 0",
  11442. " totalDiffuse += dirDiffuse;",
  11443. " totalSpecular += dirSpecular;",
  11444. " #endif",
  11445. " #if MAX_HEMI_LIGHTS > 0",
  11446. " totalDiffuse += hemiDiffuse;",
  11447. " totalSpecular += hemiSpecular;",
  11448. " #endif",
  11449. " #if MAX_POINT_LIGHTS > 0",
  11450. " totalDiffuse += pointDiffuse;",
  11451. " totalSpecular += pointSpecular;",
  11452. " #endif",
  11453. " #if MAX_SPOT_LIGHTS > 0",
  11454. " totalDiffuse += spotDiffuse;",
  11455. " totalSpecular += spotSpecular;",
  11456. " #endif",
  11457. " #ifdef METAL",
  11458. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11459. " #else",
  11460. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11461. " #endif",
  11462. " if ( enableReflection ) {",
  11463. " vec3 vReflect;",
  11464. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11465. " if ( useRefract ) {",
  11466. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11467. " } else {",
  11468. " vReflect = reflect( cameraToVertex, normal );",
  11469. " }",
  11470. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11471. " #ifdef GAMMA_INPUT",
  11472. " cubeColor.xyz *= cubeColor.xyz;",
  11473. " #endif",
  11474. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11475. " }",
  11476. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11477. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11478. THREE.ShaderChunk[ "fog_fragment" ],
  11479. "}"
  11480. ].join("\n"),
  11481. vertexShader: [
  11482. "attribute vec4 tangent;",
  11483. "uniform vec2 uOffset;",
  11484. "uniform vec2 uRepeat;",
  11485. "uniform bool enableDisplacement;",
  11486. "#ifdef VERTEX_TEXTURES",
  11487. " uniform sampler2D tDisplacement;",
  11488. " uniform float uDisplacementScale;",
  11489. " uniform float uDisplacementBias;",
  11490. "#endif",
  11491. "varying vec3 vTangent;",
  11492. "varying vec3 vBinormal;",
  11493. "varying vec3 vNormal;",
  11494. "varying vec2 vUv;",
  11495. "varying vec3 vWorldPosition;",
  11496. "varying vec3 vViewPosition;",
  11497. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11498. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11499. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11500. "void main() {",
  11501. THREE.ShaderChunk[ "skinbase_vertex" ],
  11502. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11503. // normal, tangent and binormal vectors
  11504. " #ifdef USE_SKINNING",
  11505. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11506. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11507. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11508. " #else",
  11509. " vNormal = normalize( normalMatrix * normal );",
  11510. " vTangent = normalize( normalMatrix * tangent.xyz );",
  11511. " #endif",
  11512. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11513. " vUv = uv * uRepeat + uOffset;",
  11514. // displacement mapping
  11515. " vec3 displacedPosition;",
  11516. " #ifdef VERTEX_TEXTURES",
  11517. " if ( enableDisplacement ) {",
  11518. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11519. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11520. " displacedPosition = position + normalize( normal ) * df;",
  11521. " } else {",
  11522. " #ifdef USE_SKINNING",
  11523. " vec4 skinVertex = vec4( position, 1.0 );",
  11524. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11525. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11526. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11527. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11528. " displacedPosition = skinned.xyz;",
  11529. " #else",
  11530. " displacedPosition = position;",
  11531. " #endif",
  11532. " }",
  11533. " #else",
  11534. " #ifdef USE_SKINNING",
  11535. " vec4 skinVertex = vec4( position, 1.0 );",
  11536. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11537. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11538. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11539. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11540. " displacedPosition = skinned.xyz;",
  11541. " #else",
  11542. " displacedPosition = position;",
  11543. " #endif",
  11544. " #endif",
  11545. //
  11546. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11547. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11548. " gl_Position = projectionMatrix * mvPosition;",
  11549. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11550. //
  11551. " vWorldPosition = worldPosition.xyz;",
  11552. " vViewPosition = -mvPosition.xyz;",
  11553. // shadows
  11554. " #ifdef USE_SHADOWMAP",
  11555. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11556. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11557. " }",
  11558. " #endif",
  11559. "}"
  11560. ].join("\n")
  11561. },
  11562. /* -------------------------------------------------------------------------
  11563. // Cube map shader
  11564. ------------------------------------------------------------------------- */
  11565. 'cube': {
  11566. uniforms: { "tCube": { type: "t", value: null },
  11567. "tFlip": { type: "f", value: -1 } },
  11568. vertexShader: [
  11569. "varying vec3 vWorldPosition;",
  11570. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11571. "void main() {",
  11572. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11573. " vWorldPosition = worldPosition.xyz;",
  11574. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11575. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11576. "}"
  11577. ].join("\n"),
  11578. fragmentShader: [
  11579. "uniform samplerCube tCube;",
  11580. "uniform float tFlip;",
  11581. "varying vec3 vWorldPosition;",
  11582. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11583. "void main() {",
  11584. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11585. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11586. "}"
  11587. ].join("\n")
  11588. },
  11589. // Depth encoding into RGBA texture
  11590. // based on SpiderGL shadow map example
  11591. // http://spidergl.org/example.php?id=6
  11592. // originally from
  11593. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11594. // see also here:
  11595. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11596. 'depthRGBA': {
  11597. uniforms: {},
  11598. vertexShader: [
  11599. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11600. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11601. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11602. "void main() {",
  11603. THREE.ShaderChunk[ "skinbase_vertex" ],
  11604. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11605. THREE.ShaderChunk[ "skinning_vertex" ],
  11606. THREE.ShaderChunk[ "default_vertex" ],
  11607. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11608. "}"
  11609. ].join("\n"),
  11610. fragmentShader: [
  11611. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11612. "vec4 pack_depth( const in float depth ) {",
  11613. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11614. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11615. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11616. " res -= res.xxyz * bit_mask;",
  11617. " return res;",
  11618. "}",
  11619. "void main() {",
  11620. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11621. " #ifdef USE_LOGDEPTHBUF_EXT",
  11622. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11623. " #else",
  11624. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11625. " #endif",
  11626. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11627. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11628. //"gl_FragData[ 0 ] = pack_depth( z );",
  11629. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11630. "}"
  11631. ].join("\n")
  11632. }
  11633. };
  11634. /**
  11635. * @author supereggbert / http://www.paulbrunt.co.uk/
  11636. * @author mrdoob / http://mrdoob.com/
  11637. * @author alteredq / http://alteredqualia.com/
  11638. * @author szimek / https://github.com/szimek/
  11639. */
  11640. THREE.WebGLRenderer = function ( parameters ) {
  11641. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11642. parameters = parameters || {};
  11643. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11644. _context = parameters.context !== undefined ? parameters.context : null,
  11645. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11646. _buffers = {},
  11647. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11648. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11649. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11650. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11651. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11652. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11653. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  11654. _clearColor = new THREE.Color( 0x000000 ),
  11655. _clearAlpha = 0;
  11656. // public properties
  11657. this.domElement = _canvas;
  11658. this.context = null;
  11659. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11660. ? parameters.devicePixelRatio
  11661. : self.devicePixelRatio !== undefined
  11662. ? self.devicePixelRatio
  11663. : 1;
  11664. // clearing
  11665. this.autoClear = true;
  11666. this.autoClearColor = true;
  11667. this.autoClearDepth = true;
  11668. this.autoClearStencil = true;
  11669. // scene graph
  11670. this.sortObjects = true;
  11671. this.autoUpdateObjects = true;
  11672. // physically based shading
  11673. this.gammaInput = false;
  11674. this.gammaOutput = false;
  11675. // shadow map
  11676. this.shadowMapEnabled = false;
  11677. this.shadowMapAutoUpdate = true;
  11678. this.shadowMapType = THREE.PCFShadowMap;
  11679. this.shadowMapCullFace = THREE.CullFaceFront;
  11680. this.shadowMapDebug = false;
  11681. this.shadowMapCascade = false;
  11682. // morphs
  11683. this.maxMorphTargets = 8;
  11684. this.maxMorphNormals = 4;
  11685. // flags
  11686. this.autoScaleCubemaps = true;
  11687. // custom render plugins
  11688. this.renderPluginsPre = [];
  11689. this.renderPluginsPost = [];
  11690. // info
  11691. this.info = {
  11692. memory: {
  11693. programs: 0,
  11694. geometries: 0,
  11695. textures: 0
  11696. },
  11697. render: {
  11698. calls: 0,
  11699. vertices: 0,
  11700. faces: 0,
  11701. points: 0
  11702. }
  11703. };
  11704. // internal properties
  11705. var _this = this,
  11706. _programs = [],
  11707. // internal state cache
  11708. _currentProgram = null,
  11709. _currentFramebuffer = null,
  11710. _currentMaterialId = -1,
  11711. _currentGeometryGroupHash = null,
  11712. _currentCamera = null,
  11713. _usedTextureUnits = 0,
  11714. // GL state cache
  11715. _oldDoubleSided = -1,
  11716. _oldFlipSided = -1,
  11717. _oldBlending = -1,
  11718. _oldBlendEquation = -1,
  11719. _oldBlendSrc = -1,
  11720. _oldBlendDst = -1,
  11721. _oldDepthTest = -1,
  11722. _oldDepthWrite = -1,
  11723. _oldPolygonOffset = null,
  11724. _oldPolygonOffsetFactor = null,
  11725. _oldPolygonOffsetUnits = null,
  11726. _oldLineWidth = null,
  11727. _viewportX = 0,
  11728. _viewportY = 0,
  11729. _viewportWidth = _canvas.width,
  11730. _viewportHeight = _canvas.height,
  11731. _currentWidth = 0,
  11732. _currentHeight = 0,
  11733. _newAttributes = new Uint8Array( 16 ),
  11734. _enabledAttributes = new Uint8Array( 16 ),
  11735. // frustum
  11736. _frustum = new THREE.Frustum(),
  11737. // camera matrices cache
  11738. _projScreenMatrix = new THREE.Matrix4(),
  11739. _projScreenMatrixPS = new THREE.Matrix4(),
  11740. _vector3 = new THREE.Vector3(),
  11741. // light arrays cache
  11742. _direction = new THREE.Vector3(),
  11743. _lightsNeedUpdate = true,
  11744. _lights = {
  11745. ambient: [ 0, 0, 0 ],
  11746. directional: { length: 0, colors: new Array(), positions: new Array() },
  11747. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11748. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11749. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11750. };
  11751. // initialize
  11752. var _gl;
  11753. var _glExtensionTextureFloat;
  11754. var _glExtensionTextureFloatLinear;
  11755. var _glExtensionStandardDerivatives;
  11756. var _glExtensionTextureFilterAnisotropic;
  11757. var _glExtensionCompressedTextureS3TC;
  11758. var _glExtensionElementIndexUint;
  11759. var _glExtensionFragDepth;
  11760. initGL();
  11761. setDefaultGLState();
  11762. this.context = _gl;
  11763. // GPU capabilities
  11764. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11765. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11766. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11767. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11768. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11769. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11770. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11771. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11772. //
  11773. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11774. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11775. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11776. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11777. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11778. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11779. /*
  11780. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11781. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11782. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11783. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11784. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11785. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11786. */
  11787. // clamp precision to maximum available
  11788. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11789. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11790. if ( _precision === "highp" && ! highpAvailable ) {
  11791. if ( mediumpAvailable ) {
  11792. _precision = "mediump";
  11793. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11794. } else {
  11795. _precision = "lowp";
  11796. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11797. }
  11798. }
  11799. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11800. _precision = "lowp";
  11801. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11802. }
  11803. // API
  11804. this.getContext = function () {
  11805. return _gl;
  11806. };
  11807. this.supportsVertexTextures = function () {
  11808. return _supportsVertexTextures;
  11809. };
  11810. this.supportsFloatTextures = function () {
  11811. return _glExtensionTextureFloat;
  11812. };
  11813. this.supportsStandardDerivatives = function () {
  11814. return _glExtensionStandardDerivatives;
  11815. };
  11816. this.supportsCompressedTextureS3TC = function () {
  11817. return _glExtensionCompressedTextureS3TC;
  11818. };
  11819. this.getMaxAnisotropy = function () {
  11820. return _maxAnisotropy;
  11821. };
  11822. this.getPrecision = function () {
  11823. return _precision;
  11824. };
  11825. this.setSize = function ( width, height, updateStyle ) {
  11826. _canvas.width = width * this.devicePixelRatio;
  11827. _canvas.height = height * this.devicePixelRatio;
  11828. if ( updateStyle !== false ) {
  11829. _canvas.style.width = width + 'px';
  11830. _canvas.style.height = height + 'px';
  11831. }
  11832. this.setViewport( 0, 0, width, height );
  11833. };
  11834. this.setViewport = function ( x, y, width, height ) {
  11835. _viewportX = x * this.devicePixelRatio;
  11836. _viewportY = y * this.devicePixelRatio;
  11837. _viewportWidth = width * this.devicePixelRatio;
  11838. _viewportHeight = height * this.devicePixelRatio;
  11839. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11840. };
  11841. this.setScissor = function ( x, y, width, height ) {
  11842. _gl.scissor(
  11843. x * this.devicePixelRatio,
  11844. y * this.devicePixelRatio,
  11845. width * this.devicePixelRatio,
  11846. height * this.devicePixelRatio
  11847. );
  11848. };
  11849. this.enableScissorTest = function ( enable ) {
  11850. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11851. };
  11852. // Clearing
  11853. this.setClearColor = function ( color, alpha ) {
  11854. _clearColor.set( color );
  11855. _clearAlpha = alpha !== undefined ? alpha : 1;
  11856. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11857. };
  11858. this.setClearColorHex = function ( hex, alpha ) {
  11859. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11860. this.setClearColor( hex, alpha );
  11861. };
  11862. this.getClearColor = function () {
  11863. return _clearColor;
  11864. };
  11865. this.getClearAlpha = function () {
  11866. return _clearAlpha;
  11867. };
  11868. this.clear = function ( color, depth, stencil ) {
  11869. var bits = 0;
  11870. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11871. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11872. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11873. _gl.clear( bits );
  11874. };
  11875. this.clearColor = function () {
  11876. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11877. };
  11878. this.clearDepth = function () {
  11879. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11880. };
  11881. this.clearStencil = function () {
  11882. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11883. };
  11884. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11885. this.setRenderTarget( renderTarget );
  11886. this.clear( color, depth, stencil );
  11887. };
  11888. // Plugins
  11889. this.addPostPlugin = function ( plugin ) {
  11890. plugin.init( this );
  11891. this.renderPluginsPost.push( plugin );
  11892. };
  11893. this.addPrePlugin = function ( plugin ) {
  11894. plugin.init( this );
  11895. this.renderPluginsPre.push( plugin );
  11896. };
  11897. // Rendering
  11898. this.updateShadowMap = function ( scene, camera ) {
  11899. _currentProgram = null;
  11900. _oldBlending = -1;
  11901. _oldDepthTest = -1;
  11902. _oldDepthWrite = -1;
  11903. _currentGeometryGroupHash = -1;
  11904. _currentMaterialId = -1;
  11905. _lightsNeedUpdate = true;
  11906. _oldDoubleSided = -1;
  11907. _oldFlipSided = -1;
  11908. this.shadowMapPlugin.update( scene, camera );
  11909. };
  11910. // Internal functions
  11911. // Buffer allocation
  11912. function createParticleBuffers ( geometry ) {
  11913. geometry.__webglVertexBuffer = _gl.createBuffer();
  11914. geometry.__webglColorBuffer = _gl.createBuffer();
  11915. _this.info.memory.geometries ++;
  11916. };
  11917. function createLineBuffers ( geometry ) {
  11918. geometry.__webglVertexBuffer = _gl.createBuffer();
  11919. geometry.__webglColorBuffer = _gl.createBuffer();
  11920. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11921. _this.info.memory.geometries ++;
  11922. };
  11923. function createMeshBuffers ( geometryGroup ) {
  11924. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11925. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11926. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11927. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11928. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11929. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11930. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11931. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11932. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11933. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11934. var m, ml;
  11935. if ( geometryGroup.numMorphTargets ) {
  11936. geometryGroup.__webglMorphTargetsBuffers = [];
  11937. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11938. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11939. }
  11940. }
  11941. if ( geometryGroup.numMorphNormals ) {
  11942. geometryGroup.__webglMorphNormalsBuffers = [];
  11943. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11944. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11945. }
  11946. }
  11947. _this.info.memory.geometries ++;
  11948. };
  11949. // Events
  11950. var onGeometryDispose = function ( event ) {
  11951. var geometry = event.target;
  11952. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11953. deallocateGeometry( geometry );
  11954. };
  11955. var onTextureDispose = function ( event ) {
  11956. var texture = event.target;
  11957. texture.removeEventListener( 'dispose', onTextureDispose );
  11958. deallocateTexture( texture );
  11959. _this.info.memory.textures --;
  11960. };
  11961. var onRenderTargetDispose = function ( event ) {
  11962. var renderTarget = event.target;
  11963. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11964. deallocateRenderTarget( renderTarget );
  11965. _this.info.memory.textures --;
  11966. };
  11967. var onMaterialDispose = function ( event ) {
  11968. var material = event.target;
  11969. material.removeEventListener( 'dispose', onMaterialDispose );
  11970. deallocateMaterial( material );
  11971. };
  11972. // Buffer deallocation
  11973. var deleteBuffers = function ( geometry ) {
  11974. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11975. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11976. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11977. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11978. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11979. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11980. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11981. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11982. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11983. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11984. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11985. // custom attributes
  11986. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11987. for ( var id in geometry.__webglCustomAttributesList ) {
  11988. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11989. }
  11990. }
  11991. _this.info.memory.geometries --;
  11992. };
  11993. var deallocateGeometry = function ( geometry ) {
  11994. geometry.__webglInit = undefined;
  11995. if ( geometry instanceof THREE.BufferGeometry ) {
  11996. var attributes = geometry.attributes;
  11997. for ( var key in attributes ) {
  11998. if ( attributes[ key ].buffer !== undefined ) {
  11999. _gl.deleteBuffer( attributes[ key ].buffer );
  12000. }
  12001. }
  12002. _this.info.memory.geometries --;
  12003. } else {
  12004. if ( geometry.geometryGroups !== undefined ) {
  12005. for ( var g in geometry.geometryGroups ) {
  12006. var geometryGroup = geometry.geometryGroups[ g ];
  12007. if ( geometryGroup.numMorphTargets !== undefined ) {
  12008. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12009. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12010. }
  12011. }
  12012. if ( geometryGroup.numMorphNormals !== undefined ) {
  12013. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12014. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12015. }
  12016. }
  12017. deleteBuffers( geometryGroup );
  12018. }
  12019. } else {
  12020. deleteBuffers( geometry );
  12021. }
  12022. }
  12023. };
  12024. var deallocateTexture = function ( texture ) {
  12025. if ( texture.image && texture.image.__webglTextureCube ) {
  12026. // cube texture
  12027. _gl.deleteTexture( texture.image.__webglTextureCube );
  12028. } else {
  12029. // 2D texture
  12030. if ( ! texture.__webglInit ) return;
  12031. texture.__webglInit = false;
  12032. _gl.deleteTexture( texture.__webglTexture );
  12033. }
  12034. };
  12035. var deallocateRenderTarget = function ( renderTarget ) {
  12036. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12037. _gl.deleteTexture( renderTarget.__webglTexture );
  12038. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12039. for ( var i = 0; i < 6; i ++ ) {
  12040. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12041. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12042. }
  12043. } else {
  12044. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12045. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12046. }
  12047. };
  12048. var deallocateMaterial = function ( material ) {
  12049. var program = material.program;
  12050. if ( program === undefined ) return;
  12051. material.program = undefined;
  12052. // only deallocate GL program if this was the last use of shared program
  12053. // assumed there is only single copy of any program in the _programs list
  12054. // (that's how it's constructed)
  12055. var i, il, programInfo;
  12056. var deleteProgram = false;
  12057. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12058. programInfo = _programs[ i ];
  12059. if ( programInfo.program === program ) {
  12060. programInfo.usedTimes --;
  12061. if ( programInfo.usedTimes === 0 ) {
  12062. deleteProgram = true;
  12063. }
  12064. break;
  12065. }
  12066. }
  12067. if ( deleteProgram === true ) {
  12068. // avoid using array.splice, this is costlier than creating new array from scratch
  12069. var newPrograms = [];
  12070. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12071. programInfo = _programs[ i ];
  12072. if ( programInfo.program !== program ) {
  12073. newPrograms.push( programInfo );
  12074. }
  12075. }
  12076. _programs = newPrograms;
  12077. _gl.deleteProgram( program );
  12078. _this.info.memory.programs --;
  12079. }
  12080. };
  12081. // Buffer initialization
  12082. function initCustomAttributes ( geometry, object ) {
  12083. var nvertices = geometry.vertices.length;
  12084. var material = object.material;
  12085. if ( material.attributes ) {
  12086. if ( geometry.__webglCustomAttributesList === undefined ) {
  12087. geometry.__webglCustomAttributesList = [];
  12088. }
  12089. for ( var a in material.attributes ) {
  12090. var attribute = material.attributes[ a ];
  12091. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12092. attribute.__webglInitialized = true;
  12093. var size = 1; // "f" and "i"
  12094. if ( attribute.type === "v2" ) size = 2;
  12095. else if ( attribute.type === "v3" ) size = 3;
  12096. else if ( attribute.type === "v4" ) size = 4;
  12097. else if ( attribute.type === "c" ) size = 3;
  12098. attribute.size = size;
  12099. attribute.array = new Float32Array( nvertices * size );
  12100. attribute.buffer = _gl.createBuffer();
  12101. attribute.buffer.belongsToAttribute = a;
  12102. attribute.needsUpdate = true;
  12103. }
  12104. geometry.__webglCustomAttributesList.push( attribute );
  12105. }
  12106. }
  12107. };
  12108. function initParticleBuffers ( geometry, object ) {
  12109. var nvertices = geometry.vertices.length;
  12110. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12111. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12112. geometry.__sortArray = [];
  12113. geometry.__webglParticleCount = nvertices;
  12114. initCustomAttributes ( geometry, object );
  12115. };
  12116. function initLineBuffers ( geometry, object ) {
  12117. var nvertices = geometry.vertices.length;
  12118. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12119. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12120. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12121. geometry.__webglLineCount = nvertices;
  12122. initCustomAttributes ( geometry, object );
  12123. };
  12124. function initMeshBuffers ( geometryGroup, object ) {
  12125. var geometry = object.geometry,
  12126. faces3 = geometryGroup.faces3,
  12127. nvertices = faces3.length * 3,
  12128. ntris = faces3.length * 1,
  12129. nlines = faces3.length * 3,
  12130. material = getBufferMaterial( object, geometryGroup ),
  12131. uvType = bufferGuessUVType( material ),
  12132. normalType = bufferGuessNormalType( material ),
  12133. vertexColorType = bufferGuessVertexColorType( material );
  12134. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12135. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12136. if ( normalType ) {
  12137. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12138. }
  12139. if ( geometry.hasTangents ) {
  12140. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12141. }
  12142. if ( vertexColorType ) {
  12143. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12144. }
  12145. if ( uvType ) {
  12146. if ( geometry.faceVertexUvs.length > 0 ) {
  12147. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12148. }
  12149. if ( geometry.faceVertexUvs.length > 1 ) {
  12150. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12151. }
  12152. }
  12153. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12154. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12155. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12156. }
  12157. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12158. geometryGroup.__typeArray = UintArray;
  12159. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12160. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12161. var m, ml;
  12162. if ( geometryGroup.numMorphTargets ) {
  12163. geometryGroup.__morphTargetsArrays = [];
  12164. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12165. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12166. }
  12167. }
  12168. if ( geometryGroup.numMorphNormals ) {
  12169. geometryGroup.__morphNormalsArrays = [];
  12170. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12171. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12172. }
  12173. }
  12174. geometryGroup.__webglFaceCount = ntris * 3;
  12175. geometryGroup.__webglLineCount = nlines * 2;
  12176. // custom attributes
  12177. if ( material.attributes ) {
  12178. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12179. geometryGroup.__webglCustomAttributesList = [];
  12180. }
  12181. for ( var a in material.attributes ) {
  12182. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12183. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12184. var originalAttribute = material.attributes[ a ];
  12185. var attribute = {};
  12186. for ( var property in originalAttribute ) {
  12187. attribute[ property ] = originalAttribute[ property ];
  12188. }
  12189. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12190. attribute.__webglInitialized = true;
  12191. var size = 1; // "f" and "i"
  12192. if( attribute.type === "v2" ) size = 2;
  12193. else if( attribute.type === "v3" ) size = 3;
  12194. else if( attribute.type === "v4" ) size = 4;
  12195. else if( attribute.type === "c" ) size = 3;
  12196. attribute.size = size;
  12197. attribute.array = new Float32Array( nvertices * size );
  12198. attribute.buffer = _gl.createBuffer();
  12199. attribute.buffer.belongsToAttribute = a;
  12200. originalAttribute.needsUpdate = true;
  12201. attribute.__original = originalAttribute;
  12202. }
  12203. geometryGroup.__webglCustomAttributesList.push( attribute );
  12204. }
  12205. }
  12206. geometryGroup.__inittedArrays = true;
  12207. };
  12208. function getBufferMaterial( object, geometryGroup ) {
  12209. return object.material instanceof THREE.MeshFaceMaterial
  12210. ? object.material.materials[ geometryGroup.materialIndex ]
  12211. : object.material;
  12212. };
  12213. function materialNeedsSmoothNormals ( material ) {
  12214. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12215. };
  12216. function bufferGuessNormalType ( material ) {
  12217. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12218. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12219. return false;
  12220. }
  12221. if ( materialNeedsSmoothNormals( material ) ) {
  12222. return THREE.SmoothShading;
  12223. } else {
  12224. return THREE.FlatShading;
  12225. }
  12226. };
  12227. function bufferGuessVertexColorType( material ) {
  12228. if ( material.vertexColors ) {
  12229. return material.vertexColors;
  12230. }
  12231. return false;
  12232. };
  12233. function bufferGuessUVType( material ) {
  12234. // material must use some texture to require uvs
  12235. if ( material.map ||
  12236. material.lightMap ||
  12237. material.bumpMap ||
  12238. material.normalMap ||
  12239. material.specularMap ||
  12240. material instanceof THREE.ShaderMaterial ) {
  12241. return true;
  12242. }
  12243. return false;
  12244. };
  12245. //
  12246. function initDirectBuffers( geometry ) {
  12247. for ( var name in geometry.attributes ) {
  12248. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12249. var attribute = geometry.attributes[ name ];
  12250. attribute.buffer = _gl.createBuffer();
  12251. _gl.bindBuffer( bufferType, attribute.buffer );
  12252. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12253. }
  12254. }
  12255. // Buffer setting
  12256. function setParticleBuffers ( geometry, hint, object ) {
  12257. var v, c, vertex, offset, index, color,
  12258. vertices = geometry.vertices,
  12259. vl = vertices.length,
  12260. colors = geometry.colors,
  12261. cl = colors.length,
  12262. vertexArray = geometry.__vertexArray,
  12263. colorArray = geometry.__colorArray,
  12264. sortArray = geometry.__sortArray,
  12265. dirtyVertices = geometry.verticesNeedUpdate,
  12266. dirtyElements = geometry.elementsNeedUpdate,
  12267. dirtyColors = geometry.colorsNeedUpdate,
  12268. customAttributes = geometry.__webglCustomAttributesList,
  12269. i, il,
  12270. a, ca, cal, value,
  12271. customAttribute;
  12272. if ( object.sortParticles ) {
  12273. _projScreenMatrixPS.copy( _projScreenMatrix );
  12274. _projScreenMatrixPS.multiply( object.matrixWorld );
  12275. for ( v = 0; v < vl; v ++ ) {
  12276. vertex = vertices[ v ];
  12277. _vector3.copy( vertex );
  12278. _vector3.applyProjection( _projScreenMatrixPS );
  12279. sortArray[ v ] = [ _vector3.z, v ];
  12280. }
  12281. sortArray.sort( numericalSort );
  12282. for ( v = 0; v < vl; v ++ ) {
  12283. vertex = vertices[ sortArray[v][1] ];
  12284. offset = v * 3;
  12285. vertexArray[ offset ] = vertex.x;
  12286. vertexArray[ offset + 1 ] = vertex.y;
  12287. vertexArray[ offset + 2 ] = vertex.z;
  12288. }
  12289. for ( c = 0; c < cl; c ++ ) {
  12290. offset = c * 3;
  12291. color = colors[ sortArray[c][1] ];
  12292. colorArray[ offset ] = color.r;
  12293. colorArray[ offset + 1 ] = color.g;
  12294. colorArray[ offset + 2 ] = color.b;
  12295. }
  12296. if ( customAttributes ) {
  12297. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12298. customAttribute = customAttributes[ i ];
  12299. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12300. offset = 0;
  12301. cal = customAttribute.value.length;
  12302. if ( customAttribute.size === 1 ) {
  12303. for ( ca = 0; ca < cal; ca ++ ) {
  12304. index = sortArray[ ca ][ 1 ];
  12305. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12306. }
  12307. } else if ( customAttribute.size === 2 ) {
  12308. for ( ca = 0; ca < cal; ca ++ ) {
  12309. index = sortArray[ ca ][ 1 ];
  12310. value = customAttribute.value[ index ];
  12311. customAttribute.array[ offset ] = value.x;
  12312. customAttribute.array[ offset + 1 ] = value.y;
  12313. offset += 2;
  12314. }
  12315. } else if ( customAttribute.size === 3 ) {
  12316. if ( customAttribute.type === "c" ) {
  12317. for ( ca = 0; ca < cal; ca ++ ) {
  12318. index = sortArray[ ca ][ 1 ];
  12319. value = customAttribute.value[ index ];
  12320. customAttribute.array[ offset ] = value.r;
  12321. customAttribute.array[ offset + 1 ] = value.g;
  12322. customAttribute.array[ offset + 2 ] = value.b;
  12323. offset += 3;
  12324. }
  12325. } else {
  12326. for ( ca = 0; ca < cal; ca ++ ) {
  12327. index = sortArray[ ca ][ 1 ];
  12328. value = customAttribute.value[ index ];
  12329. customAttribute.array[ offset ] = value.x;
  12330. customAttribute.array[ offset + 1 ] = value.y;
  12331. customAttribute.array[ offset + 2 ] = value.z;
  12332. offset += 3;
  12333. }
  12334. }
  12335. } else if ( customAttribute.size === 4 ) {
  12336. for ( ca = 0; ca < cal; ca ++ ) {
  12337. index = sortArray[ ca ][ 1 ];
  12338. value = customAttribute.value[ index ];
  12339. customAttribute.array[ offset ] = value.x;
  12340. customAttribute.array[ offset + 1 ] = value.y;
  12341. customAttribute.array[ offset + 2 ] = value.z;
  12342. customAttribute.array[ offset + 3 ] = value.w;
  12343. offset += 4;
  12344. }
  12345. }
  12346. }
  12347. }
  12348. } else {
  12349. if ( dirtyVertices ) {
  12350. for ( v = 0; v < vl; v ++ ) {
  12351. vertex = vertices[ v ];
  12352. offset = v * 3;
  12353. vertexArray[ offset ] = vertex.x;
  12354. vertexArray[ offset + 1 ] = vertex.y;
  12355. vertexArray[ offset + 2 ] = vertex.z;
  12356. }
  12357. }
  12358. if ( dirtyColors ) {
  12359. for ( c = 0; c < cl; c ++ ) {
  12360. color = colors[ c ];
  12361. offset = c * 3;
  12362. colorArray[ offset ] = color.r;
  12363. colorArray[ offset + 1 ] = color.g;
  12364. colorArray[ offset + 2 ] = color.b;
  12365. }
  12366. }
  12367. if ( customAttributes ) {
  12368. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12369. customAttribute = customAttributes[ i ];
  12370. if ( customAttribute.needsUpdate &&
  12371. ( customAttribute.boundTo === undefined ||
  12372. customAttribute.boundTo === "vertices") ) {
  12373. cal = customAttribute.value.length;
  12374. offset = 0;
  12375. if ( customAttribute.size === 1 ) {
  12376. for ( ca = 0; ca < cal; ca ++ ) {
  12377. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12378. }
  12379. } else if ( customAttribute.size === 2 ) {
  12380. for ( ca = 0; ca < cal; ca ++ ) {
  12381. value = customAttribute.value[ ca ];
  12382. customAttribute.array[ offset ] = value.x;
  12383. customAttribute.array[ offset + 1 ] = value.y;
  12384. offset += 2;
  12385. }
  12386. } else if ( customAttribute.size === 3 ) {
  12387. if ( customAttribute.type === "c" ) {
  12388. for ( ca = 0; ca < cal; ca ++ ) {
  12389. value = customAttribute.value[ ca ];
  12390. customAttribute.array[ offset ] = value.r;
  12391. customAttribute.array[ offset + 1 ] = value.g;
  12392. customAttribute.array[ offset + 2 ] = value.b;
  12393. offset += 3;
  12394. }
  12395. } else {
  12396. for ( ca = 0; ca < cal; ca ++ ) {
  12397. value = customAttribute.value[ ca ];
  12398. customAttribute.array[ offset ] = value.x;
  12399. customAttribute.array[ offset + 1 ] = value.y;
  12400. customAttribute.array[ offset + 2 ] = value.z;
  12401. offset += 3;
  12402. }
  12403. }
  12404. } else if ( customAttribute.size === 4 ) {
  12405. for ( ca = 0; ca < cal; ca ++ ) {
  12406. value = customAttribute.value[ ca ];
  12407. customAttribute.array[ offset ] = value.x;
  12408. customAttribute.array[ offset + 1 ] = value.y;
  12409. customAttribute.array[ offset + 2 ] = value.z;
  12410. customAttribute.array[ offset + 3 ] = value.w;
  12411. offset += 4;
  12412. }
  12413. }
  12414. }
  12415. }
  12416. }
  12417. }
  12418. if ( dirtyVertices || object.sortParticles ) {
  12419. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12420. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12421. }
  12422. if ( dirtyColors || object.sortParticles ) {
  12423. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12424. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12425. }
  12426. if ( customAttributes ) {
  12427. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12428. customAttribute = customAttributes[ i ];
  12429. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12430. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12431. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12432. }
  12433. }
  12434. }
  12435. }
  12436. function setLineBuffers ( geometry, hint ) {
  12437. var v, c, d, vertex, offset, color,
  12438. vertices = geometry.vertices,
  12439. colors = geometry.colors,
  12440. lineDistances = geometry.lineDistances,
  12441. vl = vertices.length,
  12442. cl = colors.length,
  12443. dl = lineDistances.length,
  12444. vertexArray = geometry.__vertexArray,
  12445. colorArray = geometry.__colorArray,
  12446. lineDistanceArray = geometry.__lineDistanceArray,
  12447. dirtyVertices = geometry.verticesNeedUpdate,
  12448. dirtyColors = geometry.colorsNeedUpdate,
  12449. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12450. customAttributes = geometry.__webglCustomAttributesList,
  12451. i, il,
  12452. a, ca, cal, value,
  12453. customAttribute;
  12454. if ( dirtyVertices ) {
  12455. for ( v = 0; v < vl; v ++ ) {
  12456. vertex = vertices[ v ];
  12457. offset = v * 3;
  12458. vertexArray[ offset ] = vertex.x;
  12459. vertexArray[ offset + 1 ] = vertex.y;
  12460. vertexArray[ offset + 2 ] = vertex.z;
  12461. }
  12462. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12463. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12464. }
  12465. if ( dirtyColors ) {
  12466. for ( c = 0; c < cl; c ++ ) {
  12467. color = colors[ c ];
  12468. offset = c * 3;
  12469. colorArray[ offset ] = color.r;
  12470. colorArray[ offset + 1 ] = color.g;
  12471. colorArray[ offset + 2 ] = color.b;
  12472. }
  12473. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12474. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12475. }
  12476. if ( dirtyLineDistances ) {
  12477. for ( d = 0; d < dl; d ++ ) {
  12478. lineDistanceArray[ d ] = lineDistances[ d ];
  12479. }
  12480. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12481. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12482. }
  12483. if ( customAttributes ) {
  12484. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12485. customAttribute = customAttributes[ i ];
  12486. if ( customAttribute.needsUpdate &&
  12487. ( customAttribute.boundTo === undefined ||
  12488. customAttribute.boundTo === "vertices" ) ) {
  12489. offset = 0;
  12490. cal = customAttribute.value.length;
  12491. if ( customAttribute.size === 1 ) {
  12492. for ( ca = 0; ca < cal; ca ++ ) {
  12493. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12494. }
  12495. } else if ( customAttribute.size === 2 ) {
  12496. for ( ca = 0; ca < cal; ca ++ ) {
  12497. value = customAttribute.value[ ca ];
  12498. customAttribute.array[ offset ] = value.x;
  12499. customAttribute.array[ offset + 1 ] = value.y;
  12500. offset += 2;
  12501. }
  12502. } else if ( customAttribute.size === 3 ) {
  12503. if ( customAttribute.type === "c" ) {
  12504. for ( ca = 0; ca < cal; ca ++ ) {
  12505. value = customAttribute.value[ ca ];
  12506. customAttribute.array[ offset ] = value.r;
  12507. customAttribute.array[ offset + 1 ] = value.g;
  12508. customAttribute.array[ offset + 2 ] = value.b;
  12509. offset += 3;
  12510. }
  12511. } else {
  12512. for ( ca = 0; ca < cal; ca ++ ) {
  12513. value = customAttribute.value[ ca ];
  12514. customAttribute.array[ offset ] = value.x;
  12515. customAttribute.array[ offset + 1 ] = value.y;
  12516. customAttribute.array[ offset + 2 ] = value.z;
  12517. offset += 3;
  12518. }
  12519. }
  12520. } else if ( customAttribute.size === 4 ) {
  12521. for ( ca = 0; ca < cal; ca ++ ) {
  12522. value = customAttribute.value[ ca ];
  12523. customAttribute.array[ offset ] = value.x;
  12524. customAttribute.array[ offset + 1 ] = value.y;
  12525. customAttribute.array[ offset + 2 ] = value.z;
  12526. customAttribute.array[ offset + 3 ] = value.w;
  12527. offset += 4;
  12528. }
  12529. }
  12530. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12531. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12532. }
  12533. }
  12534. }
  12535. }
  12536. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12537. if ( ! geometryGroup.__inittedArrays ) {
  12538. return;
  12539. }
  12540. var normalType = bufferGuessNormalType( material ),
  12541. vertexColorType = bufferGuessVertexColorType( material ),
  12542. uvType = bufferGuessUVType( material ),
  12543. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12544. var f, fl, fi, face,
  12545. vertexNormals, faceNormal, normal,
  12546. vertexColors, faceColor,
  12547. vertexTangents,
  12548. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12549. c1, c2, c3, c4,
  12550. sw1, sw2, sw3, sw4,
  12551. si1, si2, si3, si4,
  12552. sa1, sa2, sa3, sa4,
  12553. sb1, sb2, sb3, sb4,
  12554. m, ml, i, il,
  12555. vn, uvi, uv2i,
  12556. vk, vkl, vka,
  12557. nka, chf, faceVertexNormals,
  12558. a,
  12559. vertexIndex = 0,
  12560. offset = 0,
  12561. offset_uv = 0,
  12562. offset_uv2 = 0,
  12563. offset_face = 0,
  12564. offset_normal = 0,
  12565. offset_tangent = 0,
  12566. offset_line = 0,
  12567. offset_color = 0,
  12568. offset_skin = 0,
  12569. offset_morphTarget = 0,
  12570. offset_custom = 0,
  12571. offset_customSrc = 0,
  12572. value,
  12573. vertexArray = geometryGroup.__vertexArray,
  12574. uvArray = geometryGroup.__uvArray,
  12575. uv2Array = geometryGroup.__uv2Array,
  12576. normalArray = geometryGroup.__normalArray,
  12577. tangentArray = geometryGroup.__tangentArray,
  12578. colorArray = geometryGroup.__colorArray,
  12579. skinIndexArray = geometryGroup.__skinIndexArray,
  12580. skinWeightArray = geometryGroup.__skinWeightArray,
  12581. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12582. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12583. customAttributes = geometryGroup.__webglCustomAttributesList,
  12584. customAttribute,
  12585. faceArray = geometryGroup.__faceArray,
  12586. lineArray = geometryGroup.__lineArray,
  12587. geometry = object.geometry, // this is shared for all chunks
  12588. dirtyVertices = geometry.verticesNeedUpdate,
  12589. dirtyElements = geometry.elementsNeedUpdate,
  12590. dirtyUvs = geometry.uvsNeedUpdate,
  12591. dirtyNormals = geometry.normalsNeedUpdate,
  12592. dirtyTangents = geometry.tangentsNeedUpdate,
  12593. dirtyColors = geometry.colorsNeedUpdate,
  12594. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12595. vertices = geometry.vertices,
  12596. chunk_faces3 = geometryGroup.faces3,
  12597. obj_faces = geometry.faces,
  12598. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12599. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12600. obj_colors = geometry.colors,
  12601. obj_skinIndices = geometry.skinIndices,
  12602. obj_skinWeights = geometry.skinWeights,
  12603. morphTargets = geometry.morphTargets,
  12604. morphNormals = geometry.morphNormals;
  12605. if ( dirtyVertices ) {
  12606. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12607. face = obj_faces[ chunk_faces3[ f ] ];
  12608. v1 = vertices[ face.a ];
  12609. v2 = vertices[ face.b ];
  12610. v3 = vertices[ face.c ];
  12611. vertexArray[ offset ] = v1.x;
  12612. vertexArray[ offset + 1 ] = v1.y;
  12613. vertexArray[ offset + 2 ] = v1.z;
  12614. vertexArray[ offset + 3 ] = v2.x;
  12615. vertexArray[ offset + 4 ] = v2.y;
  12616. vertexArray[ offset + 5 ] = v2.z;
  12617. vertexArray[ offset + 6 ] = v3.x;
  12618. vertexArray[ offset + 7 ] = v3.y;
  12619. vertexArray[ offset + 8 ] = v3.z;
  12620. offset += 9;
  12621. }
  12622. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12623. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12624. }
  12625. if ( dirtyMorphTargets ) {
  12626. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12627. offset_morphTarget = 0;
  12628. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12629. chf = chunk_faces3[ f ];
  12630. face = obj_faces[ chf ];
  12631. // morph positions
  12632. v1 = morphTargets[ vk ].vertices[ face.a ];
  12633. v2 = morphTargets[ vk ].vertices[ face.b ];
  12634. v3 = morphTargets[ vk ].vertices[ face.c ];
  12635. vka = morphTargetsArrays[ vk ];
  12636. vka[ offset_morphTarget ] = v1.x;
  12637. vka[ offset_morphTarget + 1 ] = v1.y;
  12638. vka[ offset_morphTarget + 2 ] = v1.z;
  12639. vka[ offset_morphTarget + 3 ] = v2.x;
  12640. vka[ offset_morphTarget + 4 ] = v2.y;
  12641. vka[ offset_morphTarget + 5 ] = v2.z;
  12642. vka[ offset_morphTarget + 6 ] = v3.x;
  12643. vka[ offset_morphTarget + 7 ] = v3.y;
  12644. vka[ offset_morphTarget + 8 ] = v3.z;
  12645. // morph normals
  12646. if ( material.morphNormals ) {
  12647. if ( needsSmoothNormals ) {
  12648. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12649. n1 = faceVertexNormals.a;
  12650. n2 = faceVertexNormals.b;
  12651. n3 = faceVertexNormals.c;
  12652. } else {
  12653. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12654. n2 = n1;
  12655. n3 = n1;
  12656. }
  12657. nka = morphNormalsArrays[ vk ];
  12658. nka[ offset_morphTarget ] = n1.x;
  12659. nka[ offset_morphTarget + 1 ] = n1.y;
  12660. nka[ offset_morphTarget + 2 ] = n1.z;
  12661. nka[ offset_morphTarget + 3 ] = n2.x;
  12662. nka[ offset_morphTarget + 4 ] = n2.y;
  12663. nka[ offset_morphTarget + 5 ] = n2.z;
  12664. nka[ offset_morphTarget + 6 ] = n3.x;
  12665. nka[ offset_morphTarget + 7 ] = n3.y;
  12666. nka[ offset_morphTarget + 8 ] = n3.z;
  12667. }
  12668. //
  12669. offset_morphTarget += 9;
  12670. }
  12671. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12672. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12673. if ( material.morphNormals ) {
  12674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12675. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12676. }
  12677. }
  12678. }
  12679. if ( obj_skinWeights.length ) {
  12680. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12681. face = obj_faces[ chunk_faces3[ f ] ];
  12682. // weights
  12683. sw1 = obj_skinWeights[ face.a ];
  12684. sw2 = obj_skinWeights[ face.b ];
  12685. sw3 = obj_skinWeights[ face.c ];
  12686. skinWeightArray[ offset_skin ] = sw1.x;
  12687. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12688. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12689. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12690. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12691. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12692. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12693. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12694. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12695. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12696. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12697. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12698. // indices
  12699. si1 = obj_skinIndices[ face.a ];
  12700. si2 = obj_skinIndices[ face.b ];
  12701. si3 = obj_skinIndices[ face.c ];
  12702. skinIndexArray[ offset_skin ] = si1.x;
  12703. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12704. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12705. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12706. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12707. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12708. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12709. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12710. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12711. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12712. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12713. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12714. offset_skin += 12;
  12715. }
  12716. if ( offset_skin > 0 ) {
  12717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12718. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12719. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12720. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12721. }
  12722. }
  12723. if ( dirtyColors && vertexColorType ) {
  12724. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12725. face = obj_faces[ chunk_faces3[ f ] ];
  12726. vertexColors = face.vertexColors;
  12727. faceColor = face.color;
  12728. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12729. c1 = vertexColors[ 0 ];
  12730. c2 = vertexColors[ 1 ];
  12731. c3 = vertexColors[ 2 ];
  12732. } else {
  12733. c1 = faceColor;
  12734. c2 = faceColor;
  12735. c3 = faceColor;
  12736. }
  12737. colorArray[ offset_color ] = c1.r;
  12738. colorArray[ offset_color + 1 ] = c1.g;
  12739. colorArray[ offset_color + 2 ] = c1.b;
  12740. colorArray[ offset_color + 3 ] = c2.r;
  12741. colorArray[ offset_color + 4 ] = c2.g;
  12742. colorArray[ offset_color + 5 ] = c2.b;
  12743. colorArray[ offset_color + 6 ] = c3.r;
  12744. colorArray[ offset_color + 7 ] = c3.g;
  12745. colorArray[ offset_color + 8 ] = c3.b;
  12746. offset_color += 9;
  12747. }
  12748. if ( offset_color > 0 ) {
  12749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12750. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12751. }
  12752. }
  12753. if ( dirtyTangents && geometry.hasTangents ) {
  12754. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12755. face = obj_faces[ chunk_faces3[ f ] ];
  12756. vertexTangents = face.vertexTangents;
  12757. t1 = vertexTangents[ 0 ];
  12758. t2 = vertexTangents[ 1 ];
  12759. t3 = vertexTangents[ 2 ];
  12760. tangentArray[ offset_tangent ] = t1.x;
  12761. tangentArray[ offset_tangent + 1 ] = t1.y;
  12762. tangentArray[ offset_tangent + 2 ] = t1.z;
  12763. tangentArray[ offset_tangent + 3 ] = t1.w;
  12764. tangentArray[ offset_tangent + 4 ] = t2.x;
  12765. tangentArray[ offset_tangent + 5 ] = t2.y;
  12766. tangentArray[ offset_tangent + 6 ] = t2.z;
  12767. tangentArray[ offset_tangent + 7 ] = t2.w;
  12768. tangentArray[ offset_tangent + 8 ] = t3.x;
  12769. tangentArray[ offset_tangent + 9 ] = t3.y;
  12770. tangentArray[ offset_tangent + 10 ] = t3.z;
  12771. tangentArray[ offset_tangent + 11 ] = t3.w;
  12772. offset_tangent += 12;
  12773. }
  12774. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12775. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12776. }
  12777. if ( dirtyNormals && normalType ) {
  12778. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12779. face = obj_faces[ chunk_faces3[ f ] ];
  12780. vertexNormals = face.vertexNormals;
  12781. faceNormal = face.normal;
  12782. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12783. for ( i = 0; i < 3; i ++ ) {
  12784. vn = vertexNormals[ i ];
  12785. normalArray[ offset_normal ] = vn.x;
  12786. normalArray[ offset_normal + 1 ] = vn.y;
  12787. normalArray[ offset_normal + 2 ] = vn.z;
  12788. offset_normal += 3;
  12789. }
  12790. } else {
  12791. for ( i = 0; i < 3; i ++ ) {
  12792. normalArray[ offset_normal ] = faceNormal.x;
  12793. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12794. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12795. offset_normal += 3;
  12796. }
  12797. }
  12798. }
  12799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12800. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12801. }
  12802. if ( dirtyUvs && obj_uvs && uvType ) {
  12803. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12804. fi = chunk_faces3[ f ];
  12805. uv = obj_uvs[ fi ];
  12806. if ( uv === undefined ) continue;
  12807. for ( i = 0; i < 3; i ++ ) {
  12808. uvi = uv[ i ];
  12809. uvArray[ offset_uv ] = uvi.x;
  12810. uvArray[ offset_uv + 1 ] = uvi.y;
  12811. offset_uv += 2;
  12812. }
  12813. }
  12814. if ( offset_uv > 0 ) {
  12815. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12816. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12817. }
  12818. }
  12819. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12820. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12821. fi = chunk_faces3[ f ];
  12822. uv2 = obj_uvs2[ fi ];
  12823. if ( uv2 === undefined ) continue;
  12824. for ( i = 0; i < 3; i ++ ) {
  12825. uv2i = uv2[ i ];
  12826. uv2Array[ offset_uv2 ] = uv2i.x;
  12827. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12828. offset_uv2 += 2;
  12829. }
  12830. }
  12831. if ( offset_uv2 > 0 ) {
  12832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12833. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12834. }
  12835. }
  12836. if ( dirtyElements ) {
  12837. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12838. faceArray[ offset_face ] = vertexIndex;
  12839. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12840. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12841. offset_face += 3;
  12842. lineArray[ offset_line ] = vertexIndex;
  12843. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12844. lineArray[ offset_line + 2 ] = vertexIndex;
  12845. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12846. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12847. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12848. offset_line += 6;
  12849. vertexIndex += 3;
  12850. }
  12851. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12852. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12853. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12854. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12855. }
  12856. if ( customAttributes ) {
  12857. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12858. customAttribute = customAttributes[ i ];
  12859. if ( ! customAttribute.__original.needsUpdate ) continue;
  12860. offset_custom = 0;
  12861. offset_customSrc = 0;
  12862. if ( customAttribute.size === 1 ) {
  12863. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12864. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12865. face = obj_faces[ chunk_faces3[ f ] ];
  12866. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12867. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12868. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12869. offset_custom += 3;
  12870. }
  12871. } else if ( customAttribute.boundTo === "faces" ) {
  12872. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12873. value = customAttribute.value[ chunk_faces3[ f ] ];
  12874. customAttribute.array[ offset_custom ] = value;
  12875. customAttribute.array[ offset_custom + 1 ] = value;
  12876. customAttribute.array[ offset_custom + 2 ] = value;
  12877. offset_custom += 3;
  12878. }
  12879. }
  12880. } else if ( customAttribute.size === 2 ) {
  12881. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12882. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12883. face = obj_faces[ chunk_faces3[ f ] ];
  12884. v1 = customAttribute.value[ face.a ];
  12885. v2 = customAttribute.value[ face.b ];
  12886. v3 = customAttribute.value[ face.c ];
  12887. customAttribute.array[ offset_custom ] = v1.x;
  12888. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12889. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12890. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12891. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12892. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12893. offset_custom += 6;
  12894. }
  12895. } else if ( customAttribute.boundTo === "faces" ) {
  12896. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12897. value = customAttribute.value[ chunk_faces3[ f ] ];
  12898. v1 = value;
  12899. v2 = value;
  12900. v3 = value;
  12901. customAttribute.array[ offset_custom ] = v1.x;
  12902. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12903. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12904. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12905. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12906. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12907. offset_custom += 6;
  12908. }
  12909. }
  12910. } else if ( customAttribute.size === 3 ) {
  12911. var pp;
  12912. if ( customAttribute.type === "c" ) {
  12913. pp = [ "r", "g", "b" ];
  12914. } else {
  12915. pp = [ "x", "y", "z" ];
  12916. }
  12917. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12918. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12919. face = obj_faces[ chunk_faces3[ f ] ];
  12920. v1 = customAttribute.value[ face.a ];
  12921. v2 = customAttribute.value[ face.b ];
  12922. v3 = customAttribute.value[ face.c ];
  12923. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12924. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12925. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12926. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12927. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12928. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12929. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12930. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12931. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12932. offset_custom += 9;
  12933. }
  12934. } else if ( customAttribute.boundTo === "faces" ) {
  12935. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12936. value = customAttribute.value[ chunk_faces3[ f ] ];
  12937. v1 = value;
  12938. v2 = value;
  12939. v3 = value;
  12940. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12941. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12942. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12943. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12944. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12945. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12946. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12947. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12948. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12949. offset_custom += 9;
  12950. }
  12951. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12952. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12953. value = customAttribute.value[ chunk_faces3[ f ] ];
  12954. v1 = value[ 0 ];
  12955. v2 = value[ 1 ];
  12956. v3 = value[ 2 ];
  12957. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12958. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12959. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12960. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12961. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12962. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12963. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12964. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12965. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12966. offset_custom += 9;
  12967. }
  12968. }
  12969. } else if ( customAttribute.size === 4 ) {
  12970. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12971. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12972. face = obj_faces[ chunk_faces3[ f ] ];
  12973. v1 = customAttribute.value[ face.a ];
  12974. v2 = customAttribute.value[ face.b ];
  12975. v3 = customAttribute.value[ face.c ];
  12976. customAttribute.array[ offset_custom ] = v1.x;
  12977. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12978. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12979. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12980. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12981. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12982. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12983. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12984. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12985. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12986. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12987. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12988. offset_custom += 12;
  12989. }
  12990. } else if ( customAttribute.boundTo === "faces" ) {
  12991. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12992. value = customAttribute.value[ chunk_faces3[ f ] ];
  12993. v1 = value;
  12994. v2 = value;
  12995. v3 = value;
  12996. customAttribute.array[ offset_custom ] = v1.x;
  12997. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12998. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12999. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13000. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13001. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13002. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13003. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13004. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13005. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13006. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13007. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13008. offset_custom += 12;
  13009. }
  13010. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13011. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13012. value = customAttribute.value[ chunk_faces3[ f ] ];
  13013. v1 = value[ 0 ];
  13014. v2 = value[ 1 ];
  13015. v3 = value[ 2 ];
  13016. customAttribute.array[ offset_custom ] = v1.x;
  13017. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13018. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13019. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13020. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13021. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13022. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13023. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13024. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13025. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13026. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13027. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13028. offset_custom += 12;
  13029. }
  13030. }
  13031. }
  13032. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13033. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13034. }
  13035. }
  13036. if ( dispose ) {
  13037. delete geometryGroup.__inittedArrays;
  13038. delete geometryGroup.__colorArray;
  13039. delete geometryGroup.__normalArray;
  13040. delete geometryGroup.__tangentArray;
  13041. delete geometryGroup.__uvArray;
  13042. delete geometryGroup.__uv2Array;
  13043. delete geometryGroup.__faceArray;
  13044. delete geometryGroup.__vertexArray;
  13045. delete geometryGroup.__lineArray;
  13046. delete geometryGroup.__skinIndexArray;
  13047. delete geometryGroup.__skinWeightArray;
  13048. }
  13049. };
  13050. function setDirectBuffers( geometry, hint ) {
  13051. var attributes = geometry.attributes;
  13052. var attributeName, attributeItem;
  13053. for ( attributeName in attributes ) {
  13054. attributeItem = attributes[ attributeName ];
  13055. if ( attributeItem.needsUpdate ) {
  13056. if ( attributeName === 'index' ) {
  13057. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13058. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13059. } else {
  13060. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13061. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13062. }
  13063. attributeItem.needsUpdate = false;
  13064. }
  13065. }
  13066. }
  13067. // Buffer rendering
  13068. this.renderBufferImmediate = function ( object, program, material ) {
  13069. initAttributes();
  13070. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13071. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13072. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13073. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13074. if ( object.hasPositions ) {
  13075. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13076. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13077. enableAttribute( program.attributes.position );
  13078. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13079. }
  13080. if ( object.hasNormals ) {
  13081. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13082. if ( material.shading === THREE.FlatShading ) {
  13083. var nx, ny, nz,
  13084. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13085. normalArray,
  13086. i, il = object.count * 3;
  13087. for( i = 0; i < il; i += 9 ) {
  13088. normalArray = object.normalArray;
  13089. nax = normalArray[ i ];
  13090. nay = normalArray[ i + 1 ];
  13091. naz = normalArray[ i + 2 ];
  13092. nbx = normalArray[ i + 3 ];
  13093. nby = normalArray[ i + 4 ];
  13094. nbz = normalArray[ i + 5 ];
  13095. ncx = normalArray[ i + 6 ];
  13096. ncy = normalArray[ i + 7 ];
  13097. ncz = normalArray[ i + 8 ];
  13098. nx = ( nax + nbx + ncx ) / 3;
  13099. ny = ( nay + nby + ncy ) / 3;
  13100. nz = ( naz + nbz + ncz ) / 3;
  13101. normalArray[ i ] = nx;
  13102. normalArray[ i + 1 ] = ny;
  13103. normalArray[ i + 2 ] = nz;
  13104. normalArray[ i + 3 ] = nx;
  13105. normalArray[ i + 4 ] = ny;
  13106. normalArray[ i + 5 ] = nz;
  13107. normalArray[ i + 6 ] = nx;
  13108. normalArray[ i + 7 ] = ny;
  13109. normalArray[ i + 8 ] = nz;
  13110. }
  13111. }
  13112. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13113. enableAttribute( program.attributes.normal );
  13114. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13115. }
  13116. if ( object.hasUvs && material.map ) {
  13117. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13118. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13119. enableAttribute( program.attributes.uv );
  13120. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13121. }
  13122. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13123. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13124. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13125. enableAttribute( program.attributes.color );
  13126. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13127. }
  13128. disableUnusedAttributes();
  13129. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13130. object.count = 0;
  13131. };
  13132. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13133. for ( var attributeName in programAttributes ) {
  13134. var attributePointer = programAttributes[ attributeName ];
  13135. var attributeItem = geometryAttributes[ attributeName ];
  13136. if ( attributePointer >= 0 ) {
  13137. if ( attributeItem ) {
  13138. var attributeSize = attributeItem.itemSize;
  13139. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13140. enableAttribute( attributePointer );
  13141. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13142. } else if ( material.defaultAttributeValues ) {
  13143. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13144. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13145. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13146. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13147. }
  13148. }
  13149. }
  13150. }
  13151. disableUnusedAttributes();
  13152. }
  13153. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13154. if ( material.visible === false ) return;
  13155. var linewidth, a, attribute;
  13156. var attributeItem, attributeName, attributePointer, attributeSize;
  13157. var program = setProgram( camera, lights, fog, material, object );
  13158. var programAttributes = program.attributes;
  13159. var geometryAttributes = geometry.attributes;
  13160. var updateBuffers = false,
  13161. wireframeBit = material.wireframe ? 1 : 0,
  13162. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13163. if ( geometryHash !== _currentGeometryGroupHash ) {
  13164. _currentGeometryGroupHash = geometryHash;
  13165. updateBuffers = true;
  13166. }
  13167. if ( updateBuffers ) {
  13168. initAttributes();
  13169. }
  13170. // render mesh
  13171. if ( object instanceof THREE.Mesh ) {
  13172. var index = geometryAttributes[ "index" ];
  13173. if ( index ) {
  13174. // indexed triangles
  13175. var type, size;
  13176. if ( index.array instanceof Uint32Array ) {
  13177. type = _gl.UNSIGNED_INT;
  13178. size = 4;
  13179. } else {
  13180. type = _gl.UNSIGNED_SHORT;
  13181. size = 2;
  13182. }
  13183. var offsets = geometry.offsets;
  13184. if ( offsets.length === 0 ) {
  13185. if ( updateBuffers ) {
  13186. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13187. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13188. }
  13189. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13190. _this.info.render.calls ++;
  13191. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13192. _this.info.render.faces += index.array.length / 3;
  13193. } else {
  13194. // if there is more than 1 chunk
  13195. // must set attribute pointers to use new offsets for each chunk
  13196. // even if geometry and materials didn't change
  13197. updateBuffers = true;
  13198. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13199. var startIndex = offsets[ i ].index;
  13200. if ( updateBuffers ) {
  13201. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13202. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13203. }
  13204. // render indexed triangles
  13205. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13206. _this.info.render.calls ++;
  13207. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13208. _this.info.render.faces += offsets[ i ].count / 3;
  13209. }
  13210. }
  13211. } else {
  13212. // non-indexed triangles
  13213. if ( updateBuffers ) {
  13214. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13215. }
  13216. var position = geometry.attributes[ "position" ];
  13217. // render non-indexed triangles
  13218. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13219. _this.info.render.calls ++;
  13220. _this.info.render.vertices += position.array.length / 3;
  13221. _this.info.render.faces += position.array.length / 9;
  13222. }
  13223. } else if ( object instanceof THREE.PointCloud ) {
  13224. // render particles
  13225. if ( updateBuffers ) {
  13226. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13227. }
  13228. var position = geometryAttributes[ "position" ];
  13229. // render particles
  13230. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13231. _this.info.render.calls ++;
  13232. _this.info.render.points += position.array.length / 3;
  13233. } else if ( object instanceof THREE.Line ) {
  13234. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13235. setLineWidth( material.linewidth );
  13236. var index = geometryAttributes[ "index" ];
  13237. if ( index ) {
  13238. // indexed lines
  13239. var type, size;
  13240. if ( index.array instanceof Uint32Array ){
  13241. type = _gl.UNSIGNED_INT;
  13242. size = 4;
  13243. } else {
  13244. type = _gl.UNSIGNED_SHORT;
  13245. size = 2;
  13246. }
  13247. var offsets = geometry.offsets;
  13248. if ( offsets.length === 0 ) {
  13249. if ( updateBuffers ) {
  13250. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13251. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13252. }
  13253. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13254. _this.info.render.calls ++;
  13255. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13256. } else {
  13257. // if there is more than 1 chunk
  13258. // must set attribute pointers to use new offsets for each chunk
  13259. // even if geometry and materials didn't change
  13260. if ( offsets.length > 1 ) updateBuffers = true;
  13261. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13262. var startIndex = offsets[ i ].index;
  13263. if ( updateBuffers ) {
  13264. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13265. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13266. }
  13267. // render indexed lines
  13268. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13269. _this.info.render.calls ++;
  13270. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13271. }
  13272. }
  13273. } else {
  13274. // non-indexed lines
  13275. if ( updateBuffers ) {
  13276. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13277. }
  13278. var position = geometryAttributes[ "position" ];
  13279. _gl.drawArrays( mode, 0, position.array.length / 3 );
  13280. _this.info.render.calls ++;
  13281. _this.info.render.points += position.array.length / 3;
  13282. }
  13283. }
  13284. };
  13285. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13286. if ( material.visible === false ) return;
  13287. var linewidth, a, attribute, i, il;
  13288. var program = setProgram( camera, lights, fog, material, object );
  13289. var attributes = program.attributes;
  13290. var updateBuffers = false,
  13291. wireframeBit = material.wireframe ? 1 : 0,
  13292. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13293. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13294. _currentGeometryGroupHash = geometryGroupHash;
  13295. updateBuffers = true;
  13296. }
  13297. if ( updateBuffers ) {
  13298. initAttributes();
  13299. }
  13300. // vertices
  13301. if ( !material.morphTargets && attributes.position >= 0 ) {
  13302. if ( updateBuffers ) {
  13303. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13304. enableAttribute( attributes.position );
  13305. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13306. }
  13307. } else {
  13308. if ( object.morphTargetBase ) {
  13309. setupMorphTargets( material, geometryGroup, object );
  13310. }
  13311. }
  13312. if ( updateBuffers ) {
  13313. // custom attributes
  13314. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13315. if ( geometryGroup.__webglCustomAttributesList ) {
  13316. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13317. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13318. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13319. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13320. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13321. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13322. }
  13323. }
  13324. }
  13325. // colors
  13326. if ( attributes.color >= 0 ) {
  13327. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13328. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13329. enableAttribute( attributes.color );
  13330. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13331. } else if ( material.defaultAttributeValues ) {
  13332. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13333. }
  13334. }
  13335. // normals
  13336. if ( attributes.normal >= 0 ) {
  13337. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13338. enableAttribute( attributes.normal );
  13339. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13340. }
  13341. // tangents
  13342. if ( attributes.tangent >= 0 ) {
  13343. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13344. enableAttribute( attributes.tangent );
  13345. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13346. }
  13347. // uvs
  13348. if ( attributes.uv >= 0 ) {
  13349. if ( object.geometry.faceVertexUvs[0] ) {
  13350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13351. enableAttribute( attributes.uv );
  13352. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13353. } else if ( material.defaultAttributeValues ) {
  13354. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13355. }
  13356. }
  13357. if ( attributes.uv2 >= 0 ) {
  13358. if ( object.geometry.faceVertexUvs[1] ) {
  13359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13360. enableAttribute( attributes.uv2 );
  13361. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13362. } else if ( material.defaultAttributeValues ) {
  13363. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13364. }
  13365. }
  13366. if ( material.skinning &&
  13367. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13368. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13369. enableAttribute( attributes.skinIndex );
  13370. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13371. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13372. enableAttribute( attributes.skinWeight );
  13373. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13374. }
  13375. // line distances
  13376. if ( attributes.lineDistance >= 0 ) {
  13377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13378. enableAttribute( attributes.lineDistance );
  13379. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13380. }
  13381. }
  13382. disableUnusedAttributes();
  13383. // render mesh
  13384. if ( object instanceof THREE.Mesh ) {
  13385. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13386. // wireframe
  13387. if ( material.wireframe ) {
  13388. setLineWidth( material.wireframeLinewidth );
  13389. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13390. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13391. // triangles
  13392. } else {
  13393. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13394. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13395. }
  13396. _this.info.render.calls ++;
  13397. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13398. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13399. // render lines
  13400. } else if ( object instanceof THREE.Line ) {
  13401. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13402. setLineWidth( material.linewidth );
  13403. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  13404. _this.info.render.calls ++;
  13405. // render particles
  13406. } else if ( object instanceof THREE.PointCloud ) {
  13407. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13408. _this.info.render.calls ++;
  13409. _this.info.render.points += geometryGroup.__webglParticleCount;
  13410. }
  13411. };
  13412. function initAttributes() {
  13413. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13414. _newAttributes[ i ] = 0;
  13415. }
  13416. }
  13417. function enableAttribute( attribute ) {
  13418. _newAttributes[ attribute ] = 1;
  13419. if ( _enabledAttributes[ attribute ] === 0 ) {
  13420. _gl.enableVertexAttribArray( attribute );
  13421. _enabledAttributes[ attribute ] = 1;
  13422. }
  13423. }
  13424. function disableUnusedAttributes() {
  13425. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13426. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13427. _gl.disableVertexAttribArray( i );
  13428. _enabledAttributes[ i ] = 0;
  13429. }
  13430. }
  13431. }
  13432. function setupMorphTargets ( material, geometryGroup, object ) {
  13433. // set base
  13434. var attributes = material.program.attributes;
  13435. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13436. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13437. enableAttribute( attributes.position );
  13438. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13439. } else if ( attributes.position >= 0 ) {
  13440. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13441. enableAttribute( attributes.position );
  13442. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13443. }
  13444. if ( object.morphTargetForcedOrder.length ) {
  13445. // set forced order
  13446. var m = 0;
  13447. var order = object.morphTargetForcedOrder;
  13448. var influences = object.morphTargetInfluences;
  13449. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13450. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13451. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13452. enableAttribute( attributes[ "morphTarget" + m ] );
  13453. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13454. }
  13455. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13456. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13457. enableAttribute( attributes[ "morphNormal" + m ] );
  13458. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13459. }
  13460. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13461. m ++;
  13462. }
  13463. } else {
  13464. // find the most influencing
  13465. var influence, activeInfluenceIndices = [];
  13466. var influences = object.morphTargetInfluences;
  13467. var i, il = influences.length;
  13468. for ( i = 0; i < il; i ++ ) {
  13469. influence = influences[ i ];
  13470. if ( influence > 0 ) {
  13471. activeInfluenceIndices.push( [ influence, i ] );
  13472. }
  13473. }
  13474. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13475. activeInfluenceIndices.sort( numericalSort );
  13476. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13477. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13478. activeInfluenceIndices.sort( numericalSort );
  13479. } else if ( activeInfluenceIndices.length === 0 ) {
  13480. activeInfluenceIndices.push( [ 0, 0 ] );
  13481. };
  13482. var influenceIndex, m = 0;
  13483. while ( m < material.numSupportedMorphTargets ) {
  13484. if ( activeInfluenceIndices[ m ] ) {
  13485. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13486. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13487. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13488. enableAttribute( attributes[ "morphTarget" + m ] );
  13489. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13490. }
  13491. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13492. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13493. enableAttribute( attributes[ "morphNormal" + m ] );
  13494. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13495. }
  13496. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13497. } else {
  13498. /*
  13499. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13500. if ( material.morphNormals ) {
  13501. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13502. }
  13503. */
  13504. object.__webglMorphTargetInfluences[ m ] = 0;
  13505. }
  13506. m ++;
  13507. }
  13508. }
  13509. // load updated influences uniform
  13510. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13511. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13512. }
  13513. };
  13514. // Sorting
  13515. function painterSortStable ( a, b ) {
  13516. if ( a.z !== b.z ) {
  13517. return b.z - a.z;
  13518. } else {
  13519. return a.id - b.id;
  13520. }
  13521. };
  13522. function numericalSort ( a, b ) {
  13523. return b[ 0 ] - a[ 0 ];
  13524. };
  13525. // Rendering
  13526. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13527. if ( camera instanceof THREE.Camera === false ) {
  13528. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13529. return;
  13530. }
  13531. var i, il,
  13532. webglObject, object,
  13533. renderList,
  13534. lights = scene.__lights,
  13535. fog = scene.fog;
  13536. // reset caching for this frame
  13537. _currentMaterialId = -1;
  13538. _lightsNeedUpdate = true;
  13539. // update scene graph
  13540. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13541. // update camera matrices and frustum
  13542. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13543. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13544. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13545. _frustum.setFromMatrix( _projScreenMatrix );
  13546. // update WebGL objects
  13547. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13548. // custom render plugins (pre pass)
  13549. renderPlugins( this.renderPluginsPre, scene, camera );
  13550. //
  13551. _this.info.render.calls = 0;
  13552. _this.info.render.vertices = 0;
  13553. _this.info.render.faces = 0;
  13554. _this.info.render.points = 0;
  13555. this.setRenderTarget( renderTarget );
  13556. if ( this.autoClear || forceClear ) {
  13557. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13558. }
  13559. // set matrices for regular objects (frustum culled)
  13560. renderList = scene.__webglObjects;
  13561. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13562. webglObject = renderList[ i ];
  13563. object = webglObject.object;
  13564. webglObject.id = i;
  13565. webglObject.render = false;
  13566. if ( object.visible ) {
  13567. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  13568. setupMatrices( object, camera );
  13569. unrollBufferMaterial( webglObject );
  13570. webglObject.render = true;
  13571. if ( this.sortObjects === true ) {
  13572. if ( object.renderDepth !== null ) {
  13573. webglObject.z = object.renderDepth;
  13574. } else {
  13575. _vector3.setFromMatrixPosition( object.matrixWorld );
  13576. _vector3.applyProjection( _projScreenMatrix );
  13577. webglObject.z = _vector3.z;
  13578. }
  13579. }
  13580. }
  13581. }
  13582. }
  13583. if ( this.sortObjects ) {
  13584. renderList.sort( painterSortStable );
  13585. }
  13586. // set matrices for immediate objects
  13587. renderList = scene.__webglObjectsImmediate;
  13588. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13589. webglObject = renderList[ i ];
  13590. object = webglObject.object;
  13591. if ( object.visible ) {
  13592. setupMatrices( object, camera );
  13593. unrollImmediateBufferMaterial( webglObject );
  13594. }
  13595. }
  13596. if ( scene.overrideMaterial ) {
  13597. var material = scene.overrideMaterial;
  13598. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13599. this.setDepthTest( material.depthTest );
  13600. this.setDepthWrite( material.depthWrite );
  13601. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13602. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13603. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13604. } else {
  13605. var material = null;
  13606. // opaque pass (front-to-back order)
  13607. this.setBlending( THREE.NoBlending );
  13608. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13609. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13610. // transparent pass (back-to-front order)
  13611. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13612. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13613. }
  13614. // custom render plugins (post pass)
  13615. renderPlugins( this.renderPluginsPost, scene, camera );
  13616. // Generate mipmap if we're using any kind of mipmap filtering
  13617. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13618. updateRenderTargetMipmap( renderTarget );
  13619. }
  13620. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13621. this.setDepthTest( true );
  13622. this.setDepthWrite( true );
  13623. // _gl.finish();
  13624. };
  13625. function renderPlugins( plugins, scene, camera ) {
  13626. if ( ! plugins.length ) return;
  13627. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13628. // reset state for plugin (to start from clean slate)
  13629. _currentProgram = null;
  13630. _currentCamera = null;
  13631. _oldBlending = -1;
  13632. _oldDepthTest = -1;
  13633. _oldDepthWrite = -1;
  13634. _oldDoubleSided = -1;
  13635. _oldFlipSided = -1;
  13636. _currentGeometryGroupHash = -1;
  13637. _currentMaterialId = -1;
  13638. _lightsNeedUpdate = true;
  13639. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13640. // reset state after plugin (anything could have changed)
  13641. _currentProgram = null;
  13642. _currentCamera = null;
  13643. _oldBlending = -1;
  13644. _oldDepthTest = -1;
  13645. _oldDepthWrite = -1;
  13646. _oldDoubleSided = -1;
  13647. _oldFlipSided = -1;
  13648. _currentGeometryGroupHash = -1;
  13649. _currentMaterialId = -1;
  13650. _lightsNeedUpdate = true;
  13651. }
  13652. };
  13653. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13654. var webglObject, object, buffer, material, start, end, delta;
  13655. if ( reverse ) {
  13656. start = renderList.length - 1;
  13657. end = -1;
  13658. delta = -1;
  13659. } else {
  13660. start = 0;
  13661. end = renderList.length;
  13662. delta = 1;
  13663. }
  13664. for ( var i = start; i !== end; i += delta ) {
  13665. webglObject = renderList[ i ];
  13666. if ( webglObject.render ) {
  13667. object = webglObject.object;
  13668. buffer = webglObject.buffer;
  13669. if ( overrideMaterial ) {
  13670. material = overrideMaterial;
  13671. } else {
  13672. material = webglObject[ materialType ];
  13673. if ( ! material ) continue;
  13674. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13675. _this.setDepthTest( material.depthTest );
  13676. _this.setDepthWrite( material.depthWrite );
  13677. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13678. }
  13679. _this.setMaterialFaces( material );
  13680. if ( buffer instanceof THREE.BufferGeometry ) {
  13681. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13682. } else {
  13683. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13684. }
  13685. }
  13686. }
  13687. };
  13688. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13689. var webglObject, object, material, program;
  13690. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13691. webglObject = renderList[ i ];
  13692. object = webglObject.object;
  13693. if ( object.visible ) {
  13694. if ( overrideMaterial ) {
  13695. material = overrideMaterial;
  13696. } else {
  13697. material = webglObject[ materialType ];
  13698. if ( ! material ) continue;
  13699. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13700. _this.setDepthTest( material.depthTest );
  13701. _this.setDepthWrite( material.depthWrite );
  13702. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13703. }
  13704. _this.renderImmediateObject( camera, lights, fog, material, object );
  13705. }
  13706. }
  13707. };
  13708. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13709. var program = setProgram( camera, lights, fog, material, object );
  13710. _currentGeometryGroupHash = -1;
  13711. _this.setMaterialFaces( material );
  13712. if ( object.immediateRenderCallback ) {
  13713. object.immediateRenderCallback( program, _gl, _frustum );
  13714. } else {
  13715. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13716. }
  13717. };
  13718. function unrollImmediateBufferMaterial ( globject ) {
  13719. var object = globject.object,
  13720. material = object.material;
  13721. if ( material.transparent ) {
  13722. globject.transparent = material;
  13723. globject.opaque = null;
  13724. } else {
  13725. globject.opaque = material;
  13726. globject.transparent = null;
  13727. }
  13728. };
  13729. function unrollBufferMaterial ( globject ) {
  13730. var object = globject.object;
  13731. var buffer = globject.buffer;
  13732. var geometry = object.geometry;
  13733. var material = object.material;
  13734. if ( material instanceof THREE.MeshFaceMaterial ) {
  13735. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  13736. material = material.materials[ materialIndex ];
  13737. if ( material.transparent ) {
  13738. globject.transparent = material;
  13739. globject.opaque = null;
  13740. } else {
  13741. globject.opaque = material;
  13742. globject.transparent = null;
  13743. }
  13744. } else {
  13745. if ( material ) {
  13746. if ( material.transparent ) {
  13747. globject.transparent = material;
  13748. globject.opaque = null;
  13749. } else {
  13750. globject.opaque = material;
  13751. globject.transparent = null;
  13752. }
  13753. }
  13754. }
  13755. };
  13756. // Objects refresh
  13757. this.initWebGLObjects = function ( scene ) {
  13758. if ( !scene.__webglObjects ) {
  13759. scene.__webglObjects = [];
  13760. scene.__webglObjectsImmediate = [];
  13761. scene.__webglSprites = [];
  13762. scene.__webglFlares = [];
  13763. }
  13764. while ( scene.__objectsAdded.length ) {
  13765. addObject( scene.__objectsAdded[ 0 ], scene );
  13766. scene.__objectsAdded.splice( 0, 1 );
  13767. }
  13768. while ( scene.__objectsRemoved.length ) {
  13769. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13770. scene.__objectsRemoved.splice( 0, 1 );
  13771. }
  13772. // update must be called after objects adding / removal
  13773. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13774. var object = scene.__webglObjects[ o ].object;
  13775. // TODO: Remove this hack (WebGLRenderer refactoring)
  13776. if ( object.__webglInit === undefined ) {
  13777. if ( object.__webglActive !== undefined ) {
  13778. removeObject( object, scene );
  13779. }
  13780. addObject( object, scene );
  13781. }
  13782. updateObject( object );
  13783. }
  13784. };
  13785. // Objects adding
  13786. function addObject( object, scene ) {
  13787. var g, geometry, material, geometryGroup;
  13788. if ( object.__webglInit === undefined ) {
  13789. object.__webglInit = true;
  13790. object._modelViewMatrix = new THREE.Matrix4();
  13791. object._normalMatrix = new THREE.Matrix3();
  13792. geometry = object.geometry;
  13793. if ( geometry === undefined ) {
  13794. // ImmediateRenderObject
  13795. } else if ( geometry.__webglInit === undefined ) {
  13796. geometry.__webglInit = true;
  13797. geometry.addEventListener( 'dispose', onGeometryDispose );
  13798. if ( geometry instanceof THREE.BufferGeometry ) {
  13799. initDirectBuffers( geometry );
  13800. } else if ( object instanceof THREE.Mesh ) {
  13801. material = object.material;
  13802. if ( geometry.geometryGroups === undefined ) {
  13803. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  13804. }
  13805. // create separate VBOs per geometry chunk
  13806. for ( g in geometry.geometryGroups ) {
  13807. geometryGroup = geometry.geometryGroups[ g ];
  13808. // initialise VBO on the first access
  13809. if ( ! geometryGroup.__webglVertexBuffer ) {
  13810. createMeshBuffers( geometryGroup );
  13811. initMeshBuffers( geometryGroup, object );
  13812. geometry.verticesNeedUpdate = true;
  13813. geometry.morphTargetsNeedUpdate = true;
  13814. geometry.elementsNeedUpdate = true;
  13815. geometry.uvsNeedUpdate = true;
  13816. geometry.normalsNeedUpdate = true;
  13817. geometry.tangentsNeedUpdate = true;
  13818. geometry.colorsNeedUpdate = true;
  13819. }
  13820. }
  13821. } else if ( object instanceof THREE.Line ) {
  13822. if ( ! geometry.__webglVertexBuffer ) {
  13823. createLineBuffers( geometry );
  13824. initLineBuffers( geometry, object );
  13825. geometry.verticesNeedUpdate = true;
  13826. geometry.colorsNeedUpdate = true;
  13827. geometry.lineDistancesNeedUpdate = true;
  13828. }
  13829. } else if ( object instanceof THREE.PointCloud ) {
  13830. if ( ! geometry.__webglVertexBuffer ) {
  13831. createParticleBuffers( geometry );
  13832. initParticleBuffers( geometry, object );
  13833. geometry.verticesNeedUpdate = true;
  13834. geometry.colorsNeedUpdate = true;
  13835. }
  13836. }
  13837. }
  13838. }
  13839. if ( object.__webglActive === undefined ) {
  13840. if ( object instanceof THREE.Mesh ) {
  13841. geometry = object.geometry;
  13842. if ( geometry instanceof THREE.BufferGeometry ) {
  13843. addBuffer( scene.__webglObjects, geometry, object );
  13844. } else if ( geometry instanceof THREE.Geometry ) {
  13845. for ( g in geometry.geometryGroups ) {
  13846. geometryGroup = geometry.geometryGroups[ g ];
  13847. addBuffer( scene.__webglObjects, geometryGroup, object );
  13848. }
  13849. }
  13850. } else if ( object instanceof THREE.Line ||
  13851. object instanceof THREE.PointCloud ) {
  13852. geometry = object.geometry;
  13853. addBuffer( scene.__webglObjects, geometry, object );
  13854. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13855. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13856. } else if ( object instanceof THREE.Sprite ) {
  13857. scene.__webglSprites.push( object );
  13858. } else if ( object instanceof THREE.LensFlare ) {
  13859. scene.__webglFlares.push( object );
  13860. }
  13861. object.__webglActive = true;
  13862. }
  13863. };
  13864. function addBuffer( objlist, buffer, object ) {
  13865. objlist.push(
  13866. {
  13867. id: null,
  13868. buffer: buffer,
  13869. object: object,
  13870. opaque: null,
  13871. transparent: null,
  13872. z: 0
  13873. }
  13874. );
  13875. };
  13876. function addBufferImmediate( objlist, object ) {
  13877. objlist.push(
  13878. {
  13879. id: null,
  13880. object: object,
  13881. opaque: null,
  13882. transparent: null,
  13883. z: 0
  13884. }
  13885. );
  13886. };
  13887. // Objects updates
  13888. function updateObject( object ) {
  13889. var geometry = object.geometry,
  13890. geometryGroup, customAttributesDirty, material;
  13891. if ( geometry instanceof THREE.BufferGeometry ) {
  13892. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  13893. } else if ( object instanceof THREE.Mesh ) {
  13894. // check all geometry groups
  13895. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13896. geometryGroup = geometry.geometryGroupsList[ i ];
  13897. material = getBufferMaterial( object, geometryGroup );
  13898. if ( geometry.buffersNeedUpdate ) {
  13899. initMeshBuffers( geometryGroup, object );
  13900. }
  13901. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13902. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13903. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13904. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13905. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13906. }
  13907. }
  13908. geometry.verticesNeedUpdate = false;
  13909. geometry.morphTargetsNeedUpdate = false;
  13910. geometry.elementsNeedUpdate = false;
  13911. geometry.uvsNeedUpdate = false;
  13912. geometry.normalsNeedUpdate = false;
  13913. geometry.colorsNeedUpdate = false;
  13914. geometry.tangentsNeedUpdate = false;
  13915. geometry.buffersNeedUpdate = false;
  13916. material.attributes && clearCustomAttributes( material );
  13917. } else if ( object instanceof THREE.Line ) {
  13918. material = getBufferMaterial( object, geometry );
  13919. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13920. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13921. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13922. }
  13923. geometry.verticesNeedUpdate = false;
  13924. geometry.colorsNeedUpdate = false;
  13925. geometry.lineDistancesNeedUpdate = false;
  13926. material.attributes && clearCustomAttributes( material );
  13927. } else if ( object instanceof THREE.PointCloud ) {
  13928. material = getBufferMaterial( object, geometry );
  13929. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13930. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13931. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13932. }
  13933. geometry.verticesNeedUpdate = false;
  13934. geometry.colorsNeedUpdate = false;
  13935. material.attributes && clearCustomAttributes( material );
  13936. }
  13937. };
  13938. // Objects updates - custom attributes check
  13939. function areCustomAttributesDirty( material ) {
  13940. for ( var a in material.attributes ) {
  13941. if ( material.attributes[ a ].needsUpdate ) return true;
  13942. }
  13943. return false;
  13944. };
  13945. function clearCustomAttributes( material ) {
  13946. for ( var a in material.attributes ) {
  13947. material.attributes[ a ].needsUpdate = false;
  13948. }
  13949. };
  13950. // Objects removal
  13951. function removeObject( object, scene ) {
  13952. if ( object instanceof THREE.Mesh ||
  13953. object instanceof THREE.PointCloud ||
  13954. object instanceof THREE.Line ) {
  13955. removeInstances( scene.__webglObjects, object );
  13956. } else if ( object instanceof THREE.Sprite ) {
  13957. removeInstancesDirect( scene.__webglSprites, object );
  13958. } else if ( object instanceof THREE.LensFlare ) {
  13959. removeInstancesDirect( scene.__webglFlares, object );
  13960. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13961. removeInstances( scene.__webglObjectsImmediate, object );
  13962. }
  13963. delete object.__webglActive;
  13964. };
  13965. function removeInstances( objlist, object ) {
  13966. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13967. if ( objlist[ o ].object === object ) {
  13968. objlist.splice( o, 1 );
  13969. }
  13970. }
  13971. };
  13972. function removeInstancesDirect( objlist, object ) {
  13973. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13974. if ( objlist[ o ] === object ) {
  13975. objlist.splice( o, 1 );
  13976. }
  13977. }
  13978. };
  13979. // Materials
  13980. this.initMaterial = function ( material, lights, fog, object ) {
  13981. material.addEventListener( 'dispose', onMaterialDispose );
  13982. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13983. if ( material instanceof THREE.MeshDepthMaterial ) {
  13984. shaderID = 'depth';
  13985. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13986. shaderID = 'normal';
  13987. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13988. shaderID = 'basic';
  13989. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13990. shaderID = 'lambert';
  13991. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13992. shaderID = 'phong';
  13993. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13994. shaderID = 'basic';
  13995. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13996. shaderID = 'dashed';
  13997. } else if ( material instanceof THREE.PointCloudMaterial ) {
  13998. shaderID = 'particle_basic';
  13999. }
  14000. if ( shaderID ) {
  14001. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14002. }
  14003. // heuristics to create shader parameters according to lights in the scene
  14004. // (not to blow over maxLights budget)
  14005. maxLightCount = allocateLights( lights );
  14006. maxShadows = allocateShadows( lights );
  14007. maxBones = allocateBones( object );
  14008. parameters = {
  14009. precision: _precision,
  14010. supportsVertexTextures: _supportsVertexTextures,
  14011. map: !!material.map,
  14012. envMap: !!material.envMap,
  14013. lightMap: !!material.lightMap,
  14014. bumpMap: !!material.bumpMap,
  14015. normalMap: !!material.normalMap,
  14016. specularMap: !!material.specularMap,
  14017. vertexColors: material.vertexColors,
  14018. fog: fog,
  14019. useFog: material.fog,
  14020. fogExp: fog instanceof THREE.FogExp2,
  14021. sizeAttenuation: material.sizeAttenuation,
  14022. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14023. skinning: material.skinning,
  14024. maxBones: maxBones,
  14025. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14026. morphTargets: material.morphTargets,
  14027. morphNormals: material.morphNormals,
  14028. maxMorphTargets: this.maxMorphTargets,
  14029. maxMorphNormals: this.maxMorphNormals,
  14030. maxDirLights: maxLightCount.directional,
  14031. maxPointLights: maxLightCount.point,
  14032. maxSpotLights: maxLightCount.spot,
  14033. maxHemiLights: maxLightCount.hemi,
  14034. maxShadows: maxShadows,
  14035. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14036. shadowMapType: this.shadowMapType,
  14037. shadowMapDebug: this.shadowMapDebug,
  14038. shadowMapCascade: this.shadowMapCascade,
  14039. alphaTest: material.alphaTest,
  14040. metal: material.metal,
  14041. wrapAround: material.wrapAround,
  14042. doubleSided: material.side === THREE.DoubleSide,
  14043. flipSided: material.side === THREE.BackSide
  14044. };
  14045. // Generate code
  14046. var chunks = [];
  14047. if ( shaderID ) {
  14048. chunks.push( shaderID );
  14049. } else {
  14050. chunks.push( material.fragmentShader );
  14051. chunks.push( material.vertexShader );
  14052. }
  14053. for ( var d in material.defines ) {
  14054. chunks.push( d );
  14055. chunks.push( material.defines[ d ] );
  14056. }
  14057. for ( var p in parameters ) {
  14058. chunks.push( p );
  14059. chunks.push( parameters[ p ] );
  14060. }
  14061. var code = chunks.join();
  14062. var program;
  14063. // Check if code has been already compiled
  14064. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14065. var programInfo = _programs[ p ];
  14066. if ( programInfo.code === code ) {
  14067. program = programInfo;
  14068. program.usedTimes ++;
  14069. break;
  14070. }
  14071. }
  14072. if ( program === undefined ) {
  14073. program = new THREE.WebGLProgram( this, code, material, parameters );
  14074. _programs.push( program );
  14075. _this.info.memory.programs = _programs.length;
  14076. }
  14077. material.program = program;
  14078. var attributes = material.program.attributes;
  14079. if ( material.morphTargets ) {
  14080. material.numSupportedMorphTargets = 0;
  14081. var id, base = "morphTarget";
  14082. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14083. id = base + i;
  14084. if ( attributes[ id ] >= 0 ) {
  14085. material.numSupportedMorphTargets ++;
  14086. }
  14087. }
  14088. }
  14089. if ( material.morphNormals ) {
  14090. material.numSupportedMorphNormals = 0;
  14091. var id, base = "morphNormal";
  14092. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14093. id = base + i;
  14094. if ( attributes[ id ] >= 0 ) {
  14095. material.numSupportedMorphNormals ++;
  14096. }
  14097. }
  14098. }
  14099. material.uniformsList = [];
  14100. for ( u in material.uniforms ) {
  14101. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14102. }
  14103. };
  14104. function setMaterialShaders( material, shaders ) {
  14105. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14106. material.vertexShader = shaders.vertexShader;
  14107. material.fragmentShader = shaders.fragmentShader;
  14108. };
  14109. function setProgram( camera, lights, fog, material, object ) {
  14110. _usedTextureUnits = 0;
  14111. if ( material.needsUpdate ) {
  14112. if ( material.program ) deallocateMaterial( material );
  14113. _this.initMaterial( material, lights, fog, object );
  14114. material.needsUpdate = false;
  14115. }
  14116. if ( material.morphTargets ) {
  14117. if ( ! object.__webglMorphTargetInfluences ) {
  14118. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14119. }
  14120. }
  14121. var refreshMaterial = false;
  14122. var program = material.program,
  14123. p_uniforms = program.uniforms,
  14124. m_uniforms = material.uniforms;
  14125. if ( program.id !== _currentProgram ) {
  14126. _gl.useProgram( program.program );
  14127. _currentProgram = program.id;
  14128. refreshMaterial = true;
  14129. }
  14130. if ( material.id !== _currentMaterialId ) {
  14131. _currentMaterialId = material.id;
  14132. refreshMaterial = true;
  14133. }
  14134. if ( refreshMaterial || camera !== _currentCamera ) {
  14135. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14136. if ( _logarithmicDepthBuffer ) {
  14137. _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14138. }
  14139. if ( camera !== _currentCamera ) _currentCamera = camera;
  14140. }
  14141. // skinning uniforms must be set even if material didn't change
  14142. // auto-setting of texture unit for bone texture must go before other textures
  14143. // not sure why, but otherwise weird things happen
  14144. if ( material.skinning ) {
  14145. if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) {
  14146. if ( p_uniforms.boneTexture !== null ) {
  14147. var textureUnit = getTextureUnit();
  14148. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14149. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  14150. }
  14151. if ( p_uniforms.boneTextureWidth !== null ) {
  14152. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  14153. }
  14154. if ( p_uniforms.boneTextureHeight !== null ) {
  14155. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  14156. }
  14157. } else {
  14158. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14159. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  14160. }
  14161. }
  14162. }
  14163. if ( refreshMaterial ) {
  14164. // refresh uniforms common to several materials
  14165. if ( fog && material.fog ) {
  14166. refreshUniformsFog( m_uniforms, fog );
  14167. }
  14168. if ( material instanceof THREE.MeshPhongMaterial ||
  14169. material instanceof THREE.MeshLambertMaterial ||
  14170. material.lights ) {
  14171. if ( _lightsNeedUpdate ) {
  14172. setupLights( program, lights );
  14173. _lightsNeedUpdate = false;
  14174. }
  14175. refreshUniformsLights( m_uniforms, _lights );
  14176. }
  14177. if ( material instanceof THREE.MeshBasicMaterial ||
  14178. material instanceof THREE.MeshLambertMaterial ||
  14179. material instanceof THREE.MeshPhongMaterial ) {
  14180. refreshUniformsCommon( m_uniforms, material );
  14181. }
  14182. // refresh single material specific uniforms
  14183. if ( material instanceof THREE.LineBasicMaterial ) {
  14184. refreshUniformsLine( m_uniforms, material );
  14185. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14186. refreshUniformsLine( m_uniforms, material );
  14187. refreshUniformsDash( m_uniforms, material );
  14188. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14189. refreshUniformsParticle( m_uniforms, material );
  14190. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14191. refreshUniformsPhong( m_uniforms, material );
  14192. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14193. refreshUniformsLambert( m_uniforms, material );
  14194. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14195. m_uniforms.mNear.value = camera.near;
  14196. m_uniforms.mFar.value = camera.far;
  14197. m_uniforms.opacity.value = material.opacity;
  14198. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14199. m_uniforms.opacity.value = material.opacity;
  14200. }
  14201. if ( object.receiveShadow && ! material._shadowPass ) {
  14202. refreshUniformsShadow( m_uniforms, lights );
  14203. }
  14204. // load common uniforms
  14205. loadUniformsGeneric( program, material.uniformsList );
  14206. // load material specific uniforms
  14207. // (shader material also gets them for the sake of genericity)
  14208. if ( material instanceof THREE.ShaderMaterial ||
  14209. material instanceof THREE.MeshPhongMaterial ||
  14210. material.envMap ) {
  14211. if ( p_uniforms.cameraPosition !== null ) {
  14212. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14213. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14214. }
  14215. }
  14216. if ( material instanceof THREE.MeshPhongMaterial ||
  14217. material instanceof THREE.MeshLambertMaterial ||
  14218. material instanceof THREE.ShaderMaterial ||
  14219. material.skinning ) {
  14220. if ( p_uniforms.viewMatrix !== null ) {
  14221. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14222. }
  14223. }
  14224. }
  14225. loadUniformsMatrices( p_uniforms, object );
  14226. if ( p_uniforms.modelMatrix !== null ) {
  14227. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14228. }
  14229. return program;
  14230. };
  14231. // Uniforms (refresh uniforms objects)
  14232. function refreshUniformsCommon ( uniforms, material ) {
  14233. uniforms.opacity.value = material.opacity;
  14234. if ( _this.gammaInput ) {
  14235. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14236. } else {
  14237. uniforms.diffuse.value = material.color;
  14238. }
  14239. uniforms.map.value = material.map;
  14240. uniforms.lightMap.value = material.lightMap;
  14241. uniforms.specularMap.value = material.specularMap;
  14242. if ( material.bumpMap ) {
  14243. uniforms.bumpMap.value = material.bumpMap;
  14244. uniforms.bumpScale.value = material.bumpScale;
  14245. }
  14246. if ( material.normalMap ) {
  14247. uniforms.normalMap.value = material.normalMap;
  14248. uniforms.normalScale.value.copy( material.normalScale );
  14249. }
  14250. // uv repeat and offset setting priorities
  14251. // 1. color map
  14252. // 2. specular map
  14253. // 3. normal map
  14254. // 4. bump map
  14255. var uvScaleMap;
  14256. if ( material.map ) {
  14257. uvScaleMap = material.map;
  14258. } else if ( material.specularMap ) {
  14259. uvScaleMap = material.specularMap;
  14260. } else if ( material.normalMap ) {
  14261. uvScaleMap = material.normalMap;
  14262. } else if ( material.bumpMap ) {
  14263. uvScaleMap = material.bumpMap;
  14264. }
  14265. if ( uvScaleMap !== undefined ) {
  14266. var offset = uvScaleMap.offset;
  14267. var repeat = uvScaleMap.repeat;
  14268. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14269. }
  14270. uniforms.envMap.value = material.envMap;
  14271. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14272. if ( _this.gammaInput ) {
  14273. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14274. uniforms.reflectivity.value = material.reflectivity;
  14275. } else {
  14276. uniforms.reflectivity.value = material.reflectivity;
  14277. }
  14278. uniforms.refractionRatio.value = material.refractionRatio;
  14279. uniforms.combine.value = material.combine;
  14280. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14281. };
  14282. function refreshUniformsLine ( uniforms, material ) {
  14283. uniforms.diffuse.value = material.color;
  14284. uniforms.opacity.value = material.opacity;
  14285. };
  14286. function refreshUniformsDash ( uniforms, material ) {
  14287. uniforms.dashSize.value = material.dashSize;
  14288. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14289. uniforms.scale.value = material.scale;
  14290. };
  14291. function refreshUniformsParticle ( uniforms, material ) {
  14292. uniforms.psColor.value = material.color;
  14293. uniforms.opacity.value = material.opacity;
  14294. uniforms.size.value = material.size;
  14295. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14296. uniforms.map.value = material.map;
  14297. };
  14298. function refreshUniformsFog ( uniforms, fog ) {
  14299. uniforms.fogColor.value = fog.color;
  14300. if ( fog instanceof THREE.Fog ) {
  14301. uniforms.fogNear.value = fog.near;
  14302. uniforms.fogFar.value = fog.far;
  14303. } else if ( fog instanceof THREE.FogExp2 ) {
  14304. uniforms.fogDensity.value = fog.density;
  14305. }
  14306. };
  14307. function refreshUniformsPhong ( uniforms, material ) {
  14308. uniforms.shininess.value = material.shininess;
  14309. if ( _this.gammaInput ) {
  14310. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14311. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14312. uniforms.specular.value.copyGammaToLinear( material.specular );
  14313. } else {
  14314. uniforms.ambient.value = material.ambient;
  14315. uniforms.emissive.value = material.emissive;
  14316. uniforms.specular.value = material.specular;
  14317. }
  14318. if ( material.wrapAround ) {
  14319. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14320. }
  14321. };
  14322. function refreshUniformsLambert ( uniforms, material ) {
  14323. if ( _this.gammaInput ) {
  14324. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14325. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14326. } else {
  14327. uniforms.ambient.value = material.ambient;
  14328. uniforms.emissive.value = material.emissive;
  14329. }
  14330. if ( material.wrapAround ) {
  14331. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14332. }
  14333. };
  14334. function refreshUniformsLights ( uniforms, lights ) {
  14335. uniforms.ambientLightColor.value = lights.ambient;
  14336. uniforms.directionalLightColor.value = lights.directional.colors;
  14337. uniforms.directionalLightDirection.value = lights.directional.positions;
  14338. uniforms.pointLightColor.value = lights.point.colors;
  14339. uniforms.pointLightPosition.value = lights.point.positions;
  14340. uniforms.pointLightDistance.value = lights.point.distances;
  14341. uniforms.spotLightColor.value = lights.spot.colors;
  14342. uniforms.spotLightPosition.value = lights.spot.positions;
  14343. uniforms.spotLightDistance.value = lights.spot.distances;
  14344. uniforms.spotLightDirection.value = lights.spot.directions;
  14345. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14346. uniforms.spotLightExponent.value = lights.spot.exponents;
  14347. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14348. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14349. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14350. };
  14351. function refreshUniformsShadow ( uniforms, lights ) {
  14352. if ( uniforms.shadowMatrix ) {
  14353. var j = 0;
  14354. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14355. var light = lights[ i ];
  14356. if ( ! light.castShadow ) continue;
  14357. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14358. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14359. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14360. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14361. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14362. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14363. j ++;
  14364. }
  14365. }
  14366. }
  14367. };
  14368. // Uniforms (load to GPU)
  14369. function loadUniformsMatrices ( uniforms, object ) {
  14370. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14371. if ( uniforms.normalMatrix ) {
  14372. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14373. }
  14374. };
  14375. function getTextureUnit() {
  14376. var textureUnit = _usedTextureUnits;
  14377. if ( textureUnit >= _maxTextures ) {
  14378. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14379. }
  14380. _usedTextureUnits += 1;
  14381. return textureUnit;
  14382. };
  14383. function loadUniformsGeneric ( program, uniforms ) {
  14384. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14385. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14386. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14387. if ( !location ) continue;
  14388. uniform = uniforms[ j ][ 0 ];
  14389. type = uniform.type;
  14390. value = uniform.value;
  14391. if ( type === "i" ) { // single integer
  14392. _gl.uniform1i( location, value );
  14393. } else if ( type === "f" ) { // single float
  14394. _gl.uniform1f( location, value );
  14395. } else if ( type === "v2" ) { // single THREE.Vector2
  14396. _gl.uniform2f( location, value.x, value.y );
  14397. } else if ( type === "v3" ) { // single THREE.Vector3
  14398. _gl.uniform3f( location, value.x, value.y, value.z );
  14399. } else if ( type === "v4" ) { // single THREE.Vector4
  14400. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14401. } else if ( type === "c" ) { // single THREE.Color
  14402. _gl.uniform3f( location, value.r, value.g, value.b );
  14403. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14404. _gl.uniform1iv( location, value );
  14405. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14406. _gl.uniform3iv( location, value );
  14407. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14408. _gl.uniform1fv( location, value );
  14409. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14410. _gl.uniform3fv( location, value );
  14411. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14412. if ( uniform._array === undefined ) {
  14413. uniform._array = new Float32Array( 2 * value.length );
  14414. }
  14415. for ( i = 0, il = value.length; i < il; i ++ ) {
  14416. offset = i * 2;
  14417. uniform._array[ offset ] = value[ i ].x;
  14418. uniform._array[ offset + 1 ] = value[ i ].y;
  14419. }
  14420. _gl.uniform2fv( location, uniform._array );
  14421. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14422. if ( uniform._array === undefined ) {
  14423. uniform._array = new Float32Array( 3 * value.length );
  14424. }
  14425. for ( i = 0, il = value.length; i < il; i ++ ) {
  14426. offset = i * 3;
  14427. uniform._array[ offset ] = value[ i ].x;
  14428. uniform._array[ offset + 1 ] = value[ i ].y;
  14429. uniform._array[ offset + 2 ] = value[ i ].z;
  14430. }
  14431. _gl.uniform3fv( location, uniform._array );
  14432. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14433. if ( uniform._array === undefined ) {
  14434. uniform._array = new Float32Array( 4 * value.length );
  14435. }
  14436. for ( i = 0, il = value.length; i < il; i ++ ) {
  14437. offset = i * 4;
  14438. uniform._array[ offset ] = value[ i ].x;
  14439. uniform._array[ offset + 1 ] = value[ i ].y;
  14440. uniform._array[ offset + 2 ] = value[ i ].z;
  14441. uniform._array[ offset + 3 ] = value[ i ].w;
  14442. }
  14443. _gl.uniform4fv( location, uniform._array );
  14444. } else if ( type === "m3") { // single THREE.Matrix3
  14445. _gl.uniformMatrix3fv( location, false, value.elements );
  14446. } else if ( type === "m3v" ) { // array of THREE.Matrix3
  14447. if ( uniform._array === undefined ) {
  14448. uniform._array = new Float32Array( 9 * value.length );
  14449. }
  14450. for ( i = 0, il = value.length; i < il; i ++ ) {
  14451. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  14452. }
  14453. _gl.uniformMatrix3fv( location, false, uniform._array );
  14454. } else if ( type === "m4") { // single THREE.Matrix4
  14455. _gl.uniformMatrix4fv( location, false, value.elements );
  14456. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14457. if ( uniform._array === undefined ) {
  14458. uniform._array = new Float32Array( 16 * value.length );
  14459. }
  14460. for ( i = 0, il = value.length; i < il; i ++ ) {
  14461. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14462. }
  14463. _gl.uniformMatrix4fv( location, false, uniform._array );
  14464. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14465. texture = value;
  14466. textureUnit = getTextureUnit();
  14467. _gl.uniform1i( location, textureUnit );
  14468. if ( !texture ) continue;
  14469. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14470. setCubeTexture( texture, textureUnit );
  14471. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14472. setCubeTextureDynamic( texture, textureUnit );
  14473. } else {
  14474. _this.setTexture( texture, textureUnit );
  14475. }
  14476. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14477. if ( uniform._array === undefined ) {
  14478. uniform._array = [];
  14479. }
  14480. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14481. uniform._array[ i ] = getTextureUnit();
  14482. }
  14483. _gl.uniform1iv( location, uniform._array );
  14484. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14485. texture = uniform.value[ i ];
  14486. textureUnit = uniform._array[ i ];
  14487. if ( !texture ) continue;
  14488. _this.setTexture( texture, textureUnit );
  14489. }
  14490. } else {
  14491. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14492. }
  14493. }
  14494. };
  14495. function setupMatrices ( object, camera ) {
  14496. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14497. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14498. };
  14499. //
  14500. function setColorGamma( array, offset, color, intensitySq ) {
  14501. array[ offset ] = color.r * color.r * intensitySq;
  14502. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14503. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14504. };
  14505. function setColorLinear( array, offset, color, intensity ) {
  14506. array[ offset ] = color.r * intensity;
  14507. array[ offset + 1 ] = color.g * intensity;
  14508. array[ offset + 2 ] = color.b * intensity;
  14509. };
  14510. function setupLights ( program, lights ) {
  14511. var l, ll, light, n,
  14512. r = 0, g = 0, b = 0,
  14513. color, skyColor, groundColor,
  14514. intensity, intensitySq,
  14515. position,
  14516. distance,
  14517. zlights = _lights,
  14518. dirColors = zlights.directional.colors,
  14519. dirPositions = zlights.directional.positions,
  14520. pointColors = zlights.point.colors,
  14521. pointPositions = zlights.point.positions,
  14522. pointDistances = zlights.point.distances,
  14523. spotColors = zlights.spot.colors,
  14524. spotPositions = zlights.spot.positions,
  14525. spotDistances = zlights.spot.distances,
  14526. spotDirections = zlights.spot.directions,
  14527. spotAnglesCos = zlights.spot.anglesCos,
  14528. spotExponents = zlights.spot.exponents,
  14529. hemiSkyColors = zlights.hemi.skyColors,
  14530. hemiGroundColors = zlights.hemi.groundColors,
  14531. hemiPositions = zlights.hemi.positions,
  14532. dirLength = 0,
  14533. pointLength = 0,
  14534. spotLength = 0,
  14535. hemiLength = 0,
  14536. dirCount = 0,
  14537. pointCount = 0,
  14538. spotCount = 0,
  14539. hemiCount = 0,
  14540. dirOffset = 0,
  14541. pointOffset = 0,
  14542. spotOffset = 0,
  14543. hemiOffset = 0;
  14544. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14545. light = lights[ l ];
  14546. if ( light.onlyShadow ) continue;
  14547. color = light.color;
  14548. intensity = light.intensity;
  14549. distance = light.distance;
  14550. if ( light instanceof THREE.AmbientLight ) {
  14551. if ( ! light.visible ) continue;
  14552. if ( _this.gammaInput ) {
  14553. r += color.r * color.r;
  14554. g += color.g * color.g;
  14555. b += color.b * color.b;
  14556. } else {
  14557. r += color.r;
  14558. g += color.g;
  14559. b += color.b;
  14560. }
  14561. } else if ( light instanceof THREE.DirectionalLight ) {
  14562. dirCount += 1;
  14563. if ( ! light.visible ) continue;
  14564. _direction.setFromMatrixPosition( light.matrixWorld );
  14565. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14566. _direction.sub( _vector3 );
  14567. _direction.normalize();
  14568. // skip lights with undefined direction
  14569. // these create troubles in OpenGL (making pixel black)
  14570. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14571. dirOffset = dirLength * 3;
  14572. dirPositions[ dirOffset ] = _direction.x;
  14573. dirPositions[ dirOffset + 1 ] = _direction.y;
  14574. dirPositions[ dirOffset + 2 ] = _direction.z;
  14575. if ( _this.gammaInput ) {
  14576. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14577. } else {
  14578. setColorLinear( dirColors, dirOffset, color, intensity );
  14579. }
  14580. dirLength += 1;
  14581. } else if ( light instanceof THREE.PointLight ) {
  14582. pointCount += 1;
  14583. if ( ! light.visible ) continue;
  14584. pointOffset = pointLength * 3;
  14585. if ( _this.gammaInput ) {
  14586. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14587. } else {
  14588. setColorLinear( pointColors, pointOffset, color, intensity );
  14589. }
  14590. _vector3.setFromMatrixPosition( light.matrixWorld );
  14591. pointPositions[ pointOffset ] = _vector3.x;
  14592. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14593. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14594. pointDistances[ pointLength ] = distance;
  14595. pointLength += 1;
  14596. } else if ( light instanceof THREE.SpotLight ) {
  14597. spotCount += 1;
  14598. if ( ! light.visible ) continue;
  14599. spotOffset = spotLength * 3;
  14600. if ( _this.gammaInput ) {
  14601. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14602. } else {
  14603. setColorLinear( spotColors, spotOffset, color, intensity );
  14604. }
  14605. _vector3.setFromMatrixPosition( light.matrixWorld );
  14606. spotPositions[ spotOffset ] = _vector3.x;
  14607. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14608. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14609. spotDistances[ spotLength ] = distance;
  14610. _direction.copy( _vector3 );
  14611. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14612. _direction.sub( _vector3 );
  14613. _direction.normalize();
  14614. spotDirections[ spotOffset ] = _direction.x;
  14615. spotDirections[ spotOffset + 1 ] = _direction.y;
  14616. spotDirections[ spotOffset + 2 ] = _direction.z;
  14617. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14618. spotExponents[ spotLength ] = light.exponent;
  14619. spotLength += 1;
  14620. } else if ( light instanceof THREE.HemisphereLight ) {
  14621. hemiCount += 1;
  14622. if ( ! light.visible ) continue;
  14623. _direction.setFromMatrixPosition( light.matrixWorld );
  14624. _direction.normalize();
  14625. // skip lights with undefined direction
  14626. // these create troubles in OpenGL (making pixel black)
  14627. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14628. hemiOffset = hemiLength * 3;
  14629. hemiPositions[ hemiOffset ] = _direction.x;
  14630. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14631. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14632. skyColor = light.color;
  14633. groundColor = light.groundColor;
  14634. if ( _this.gammaInput ) {
  14635. intensitySq = intensity * intensity;
  14636. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14637. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14638. } else {
  14639. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14640. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14641. }
  14642. hemiLength += 1;
  14643. }
  14644. }
  14645. // null eventual remains from removed lights
  14646. // (this is to avoid if in shader)
  14647. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14648. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14649. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14650. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14651. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14652. zlights.directional.length = dirLength;
  14653. zlights.point.length = pointLength;
  14654. zlights.spot.length = spotLength;
  14655. zlights.hemi.length = hemiLength;
  14656. zlights.ambient[ 0 ] = r;
  14657. zlights.ambient[ 1 ] = g;
  14658. zlights.ambient[ 2 ] = b;
  14659. };
  14660. // GL state setting
  14661. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14662. if ( cullFace === THREE.CullFaceNone ) {
  14663. _gl.disable( _gl.CULL_FACE );
  14664. } else {
  14665. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14666. _gl.frontFace( _gl.CW );
  14667. } else {
  14668. _gl.frontFace( _gl.CCW );
  14669. }
  14670. if ( cullFace === THREE.CullFaceBack ) {
  14671. _gl.cullFace( _gl.BACK );
  14672. } else if ( cullFace === THREE.CullFaceFront ) {
  14673. _gl.cullFace( _gl.FRONT );
  14674. } else {
  14675. _gl.cullFace( _gl.FRONT_AND_BACK );
  14676. }
  14677. _gl.enable( _gl.CULL_FACE );
  14678. }
  14679. };
  14680. this.setMaterialFaces = function ( material ) {
  14681. var doubleSided = material.side === THREE.DoubleSide;
  14682. var flipSided = material.side === THREE.BackSide;
  14683. if ( _oldDoubleSided !== doubleSided ) {
  14684. if ( doubleSided ) {
  14685. _gl.disable( _gl.CULL_FACE );
  14686. } else {
  14687. _gl.enable( _gl.CULL_FACE );
  14688. }
  14689. _oldDoubleSided = doubleSided;
  14690. }
  14691. if ( _oldFlipSided !== flipSided ) {
  14692. if ( flipSided ) {
  14693. _gl.frontFace( _gl.CW );
  14694. } else {
  14695. _gl.frontFace( _gl.CCW );
  14696. }
  14697. _oldFlipSided = flipSided;
  14698. }
  14699. };
  14700. this.setDepthTest = function ( depthTest ) {
  14701. if ( _oldDepthTest !== depthTest ) {
  14702. if ( depthTest ) {
  14703. _gl.enable( _gl.DEPTH_TEST );
  14704. } else {
  14705. _gl.disable( _gl.DEPTH_TEST );
  14706. }
  14707. _oldDepthTest = depthTest;
  14708. }
  14709. };
  14710. this.setDepthWrite = function ( depthWrite ) {
  14711. if ( _oldDepthWrite !== depthWrite ) {
  14712. _gl.depthMask( depthWrite );
  14713. _oldDepthWrite = depthWrite;
  14714. }
  14715. };
  14716. function setLineWidth ( width ) {
  14717. if ( width !== _oldLineWidth ) {
  14718. _gl.lineWidth( width );
  14719. _oldLineWidth = width;
  14720. }
  14721. };
  14722. function setPolygonOffset ( polygonoffset, factor, units ) {
  14723. if ( _oldPolygonOffset !== polygonoffset ) {
  14724. if ( polygonoffset ) {
  14725. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14726. } else {
  14727. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14728. }
  14729. _oldPolygonOffset = polygonoffset;
  14730. }
  14731. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14732. _gl.polygonOffset( factor, units );
  14733. _oldPolygonOffsetFactor = factor;
  14734. _oldPolygonOffsetUnits = units;
  14735. }
  14736. };
  14737. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14738. if ( blending !== _oldBlending ) {
  14739. if ( blending === THREE.NoBlending ) {
  14740. _gl.disable( _gl.BLEND );
  14741. } else if ( blending === THREE.AdditiveBlending ) {
  14742. _gl.enable( _gl.BLEND );
  14743. _gl.blendEquation( _gl.FUNC_ADD );
  14744. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14745. } else if ( blending === THREE.SubtractiveBlending ) {
  14746. // TODO: Find blendFuncSeparate() combination
  14747. _gl.enable( _gl.BLEND );
  14748. _gl.blendEquation( _gl.FUNC_ADD );
  14749. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14750. } else if ( blending === THREE.MultiplyBlending ) {
  14751. // TODO: Find blendFuncSeparate() combination
  14752. _gl.enable( _gl.BLEND );
  14753. _gl.blendEquation( _gl.FUNC_ADD );
  14754. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14755. } else if ( blending === THREE.CustomBlending ) {
  14756. _gl.enable( _gl.BLEND );
  14757. } else {
  14758. _gl.enable( _gl.BLEND );
  14759. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14760. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14761. }
  14762. _oldBlending = blending;
  14763. }
  14764. if ( blending === THREE.CustomBlending ) {
  14765. if ( blendEquation !== _oldBlendEquation ) {
  14766. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14767. _oldBlendEquation = blendEquation;
  14768. }
  14769. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14770. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14771. _oldBlendSrc = blendSrc;
  14772. _oldBlendDst = blendDst;
  14773. }
  14774. } else {
  14775. _oldBlendEquation = null;
  14776. _oldBlendSrc = null;
  14777. _oldBlendDst = null;
  14778. }
  14779. };
  14780. // Textures
  14781. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14782. if ( isImagePowerOfTwo ) {
  14783. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14784. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14785. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14786. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14787. } else {
  14788. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14789. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14790. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14791. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14792. }
  14793. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14794. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14795. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14796. texture.__oldAnisotropy = texture.anisotropy;
  14797. }
  14798. }
  14799. };
  14800. this.setTexture = function ( texture, slot ) {
  14801. if ( texture.needsUpdate ) {
  14802. if ( ! texture.__webglInit ) {
  14803. texture.__webglInit = true;
  14804. texture.addEventListener( 'dispose', onTextureDispose );
  14805. texture.__webglTexture = _gl.createTexture();
  14806. _this.info.memory.textures ++;
  14807. }
  14808. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14809. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14810. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14811. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14812. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14813. var image = texture.image,
  14814. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  14815. glFormat = paramThreeToGL( texture.format ),
  14816. glType = paramThreeToGL( texture.type );
  14817. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14818. var mipmap, mipmaps = texture.mipmaps;
  14819. if ( texture instanceof THREE.DataTexture ) {
  14820. // use manually created mipmaps if available
  14821. // if there are no manual mipmaps
  14822. // set 0 level mipmap and then use GL to generate other mipmap levels
  14823. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14824. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14825. mipmap = mipmaps[ i ];
  14826. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14827. }
  14828. texture.generateMipmaps = false;
  14829. } else {
  14830. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14831. }
  14832. } else if ( texture instanceof THREE.CompressedTexture ) {
  14833. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14834. mipmap = mipmaps[ i ];
  14835. if ( texture.format!==THREE.RGBAFormat ) {
  14836. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14837. } else {
  14838. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14839. }
  14840. }
  14841. } else { // regular Texture (image, video, canvas)
  14842. // use manually created mipmaps if available
  14843. // if there are no manual mipmaps
  14844. // set 0 level mipmap and then use GL to generate other mipmap levels
  14845. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14846. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14847. mipmap = mipmaps[ i ];
  14848. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14849. }
  14850. texture.generateMipmaps = false;
  14851. } else {
  14852. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14853. }
  14854. }
  14855. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14856. texture.needsUpdate = false;
  14857. if ( texture.onUpdate ) texture.onUpdate();
  14858. } else {
  14859. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14860. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14861. }
  14862. };
  14863. function clampToMaxSize ( image, maxSize ) {
  14864. if ( image.width <= maxSize && image.height <= maxSize ) {
  14865. return image;
  14866. }
  14867. // Warning: Scaling through the canvas will only work with images that use
  14868. // premultiplied alpha.
  14869. var maxDimension = Math.max( image.width, image.height );
  14870. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14871. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14872. var canvas = document.createElement( 'canvas' );
  14873. canvas.width = newWidth;
  14874. canvas.height = newHeight;
  14875. var ctx = canvas.getContext( "2d" );
  14876. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14877. return canvas;
  14878. }
  14879. function setCubeTexture ( texture, slot ) {
  14880. if ( texture.image.length === 6 ) {
  14881. if ( texture.needsUpdate ) {
  14882. if ( ! texture.image.__webglTextureCube ) {
  14883. texture.addEventListener( 'dispose', onTextureDispose );
  14884. texture.image.__webglTextureCube = _gl.createTexture();
  14885. _this.info.memory.textures ++;
  14886. }
  14887. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14888. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14889. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14890. var isCompressed = texture instanceof THREE.CompressedTexture;
  14891. var cubeImage = [];
  14892. for ( var i = 0; i < 6; i ++ ) {
  14893. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14894. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14895. } else {
  14896. cubeImage[ i ] = texture.image[ i ];
  14897. }
  14898. }
  14899. var image = cubeImage[ 0 ],
  14900. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  14901. glFormat = paramThreeToGL( texture.format ),
  14902. glType = paramThreeToGL( texture.type );
  14903. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14904. for ( var i = 0; i < 6; i ++ ) {
  14905. if( !isCompressed ) {
  14906. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14907. } else {
  14908. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14909. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14910. mipmap = mipmaps[ j ];
  14911. if ( texture.format!==THREE.RGBAFormat ) {
  14912. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14913. } else {
  14914. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14915. }
  14916. }
  14917. }
  14918. }
  14919. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14920. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14921. }
  14922. texture.needsUpdate = false;
  14923. if ( texture.onUpdate ) texture.onUpdate();
  14924. } else {
  14925. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14926. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14927. }
  14928. }
  14929. };
  14930. function setCubeTextureDynamic ( texture, slot ) {
  14931. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14932. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14933. };
  14934. // Render targets
  14935. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14936. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14937. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14938. };
  14939. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14940. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14941. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14942. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14943. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14944. /* For some reason this is not working. Defaulting to RGBA4.
  14945. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14946. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14947. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14948. */
  14949. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14950. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14951. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14952. } else {
  14953. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14954. }
  14955. };
  14956. this.setRenderTarget = function ( renderTarget ) {
  14957. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14958. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14959. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14960. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14961. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14962. renderTarget.__webglTexture = _gl.createTexture();
  14963. _this.info.memory.textures ++;
  14964. // Setup texture, create render and frame buffers
  14965. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  14966. glFormat = paramThreeToGL( renderTarget.format ),
  14967. glType = paramThreeToGL( renderTarget.type );
  14968. if ( isCube ) {
  14969. renderTarget.__webglFramebuffer = [];
  14970. renderTarget.__webglRenderbuffer = [];
  14971. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14972. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14973. for ( var i = 0; i < 6; i ++ ) {
  14974. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14975. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14976. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14977. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14978. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14979. }
  14980. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14981. } else {
  14982. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14983. if ( renderTarget.shareDepthFrom ) {
  14984. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14985. } else {
  14986. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14987. }
  14988. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14989. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14990. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14991. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14992. if ( renderTarget.shareDepthFrom ) {
  14993. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14994. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14995. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14996. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14997. }
  14998. } else {
  14999. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15000. }
  15001. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15002. }
  15003. // Release everything
  15004. if ( isCube ) {
  15005. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15006. } else {
  15007. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15008. }
  15009. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15010. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15011. }
  15012. var framebuffer, width, height, vx, vy;
  15013. if ( renderTarget ) {
  15014. if ( isCube ) {
  15015. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15016. } else {
  15017. framebuffer = renderTarget.__webglFramebuffer;
  15018. }
  15019. width = renderTarget.width;
  15020. height = renderTarget.height;
  15021. vx = 0;
  15022. vy = 0;
  15023. } else {
  15024. framebuffer = null;
  15025. width = _viewportWidth;
  15026. height = _viewportHeight;
  15027. vx = _viewportX;
  15028. vy = _viewportY;
  15029. }
  15030. if ( framebuffer !== _currentFramebuffer ) {
  15031. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15032. _gl.viewport( vx, vy, width, height );
  15033. _currentFramebuffer = framebuffer;
  15034. }
  15035. _currentWidth = width;
  15036. _currentHeight = height;
  15037. };
  15038. function updateRenderTargetMipmap ( renderTarget ) {
  15039. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15040. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15041. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15042. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15043. } else {
  15044. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15045. _gl.generateMipmap( _gl.TEXTURE_2D );
  15046. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15047. }
  15048. };
  15049. // Fallback filters for non-power-of-2 textures
  15050. function filterFallback ( f ) {
  15051. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15052. return _gl.NEAREST;
  15053. }
  15054. return _gl.LINEAR;
  15055. };
  15056. // Map three.js constants to WebGL constants
  15057. function paramThreeToGL ( p ) {
  15058. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15059. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15060. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15061. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15062. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15063. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15064. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15065. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15066. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15067. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15068. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15069. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15070. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15071. if ( p === THREE.ByteType ) return _gl.BYTE;
  15072. if ( p === THREE.ShortType ) return _gl.SHORT;
  15073. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15074. if ( p === THREE.IntType ) return _gl.INT;
  15075. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15076. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15077. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15078. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15079. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15080. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15081. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15082. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15083. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15084. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15085. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15086. if ( p === THREE.OneFactor ) return _gl.ONE;
  15087. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15088. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15089. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15090. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15091. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15092. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15093. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15094. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15095. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15096. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15097. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15098. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15099. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15100. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15101. }
  15102. return 0;
  15103. };
  15104. // Allocations
  15105. function allocateBones ( object ) {
  15106. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  15107. return 1024;
  15108. } else {
  15109. // default for when object is not specified
  15110. // ( for example when prebuilding shader
  15111. // to be used with multiple objects )
  15112. //
  15113. // - leave some extra space for other uniforms
  15114. // - limit here is ANGLE's 254 max uniform vectors
  15115. // (up to 54 should be safe)
  15116. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15117. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15118. var maxBones = nVertexMatrices;
  15119. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15120. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  15121. if ( maxBones < object.skeleton.bones.length ) {
  15122. console.warn( "WebGLRenderer: too many bones - " + object.skeleton.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15123. }
  15124. }
  15125. return maxBones;
  15126. }
  15127. };
  15128. function allocateLights( lights ) {
  15129. var dirLights = 0;
  15130. var pointLights = 0;
  15131. var spotLights = 0;
  15132. var hemiLights = 0;
  15133. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15134. var light = lights[ l ];
  15135. if ( light.onlyShadow || light.visible === false ) continue;
  15136. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15137. if ( light instanceof THREE.PointLight ) pointLights ++;
  15138. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15139. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15140. }
  15141. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15142. };
  15143. function allocateShadows( lights ) {
  15144. var maxShadows = 0;
  15145. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15146. var light = lights[ l ];
  15147. if ( ! light.castShadow ) continue;
  15148. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15149. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15150. }
  15151. return maxShadows;
  15152. };
  15153. // Initialization
  15154. function initGL() {
  15155. try {
  15156. var attributes = {
  15157. alpha: _alpha,
  15158. depth: _depth,
  15159. stencil: _stencil,
  15160. antialias: _antialias,
  15161. premultipliedAlpha: _premultipliedAlpha,
  15162. preserveDrawingBuffer: _preserveDrawingBuffer
  15163. };
  15164. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15165. if ( _gl === null ) {
  15166. throw 'Error creating WebGL context.';
  15167. }
  15168. } catch ( error ) {
  15169. console.error( error );
  15170. }
  15171. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15172. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15173. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15174. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15175. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15176. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15177. if ( _glExtensionTextureFloat === null ) {
  15178. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15179. }
  15180. if ( _glExtensionStandardDerivatives === null ) {
  15181. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15182. }
  15183. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15184. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15185. }
  15186. if ( _glExtensionCompressedTextureS3TC === null ) {
  15187. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15188. }
  15189. if ( _glExtensionElementIndexUint === null ) {
  15190. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15191. }
  15192. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15193. _gl.getShaderPrecisionFormat = function() {
  15194. return {
  15195. "rangeMin" : 1,
  15196. "rangeMax" : 1,
  15197. "precision" : 1
  15198. };
  15199. }
  15200. }
  15201. if ( _logarithmicDepthBuffer ) {
  15202. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  15203. }
  15204. };
  15205. function setDefaultGLState () {
  15206. _gl.clearColor( 0, 0, 0, 1 );
  15207. _gl.clearDepth( 1 );
  15208. _gl.clearStencil( 0 );
  15209. _gl.enable( _gl.DEPTH_TEST );
  15210. _gl.depthFunc( _gl.LEQUAL );
  15211. _gl.frontFace( _gl.CCW );
  15212. _gl.cullFace( _gl.BACK );
  15213. _gl.enable( _gl.CULL_FACE );
  15214. _gl.enable( _gl.BLEND );
  15215. _gl.blendEquation( _gl.FUNC_ADD );
  15216. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15217. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15218. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15219. };
  15220. // default plugins (order is important)
  15221. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15222. this.addPrePlugin( this.shadowMapPlugin );
  15223. this.addPostPlugin( new THREE.SpritePlugin() );
  15224. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15225. };
  15226. /**
  15227. * @author szimek / https://github.com/szimek/
  15228. * @author alteredq / http://alteredqualia.com/
  15229. */
  15230. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15231. this.width = width;
  15232. this.height = height;
  15233. options = options || {};
  15234. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15235. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15236. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15237. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15238. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15239. this.offset = new THREE.Vector2( 0, 0 );
  15240. this.repeat = new THREE.Vector2( 1, 1 );
  15241. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15242. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15243. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15244. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15245. this.generateMipmaps = true;
  15246. this.shareDepthFrom = null;
  15247. };
  15248. THREE.WebGLRenderTarget.prototype = {
  15249. constructor: THREE.WebGLRenderTarget,
  15250. setSize: function ( width, height ) {
  15251. this.width = width;
  15252. this.height = height;
  15253. },
  15254. clone: function () {
  15255. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15256. tmp.wrapS = this.wrapS;
  15257. tmp.wrapT = this.wrapT;
  15258. tmp.magFilter = this.magFilter;
  15259. tmp.minFilter = this.minFilter;
  15260. tmp.anisotropy = this.anisotropy;
  15261. tmp.offset.copy( this.offset );
  15262. tmp.repeat.copy( this.repeat );
  15263. tmp.format = this.format;
  15264. tmp.type = this.type;
  15265. tmp.depthBuffer = this.depthBuffer;
  15266. tmp.stencilBuffer = this.stencilBuffer;
  15267. tmp.generateMipmaps = this.generateMipmaps;
  15268. tmp.shareDepthFrom = this.shareDepthFrom;
  15269. return tmp;
  15270. },
  15271. dispose: function () {
  15272. this.dispatchEvent( { type: 'dispose' } );
  15273. }
  15274. };
  15275. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15276. /**
  15277. * @author alteredq / http://alteredqualia.com
  15278. */
  15279. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15280. THREE.WebGLRenderTarget.call( this, width, height, options );
  15281. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15282. };
  15283. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15284. THREE.WebGLProgram = ( function () {
  15285. var programIdCount = 0;
  15286. var generateDefines = function ( defines ) {
  15287. var value, chunk, chunks = [];
  15288. for ( var d in defines ) {
  15289. value = defines[ d ];
  15290. if ( value === false ) continue;
  15291. chunk = "#define " + d + " " + value;
  15292. chunks.push( chunk );
  15293. }
  15294. return chunks.join( "\n" );
  15295. };
  15296. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15297. var uniforms = {};
  15298. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15299. var id = identifiers[ i ];
  15300. uniforms[ id ] = gl.getUniformLocation( program, id );
  15301. }
  15302. return uniforms;
  15303. };
  15304. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15305. var attributes = {};
  15306. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15307. var id = identifiers[ i ];
  15308. attributes[ id ] = gl.getAttribLocation( program, id );
  15309. }
  15310. return attributes;
  15311. };
  15312. return function ( renderer, code, material, parameters ) {
  15313. var _this = renderer;
  15314. var _gl = _this.context;
  15315. var fragmentShader = material.fragmentShader;
  15316. var vertexShader = material.vertexShader;
  15317. var uniforms = material.uniforms;
  15318. var attributes = material.attributes;
  15319. var defines = material.defines;
  15320. var index0AttributeName = material.index0AttributeName;
  15321. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  15322. // programs with morphTargets displace position out of attribute 0
  15323. index0AttributeName = 'position';
  15324. }
  15325. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15326. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15327. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15328. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15329. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15330. }
  15331. // console.log( "building new program " );
  15332. //
  15333. var customDefines = generateDefines( defines );
  15334. //
  15335. var program = _gl.createProgram();
  15336. var prefix_vertex, prefix_fragment;
  15337. if ( material instanceof THREE.RawShaderMaterial ) {
  15338. prefix_vertex = '';
  15339. prefix_fragment = '';
  15340. } else {
  15341. prefix_vertex = [
  15342. "precision " + parameters.precision + " float;",
  15343. "precision " + parameters.precision + " int;",
  15344. customDefines,
  15345. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15346. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15347. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15348. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15349. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15350. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15351. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15352. "#define MAX_SHADOWS " + parameters.maxShadows,
  15353. "#define MAX_BONES " + parameters.maxBones,
  15354. parameters.map ? "#define USE_MAP" : "",
  15355. parameters.envMap ? "#define USE_ENVMAP" : "",
  15356. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15357. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15358. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15359. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15360. parameters.vertexColors ? "#define USE_COLOR" : "",
  15361. parameters.skinning ? "#define USE_SKINNING" : "",
  15362. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15363. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15364. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15365. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15366. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15367. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15368. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15369. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15370. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15371. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15372. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15373. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15374. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15375. "uniform mat4 modelMatrix;",
  15376. "uniform mat4 modelViewMatrix;",
  15377. "uniform mat4 projectionMatrix;",
  15378. "uniform mat4 viewMatrix;",
  15379. "uniform mat3 normalMatrix;",
  15380. "uniform vec3 cameraPosition;",
  15381. "attribute vec3 position;",
  15382. "attribute vec3 normal;",
  15383. "attribute vec2 uv;",
  15384. "attribute vec2 uv2;",
  15385. "#ifdef USE_COLOR",
  15386. " attribute vec3 color;",
  15387. "#endif",
  15388. "#ifdef USE_MORPHTARGETS",
  15389. " attribute vec3 morphTarget0;",
  15390. " attribute vec3 morphTarget1;",
  15391. " attribute vec3 morphTarget2;",
  15392. " attribute vec3 morphTarget3;",
  15393. " #ifdef USE_MORPHNORMALS",
  15394. " attribute vec3 morphNormal0;",
  15395. " attribute vec3 morphNormal1;",
  15396. " attribute vec3 morphNormal2;",
  15397. " attribute vec3 morphNormal3;",
  15398. " #else",
  15399. " attribute vec3 morphTarget4;",
  15400. " attribute vec3 morphTarget5;",
  15401. " attribute vec3 morphTarget6;",
  15402. " attribute vec3 morphTarget7;",
  15403. " #endif",
  15404. "#endif",
  15405. "#ifdef USE_SKINNING",
  15406. " attribute vec4 skinIndex;",
  15407. " attribute vec4 skinWeight;",
  15408. "#endif",
  15409. ""
  15410. ].join( '\n' );
  15411. prefix_fragment = [
  15412. "precision " + parameters.precision + " float;",
  15413. "precision " + parameters.precision + " int;",
  15414. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15415. customDefines,
  15416. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15417. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15418. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15419. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15420. "#define MAX_SHADOWS " + parameters.maxShadows,
  15421. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15422. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15423. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15424. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15425. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15426. parameters.map ? "#define USE_MAP" : "",
  15427. parameters.envMap ? "#define USE_ENVMAP" : "",
  15428. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15429. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15430. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15431. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15432. parameters.vertexColors ? "#define USE_COLOR" : "",
  15433. parameters.metal ? "#define METAL" : "",
  15434. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15435. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15436. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15437. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15438. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15439. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15440. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15441. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15442. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15443. "uniform mat4 viewMatrix;",
  15444. "uniform vec3 cameraPosition;",
  15445. ""
  15446. ].join( '\n' );
  15447. }
  15448. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15449. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15450. _gl.attachShader( program, glVertexShader );
  15451. _gl.attachShader( program, glFragmentShader );
  15452. if ( index0AttributeName !== undefined ) {
  15453. // Force a particular attribute to index 0.
  15454. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15455. // And, color, for example is often automatically bound to index 0 so disabling it
  15456. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15457. }
  15458. _gl.linkProgram( program );
  15459. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15460. console.error( 'Could not initialise shader' );
  15461. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15462. console.error( 'gl.getError()', _gl.getError() );
  15463. }
  15464. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15465. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15466. }
  15467. // clean up
  15468. _gl.deleteShader( glVertexShader );
  15469. _gl.deleteShader( glFragmentShader );
  15470. // cache uniform locations
  15471. var identifiers = [
  15472. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15473. 'morphTargetInfluences'
  15474. ];
  15475. if ( parameters.useVertexTexture ) {
  15476. identifiers.push( 'boneTexture' );
  15477. identifiers.push( 'boneTextureWidth' );
  15478. identifiers.push( 'boneTextureHeight' );
  15479. } else {
  15480. identifiers.push( 'boneGlobalMatrices' );
  15481. }
  15482. if ( parameters.logarithmicDepthBuffer ) {
  15483. identifiers.push('logDepthBufFC');
  15484. }
  15485. for ( var u in uniforms ) {
  15486. identifiers.push( u );
  15487. }
  15488. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  15489. // cache attributes locations
  15490. identifiers = [
  15491. "position", "normal", "uv", "uv2", "tangent", "color",
  15492. "skinIndex", "skinWeight", "lineDistance"
  15493. ];
  15494. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15495. identifiers.push( "morphTarget" + i );
  15496. }
  15497. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15498. identifiers.push( "morphNormal" + i );
  15499. }
  15500. for ( var a in attributes ) {
  15501. identifiers.push( a );
  15502. }
  15503. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  15504. //
  15505. this.id = programIdCount ++;
  15506. this.code = code;
  15507. this.usedTimes = 1;
  15508. this.program = program;
  15509. this.vertexShader = glVertexShader;
  15510. this.fragmentShader = glFragmentShader;
  15511. return this;
  15512. };
  15513. } )();
  15514. THREE.WebGLShader = ( function () {
  15515. var addLineNumbers = function ( string ) {
  15516. var lines = string.split( '\n' );
  15517. for ( var i = 0; i < lines.length; i ++ ) {
  15518. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15519. }
  15520. return lines.join( '\n' );
  15521. };
  15522. return function ( gl, type, string ) {
  15523. var shader = gl.createShader( type );
  15524. gl.shaderSource( shader, string );
  15525. gl.compileShader( shader );
  15526. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  15527. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  15528. }
  15529. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15530. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  15531. console.error( addLineNumbers( string ) );
  15532. }
  15533. // --enable-privileged-webgl-extension
  15534. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15535. return shader;
  15536. };
  15537. } )();
  15538. /**
  15539. * @author mrdoob / http://mrdoob.com/
  15540. */
  15541. THREE.RenderableVertex = function () {
  15542. this.position = new THREE.Vector3();
  15543. this.positionWorld = new THREE.Vector3();
  15544. this.positionScreen = new THREE.Vector4();
  15545. this.visible = true;
  15546. };
  15547. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15548. this.positionWorld.copy( vertex.positionWorld );
  15549. this.positionScreen.copy( vertex.positionScreen );
  15550. };
  15551. /**
  15552. * @author mrdoob / http://mrdoob.com/
  15553. */
  15554. THREE.RenderableFace = function () {
  15555. this.id = 0;
  15556. this.v1 = new THREE.RenderableVertex();
  15557. this.v2 = new THREE.RenderableVertex();
  15558. this.v3 = new THREE.RenderableVertex();
  15559. this.normalModel = new THREE.Vector3();
  15560. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15561. this.vertexNormalsLength = 0;
  15562. this.color = null;
  15563. this.material = null;
  15564. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  15565. this.z = 0;
  15566. };
  15567. /**
  15568. * @author mrdoob / http://mrdoob.com/
  15569. */
  15570. THREE.RenderableObject = function () {
  15571. this.id = 0;
  15572. this.object = null;
  15573. this.z = 0;
  15574. };
  15575. /**
  15576. * @author mrdoob / http://mrdoob.com/
  15577. */
  15578. THREE.RenderableSprite = function () {
  15579. this.id = 0;
  15580. this.object = null;
  15581. this.x = 0;
  15582. this.y = 0;
  15583. this.z = 0;
  15584. this.rotation = 0;
  15585. this.scale = new THREE.Vector2();
  15586. this.material = null;
  15587. };
  15588. /**
  15589. * @author mrdoob / http://mrdoob.com/
  15590. */
  15591. THREE.RenderableLine = function () {
  15592. this.id = 0;
  15593. this.v1 = new THREE.RenderableVertex();
  15594. this.v2 = new THREE.RenderableVertex();
  15595. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15596. this.material = null;
  15597. this.z = 0;
  15598. };
  15599. /**
  15600. * @author mrdoob / http://mrdoob.com/
  15601. * @author alteredq / http://alteredqualia.com/
  15602. */
  15603. THREE.GeometryUtils = {
  15604. // Merge two geometries or geometry and geometry from object (using object's transform)
  15605. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15606. console.warn( 'DEPRECATED: GeometryUtils\'s .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15607. var matrix;
  15608. if ( geometry2 instanceof THREE.Mesh ) {
  15609. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15610. matrix = geometry2.matrix;
  15611. geometry2 = geometry2.geometry;
  15612. }
  15613. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15614. },
  15615. // Get random point in triangle (via barycentric coordinates)
  15616. // (uniform distribution)
  15617. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15618. randomPointInTriangle: function () {
  15619. var vector = new THREE.Vector3();
  15620. return function ( vectorA, vectorB, vectorC ) {
  15621. var point = new THREE.Vector3();
  15622. var a = THREE.Math.random16();
  15623. var b = THREE.Math.random16();
  15624. if ( ( a + b ) > 1 ) {
  15625. a = 1 - a;
  15626. b = 1 - b;
  15627. }
  15628. var c = 1 - a - b;
  15629. point.copy( vectorA );
  15630. point.multiplyScalar( a );
  15631. vector.copy( vectorB );
  15632. vector.multiplyScalar( b );
  15633. point.add( vector );
  15634. vector.copy( vectorC );
  15635. vector.multiplyScalar( c );
  15636. point.add( vector );
  15637. return point;
  15638. };
  15639. }(),
  15640. // Get random point in face (triangle)
  15641. // (uniform distribution)
  15642. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15643. var vA, vB, vC;
  15644. vA = geometry.vertices[ face.a ];
  15645. vB = geometry.vertices[ face.b ];
  15646. vC = geometry.vertices[ face.c ];
  15647. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15648. },
  15649. // Get uniformly distributed random points in mesh
  15650. // - create array with cumulative sums of face areas
  15651. // - pick random number from 0 to total area
  15652. // - find corresponding place in area array by binary search
  15653. // - get random point in face
  15654. randomPointsInGeometry: function ( geometry, n ) {
  15655. var face, i,
  15656. faces = geometry.faces,
  15657. vertices = geometry.vertices,
  15658. il = faces.length,
  15659. totalArea = 0,
  15660. cumulativeAreas = [],
  15661. vA, vB, vC, vD;
  15662. // precompute face areas
  15663. for ( i = 0; i < il; i ++ ) {
  15664. face = faces[ i ];
  15665. vA = vertices[ face.a ];
  15666. vB = vertices[ face.b ];
  15667. vC = vertices[ face.c ];
  15668. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15669. totalArea += face._area;
  15670. cumulativeAreas[ i ] = totalArea;
  15671. }
  15672. // binary search cumulative areas array
  15673. function binarySearchIndices( value ) {
  15674. function binarySearch( start, end ) {
  15675. // return closest larger index
  15676. // if exact number is not found
  15677. if ( end < start )
  15678. return start;
  15679. var mid = start + Math.floor( ( end - start ) / 2 );
  15680. if ( cumulativeAreas[ mid ] > value ) {
  15681. return binarySearch( start, mid - 1 );
  15682. } else if ( cumulativeAreas[ mid ] < value ) {
  15683. return binarySearch( mid + 1, end );
  15684. } else {
  15685. return mid;
  15686. }
  15687. }
  15688. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15689. return result;
  15690. }
  15691. // pick random face weighted by face area
  15692. var r, index,
  15693. result = [];
  15694. var stats = {};
  15695. for ( i = 0; i < n; i ++ ) {
  15696. r = THREE.Math.random16() * totalArea;
  15697. index = binarySearchIndices( r );
  15698. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15699. if ( ! stats[ index ] ) {
  15700. stats[ index ] = 1;
  15701. } else {
  15702. stats[ index ] += 1;
  15703. }
  15704. }
  15705. return result;
  15706. },
  15707. // Get triangle area (half of parallelogram)
  15708. // http://mathworld.wolfram.com/TriangleArea.html
  15709. triangleArea: function () {
  15710. var vector1 = new THREE.Vector3();
  15711. var vector2 = new THREE.Vector3();
  15712. return function ( vectorA, vectorB, vectorC ) {
  15713. vector1.subVectors( vectorB, vectorA );
  15714. vector2.subVectors( vectorC, vectorA );
  15715. vector1.cross( vector2 );
  15716. return 0.5 * vector1.length();
  15717. };
  15718. }(),
  15719. // Center geometry so that 0,0,0 is in center of bounding box
  15720. center: function ( geometry ) {
  15721. geometry.computeBoundingBox();
  15722. var bb = geometry.boundingBox;
  15723. var offset = new THREE.Vector3();
  15724. offset.addVectors( bb.min, bb.max );
  15725. offset.multiplyScalar( -0.5 );
  15726. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15727. geometry.computeBoundingBox();
  15728. return offset;
  15729. }
  15730. };
  15731. /**
  15732. * @author alteredq / http://alteredqualia.com/
  15733. * @author mrdoob / http://mrdoob.com/
  15734. */
  15735. THREE.ImageUtils = {
  15736. crossOrigin: undefined,
  15737. loadTexture: function ( url, mapping, onLoad, onError ) {
  15738. var loader = new THREE.ImageLoader();
  15739. loader.crossOrigin = this.crossOrigin;
  15740. var texture = new THREE.Texture( undefined, mapping );
  15741. var image = loader.load( url, function () {
  15742. texture.needsUpdate = true;
  15743. if ( onLoad ) onLoad( texture );
  15744. }, undefined, function ( event ) {
  15745. if ( onError ) onError( event );
  15746. } );
  15747. texture.image = image;
  15748. texture.sourceFile = url;
  15749. return texture;
  15750. },
  15751. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15752. var texture = new THREE.CompressedTexture();
  15753. texture.mapping = mapping;
  15754. var request = new XMLHttpRequest();
  15755. request.onload = function () {
  15756. var buffer = request.response;
  15757. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15758. texture.format = dds.format;
  15759. texture.mipmaps = dds.mipmaps;
  15760. texture.image.width = dds.width;
  15761. texture.image.height = dds.height;
  15762. // gl.generateMipmap fails for compressed textures
  15763. // mipmaps must be embedded in the DDS file
  15764. // or texture filters must not use mipmapping
  15765. texture.generateMipmaps = false;
  15766. texture.needsUpdate = true;
  15767. if ( onLoad ) onLoad( texture );
  15768. }
  15769. request.onerror = onError;
  15770. request.open( 'GET', url, true );
  15771. request.responseType = "arraybuffer";
  15772. request.send( null );
  15773. return texture;
  15774. },
  15775. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15776. var images = [];
  15777. images.loadCount = 0;
  15778. var loader = new THREE.ImageLoader();
  15779. loader.crossOrigin = this.crossOrigin;
  15780. var texture = new THREE.Texture();
  15781. texture.image = images;
  15782. if ( mapping !== undefined ) texture.mapping = mapping;
  15783. // no flipping needed for cube textures
  15784. texture.flipY = false;
  15785. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15786. var cubeImage = loader.load( array[i], function () {
  15787. images.loadCount += 1;
  15788. if ( images.loadCount === 6 ) {
  15789. texture.needsUpdate = true;
  15790. if ( onLoad ) onLoad( texture );
  15791. }
  15792. } );
  15793. images[ i ] = cubeImage;
  15794. }
  15795. return texture;
  15796. },
  15797. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15798. var images = [];
  15799. images.loadCount = 0;
  15800. var texture = new THREE.CompressedTexture();
  15801. texture.image = images;
  15802. if ( mapping !== undefined ) texture.mapping = mapping;
  15803. // no flipping for cube textures
  15804. // (also flipping doesn't work for compressed textures )
  15805. texture.flipY = false;
  15806. // can't generate mipmaps for compressed textures
  15807. // mips must be embedded in DDS files
  15808. texture.generateMipmaps = false;
  15809. var generateCubeFaceCallback = function ( rq, img ) {
  15810. return function () {
  15811. var buffer = rq.response;
  15812. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15813. img.format = dds.format;
  15814. img.mipmaps = dds.mipmaps;
  15815. img.width = dds.width;
  15816. img.height = dds.height;
  15817. images.loadCount += 1;
  15818. if ( images.loadCount === 6 ) {
  15819. texture.format = dds.format;
  15820. texture.needsUpdate = true;
  15821. if ( onLoad ) onLoad( texture );
  15822. }
  15823. }
  15824. }
  15825. // compressed cubemap textures as 6 separate DDS files
  15826. if ( array instanceof Array ) {
  15827. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15828. var cubeImage = {};
  15829. images[ i ] = cubeImage;
  15830. var request = new XMLHttpRequest();
  15831. request.onload = generateCubeFaceCallback( request, cubeImage );
  15832. request.onerror = onError;
  15833. var url = array[ i ];
  15834. request.open( 'GET', url, true );
  15835. request.responseType = "arraybuffer";
  15836. request.send( null );
  15837. }
  15838. // compressed cubemap texture stored in a single DDS file
  15839. } else {
  15840. var url = array;
  15841. var request = new XMLHttpRequest();
  15842. request.onload = function( ) {
  15843. var buffer = request.response;
  15844. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15845. if ( dds.isCubemap ) {
  15846. var faces = dds.mipmaps.length / dds.mipmapCount;
  15847. for ( var f = 0; f < faces; f ++ ) {
  15848. images[ f ] = { mipmaps : [] };
  15849. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15850. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15851. images[ f ].format = dds.format;
  15852. images[ f ].width = dds.width;
  15853. images[ f ].height = dds.height;
  15854. }
  15855. }
  15856. texture.format = dds.format;
  15857. texture.needsUpdate = true;
  15858. if ( onLoad ) onLoad( texture );
  15859. }
  15860. }
  15861. request.onerror = onError;
  15862. request.open( 'GET', url, true );
  15863. request.responseType = "arraybuffer";
  15864. request.send( null );
  15865. }
  15866. return texture;
  15867. },
  15868. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15869. var images = [];
  15870. images.loadCount = 0;
  15871. var texture = new THREE.CompressedTexture();
  15872. texture.image = images;
  15873. if ( mapping !== undefined ) texture.mapping = mapping;
  15874. // no flipping for cube textures
  15875. // (also flipping doesn't work for compressed textures )
  15876. texture.flipY = false;
  15877. // can't generate mipmaps for compressed textures
  15878. // mips must be embedded in DDS files
  15879. texture.generateMipmaps = false;
  15880. {
  15881. var request = new XMLHttpRequest();
  15882. request.onload = function( ) {
  15883. var buffer = request.response;
  15884. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15885. if ( dds.isCubemap ) {
  15886. var faces = dds.mipmaps.length / dds.mipmapCount;
  15887. for ( var f = 0; f < faces; f ++ ) {
  15888. images[ f ] = { mipmaps : [] };
  15889. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15890. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15891. images[ f ].format = dds.format;
  15892. images[ f ].width = dds.width;
  15893. images[ f ].height = dds.height;
  15894. }
  15895. }
  15896. } else {
  15897. texture.image.width = dds.width;
  15898. texture.image.height = dds.height;
  15899. texture.mipmaps = dds.mipmaps;
  15900. }
  15901. texture.format = dds.format;
  15902. texture.needsUpdate = true;
  15903. if ( onLoad ) onLoad( texture );
  15904. }
  15905. request.onerror = onError;
  15906. request.open( 'GET', url, true );
  15907. request.responseType = "arraybuffer";
  15908. request.send( null );
  15909. }
  15910. return texture;
  15911. },
  15912. parseDDS: function ( buffer, loadMipmaps ) {
  15913. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15914. // Adapted from @toji's DDS utils
  15915. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15916. // All values and structures referenced from:
  15917. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15918. var DDS_MAGIC = 0x20534444;
  15919. var DDSD_CAPS = 0x1,
  15920. DDSD_HEIGHT = 0x2,
  15921. DDSD_WIDTH = 0x4,
  15922. DDSD_PITCH = 0x8,
  15923. DDSD_PIXELFORMAT = 0x1000,
  15924. DDSD_MIPMAPCOUNT = 0x20000,
  15925. DDSD_LINEARSIZE = 0x80000,
  15926. DDSD_DEPTH = 0x800000;
  15927. var DDSCAPS_COMPLEX = 0x8,
  15928. DDSCAPS_MIPMAP = 0x400000,
  15929. DDSCAPS_TEXTURE = 0x1000;
  15930. var DDSCAPS2_CUBEMAP = 0x200,
  15931. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15932. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15933. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15934. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15935. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15936. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15937. DDSCAPS2_VOLUME = 0x200000;
  15938. var DDPF_ALPHAPIXELS = 0x1,
  15939. DDPF_ALPHA = 0x2,
  15940. DDPF_FOURCC = 0x4,
  15941. DDPF_RGB = 0x40,
  15942. DDPF_YUV = 0x200,
  15943. DDPF_LUMINANCE = 0x20000;
  15944. function fourCCToInt32( value ) {
  15945. return value.charCodeAt(0) +
  15946. (value.charCodeAt(1) << 8) +
  15947. (value.charCodeAt(2) << 16) +
  15948. (value.charCodeAt(3) << 24);
  15949. }
  15950. function int32ToFourCC( value ) {
  15951. return String.fromCharCode(
  15952. value & 0xff,
  15953. (value >> 8) & 0xff,
  15954. (value >> 16) & 0xff,
  15955. (value >> 24) & 0xff
  15956. );
  15957. }
  15958. function loadARGBMip( buffer, dataOffset, width, height ) {
  15959. var dataLength = width*height*4;
  15960. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15961. var byteArray = new Uint8Array( dataLength );
  15962. var dst = 0;
  15963. var src = 0;
  15964. for ( var y = 0; y < height; y++ ) {
  15965. for ( var x = 0; x < width; x++ ) {
  15966. var b = srcBuffer[src]; src++;
  15967. var g = srcBuffer[src]; src++;
  15968. var r = srcBuffer[src]; src++;
  15969. var a = srcBuffer[src]; src++;
  15970. byteArray[dst] = r; dst++; //r
  15971. byteArray[dst] = g; dst++; //g
  15972. byteArray[dst] = b; dst++; //b
  15973. byteArray[dst] = a; dst++; //a
  15974. }
  15975. }
  15976. return byteArray;
  15977. }
  15978. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15979. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15980. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15981. var headerLengthInt = 31; // The header length in 32 bit ints
  15982. // Offsets into the header array
  15983. var off_magic = 0;
  15984. var off_size = 1;
  15985. var off_flags = 2;
  15986. var off_height = 3;
  15987. var off_width = 4;
  15988. var off_mipmapCount = 7;
  15989. var off_pfFlags = 20;
  15990. var off_pfFourCC = 21;
  15991. var off_RGBBitCount = 22;
  15992. var off_RBitMask = 23;
  15993. var off_GBitMask = 24;
  15994. var off_BBitMask = 25;
  15995. var off_ABitMask = 26;
  15996. var off_caps = 27;
  15997. var off_caps2 = 28;
  15998. var off_caps3 = 29;
  15999. var off_caps4 = 30;
  16000. // Parse header
  16001. var header = new Int32Array( buffer, 0, headerLengthInt );
  16002. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16003. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16004. return dds;
  16005. }
  16006. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16007. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16008. return dds;
  16009. }
  16010. var blockBytes;
  16011. var fourCC = header[ off_pfFourCC ];
  16012. var isRGBAUncompressed = false;
  16013. switch ( fourCC ) {
  16014. case FOURCC_DXT1:
  16015. blockBytes = 8;
  16016. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16017. break;
  16018. case FOURCC_DXT3:
  16019. blockBytes = 16;
  16020. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16021. break;
  16022. case FOURCC_DXT5:
  16023. blockBytes = 16;
  16024. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16025. break;
  16026. default:
  16027. if( header[off_RGBBitCount] ==32
  16028. && header[off_RBitMask]&0xff0000
  16029. && header[off_GBitMask]&0xff00
  16030. && header[off_BBitMask]&0xff
  16031. && header[off_ABitMask]&0xff000000 ) {
  16032. isRGBAUncompressed = true;
  16033. blockBytes = 64;
  16034. dds.format = THREE.RGBAFormat;
  16035. } else {
  16036. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16037. return dds;
  16038. }
  16039. }
  16040. dds.mipmapCount = 1;
  16041. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16042. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16043. }
  16044. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16045. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16046. dds.width = header[ off_width ];
  16047. dds.height = header[ off_height ];
  16048. var dataOffset = header[ off_size ] + 4;
  16049. // Extract mipmaps buffers
  16050. var width = dds.width;
  16051. var height = dds.height;
  16052. var faces = dds.isCubemap ? 6 : 1;
  16053. for ( var face = 0; face < faces; face ++ ) {
  16054. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16055. if( isRGBAUncompressed ) {
  16056. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16057. var dataLength = byteArray.length;
  16058. } else {
  16059. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16060. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16061. }
  16062. var mipmap = { "data": byteArray, "width": width, "height": height };
  16063. dds.mipmaps.push( mipmap );
  16064. dataOffset += dataLength;
  16065. width = Math.max( width * 0.5, 1 );
  16066. height = Math.max( height * 0.5, 1 );
  16067. }
  16068. width = dds.width;
  16069. height = dds.height;
  16070. }
  16071. return dds;
  16072. },
  16073. getNormalMap: function ( image, depth ) {
  16074. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16075. var cross = function ( a, b ) {
  16076. 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 ] ];
  16077. }
  16078. var subtract = function ( a, b ) {
  16079. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16080. }
  16081. var normalize = function ( a ) {
  16082. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16083. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16084. }
  16085. depth = depth | 1;
  16086. var width = image.width;
  16087. var height = image.height;
  16088. var canvas = document.createElement( 'canvas' );
  16089. canvas.width = width;
  16090. canvas.height = height;
  16091. var context = canvas.getContext( '2d' );
  16092. context.drawImage( image, 0, 0 );
  16093. var data = context.getImageData( 0, 0, width, height ).data;
  16094. var imageData = context.createImageData( width, height );
  16095. var output = imageData.data;
  16096. for ( var x = 0; x < width; x ++ ) {
  16097. for ( var y = 0; y < height; y ++ ) {
  16098. var ly = y - 1 < 0 ? 0 : y - 1;
  16099. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16100. var lx = x - 1 < 0 ? 0 : x - 1;
  16101. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16102. var points = [];
  16103. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16104. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16105. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16106. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16107. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16108. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16109. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16110. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16111. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16112. var normals = [];
  16113. var num_points = points.length;
  16114. for ( var i = 0; i < num_points; i ++ ) {
  16115. var v1 = points[ i ];
  16116. var v2 = points[ ( i + 1 ) % num_points ];
  16117. v1 = subtract( v1, origin );
  16118. v2 = subtract( v2, origin );
  16119. normals.push( normalize( cross( v1, v2 ) ) );
  16120. }
  16121. var normal = [ 0, 0, 0 ];
  16122. for ( var i = 0; i < normals.length; i ++ ) {
  16123. normal[ 0 ] += normals[ i ][ 0 ];
  16124. normal[ 1 ] += normals[ i ][ 1 ];
  16125. normal[ 2 ] += normals[ i ][ 2 ];
  16126. }
  16127. normal[ 0 ] /= normals.length;
  16128. normal[ 1 ] /= normals.length;
  16129. normal[ 2 ] /= normals.length;
  16130. var idx = ( y * width + x ) * 4;
  16131. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16132. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16133. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16134. output[ idx + 3 ] = 255;
  16135. }
  16136. }
  16137. context.putImageData( imageData, 0, 0 );
  16138. return canvas;
  16139. },
  16140. generateDataTexture: function ( width, height, color ) {
  16141. var size = width * height;
  16142. var data = new Uint8Array( 3 * size );
  16143. var r = Math.floor( color.r * 255 );
  16144. var g = Math.floor( color.g * 255 );
  16145. var b = Math.floor( color.b * 255 );
  16146. for ( var i = 0; i < size; i ++ ) {
  16147. data[ i * 3 ] = r;
  16148. data[ i * 3 + 1 ] = g;
  16149. data[ i * 3 + 2 ] = b;
  16150. }
  16151. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16152. texture.needsUpdate = true;
  16153. return texture;
  16154. }
  16155. };
  16156. /**
  16157. * @author alteredq / http://alteredqualia.com/
  16158. */
  16159. THREE.SceneUtils = {
  16160. createMultiMaterialObject: function ( geometry, materials ) {
  16161. var group = new THREE.Object3D();
  16162. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16163. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16164. }
  16165. return group;
  16166. },
  16167. detach : function ( child, parent, scene ) {
  16168. child.applyMatrix( parent.matrixWorld );
  16169. parent.remove( child );
  16170. scene.add( child );
  16171. },
  16172. attach: function ( child, scene, parent ) {
  16173. var matrixWorldInverse = new THREE.Matrix4();
  16174. matrixWorldInverse.getInverse( parent.matrixWorld );
  16175. child.applyMatrix( matrixWorldInverse );
  16176. scene.remove( child );
  16177. parent.add( child );
  16178. }
  16179. };
  16180. /**
  16181. * @author zz85 / http://www.lab4games.net/zz85/blog
  16182. * @author alteredq / http://alteredqualia.com/
  16183. *
  16184. * For Text operations in three.js (See TextGeometry)
  16185. *
  16186. * It uses techniques used in:
  16187. *
  16188. * typeface.js and canvastext
  16189. * For converting fonts and rendering with javascript
  16190. * http://typeface.neocracy.org
  16191. *
  16192. * Triangulation ported from AS3
  16193. * Simple Polygon Triangulation
  16194. * http://actionsnippet.com/?p=1462
  16195. *
  16196. * A Method to triangulate shapes with holes
  16197. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16198. *
  16199. */
  16200. THREE.FontUtils = {
  16201. faces : {},
  16202. // Just for now. face[weight][style]
  16203. face : "helvetiker",
  16204. weight: "normal",
  16205. style : "normal",
  16206. size : 150,
  16207. divisions : 10,
  16208. getFace : function() {
  16209. return this.faces[ this.face ][ this.weight ][ this.style ];
  16210. },
  16211. loadFace : function( data ) {
  16212. var family = data.familyName.toLowerCase();
  16213. var ThreeFont = this;
  16214. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16215. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16216. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16217. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16218. return data;
  16219. },
  16220. drawText : function( text ) {
  16221. var characterPts = [], allPts = [];
  16222. // RenderText
  16223. var i, p,
  16224. face = this.getFace(),
  16225. scale = this.size / face.resolution,
  16226. offset = 0,
  16227. chars = String( text ).split( '' ),
  16228. length = chars.length;
  16229. var fontPaths = [];
  16230. for ( i = 0; i < length; i ++ ) {
  16231. var path = new THREE.Path();
  16232. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16233. offset += ret.offset;
  16234. fontPaths.push( ret.path );
  16235. }
  16236. // get the width
  16237. var width = offset / 2;
  16238. //
  16239. // for ( p = 0; p < allPts.length; p++ ) {
  16240. //
  16241. // allPts[ p ].x -= width;
  16242. //
  16243. // }
  16244. //var extract = this.extractPoints( allPts, characterPts );
  16245. //extract.contour = allPts;
  16246. //extract.paths = fontPaths;
  16247. //extract.offset = width;
  16248. return { paths : fontPaths, offset : width };
  16249. },
  16250. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16251. var pts = [];
  16252. var i, i2, divisions,
  16253. outline, action, length,
  16254. scaleX, scaleY,
  16255. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16256. laste,
  16257. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16258. if ( !glyph ) return;
  16259. if ( glyph.o ) {
  16260. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16261. length = outline.length;
  16262. scaleX = scale;
  16263. scaleY = scale;
  16264. for ( i = 0; i < length; ) {
  16265. action = outline[ i ++ ];
  16266. //console.log( action );
  16267. switch( action ) {
  16268. case 'm':
  16269. // Move To
  16270. x = outline[ i++ ] * scaleX + offset;
  16271. y = outline[ i++ ] * scaleY;
  16272. path.moveTo( x, y );
  16273. break;
  16274. case 'l':
  16275. // Line To
  16276. x = outline[ i++ ] * scaleX + offset;
  16277. y = outline[ i++ ] * scaleY;
  16278. path.lineTo(x,y);
  16279. break;
  16280. case 'q':
  16281. // QuadraticCurveTo
  16282. cpx = outline[ i++ ] * scaleX + offset;
  16283. cpy = outline[ i++ ] * scaleY;
  16284. cpx1 = outline[ i++ ] * scaleX + offset;
  16285. cpy1 = outline[ i++ ] * scaleY;
  16286. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16287. laste = pts[ pts.length - 1 ];
  16288. if ( laste ) {
  16289. cpx0 = laste.x;
  16290. cpy0 = laste.y;
  16291. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16292. var t = i2 / divisions;
  16293. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16294. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16295. }
  16296. }
  16297. break;
  16298. case 'b':
  16299. // Cubic Bezier Curve
  16300. cpx = outline[ i++ ] * scaleX + offset;
  16301. cpy = outline[ i++ ] * scaleY;
  16302. cpx1 = outline[ i++ ] * scaleX + offset;
  16303. cpy1 = outline[ i++ ] * -scaleY;
  16304. cpx2 = outline[ i++ ] * scaleX + offset;
  16305. cpy2 = outline[ i++ ] * -scaleY;
  16306. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16307. laste = pts[ pts.length - 1 ];
  16308. if ( laste ) {
  16309. cpx0 = laste.x;
  16310. cpy0 = laste.y;
  16311. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16312. var t = i2 / divisions;
  16313. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16314. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16315. }
  16316. }
  16317. break;
  16318. }
  16319. }
  16320. }
  16321. return { offset: glyph.ha*scale, path:path};
  16322. }
  16323. };
  16324. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16325. // Parameters
  16326. parameters = parameters || {};
  16327. var size = parameters.size !== undefined ? parameters.size : 100;
  16328. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16329. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16330. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16331. var style = parameters.style !== undefined ? parameters.style : "normal";
  16332. THREE.FontUtils.size = size;
  16333. THREE.FontUtils.divisions = curveSegments;
  16334. THREE.FontUtils.face = font;
  16335. THREE.FontUtils.weight = weight;
  16336. THREE.FontUtils.style = style;
  16337. // Get a Font data json object
  16338. var data = THREE.FontUtils.drawText( text );
  16339. var paths = data.paths;
  16340. var shapes = [];
  16341. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16342. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16343. }
  16344. return shapes;
  16345. };
  16346. /**
  16347. * This code is a quick port of code written in C++ which was submitted to
  16348. * flipcode.com by John W. Ratcliff // July 22, 2000
  16349. * See original code and more information here:
  16350. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16351. *
  16352. * ported to actionscript by Zevan Rosser
  16353. * www.actionsnippet.com
  16354. *
  16355. * ported to javascript by Joshua Koo
  16356. * http://www.lab4games.net/zz85/blog
  16357. *
  16358. */
  16359. ( function( namespace ) {
  16360. var EPSILON = 0.0000000001;
  16361. // takes in an contour array and returns
  16362. var process = function( contour, indices ) {
  16363. var n = contour.length;
  16364. if ( n < 3 ) return null;
  16365. var result = [],
  16366. verts = [],
  16367. vertIndices = [];
  16368. /* we want a counter-clockwise polygon in verts */
  16369. var u, v, w;
  16370. if ( area( contour ) > 0.0 ) {
  16371. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16372. } else {
  16373. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16374. }
  16375. var nv = n;
  16376. /* remove nv - 2 vertices, creating 1 triangle every time */
  16377. var count = 2 * nv; /* error detection */
  16378. for( v = nv - 1; nv > 2; ) {
  16379. /* if we loop, it is probably a non-simple polygon */
  16380. if ( ( count-- ) <= 0 ) {
  16381. //** Triangulate: ERROR - probable bad polygon!
  16382. //throw ( "Warning, unable to triangulate polygon!" );
  16383. //return null;
  16384. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16385. console.log( "Warning, unable to triangulate polygon!" );
  16386. if ( indices ) return vertIndices;
  16387. return result;
  16388. }
  16389. /* three consecutive vertices in current polygon, <u,v,w> */
  16390. u = v; if ( nv <= u ) u = 0; /* previous */
  16391. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16392. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16393. if ( snip( contour, u, v, w, nv, verts ) ) {
  16394. var a, b, c, s, t;
  16395. /* true names of the vertices */
  16396. a = verts[ u ];
  16397. b = verts[ v ];
  16398. c = verts[ w ];
  16399. /* output Triangle */
  16400. result.push( [ contour[ a ],
  16401. contour[ b ],
  16402. contour[ c ] ] );
  16403. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16404. /* remove v from the remaining polygon */
  16405. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16406. verts[ s ] = verts[ t ];
  16407. }
  16408. nv--;
  16409. /* reset error detection counter */
  16410. count = 2 * nv;
  16411. }
  16412. }
  16413. if ( indices ) return vertIndices;
  16414. return result;
  16415. };
  16416. // calculate area of the contour polygon
  16417. var area = function ( contour ) {
  16418. var n = contour.length;
  16419. var a = 0.0;
  16420. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16421. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16422. }
  16423. return a * 0.5;
  16424. };
  16425. var snip = function ( contour, u, v, w, n, verts ) {
  16426. var p;
  16427. var ax, ay, bx, by;
  16428. var cx, cy, px, py;
  16429. ax = contour[ verts[ u ] ].x;
  16430. ay = contour[ verts[ u ] ].y;
  16431. bx = contour[ verts[ v ] ].x;
  16432. by = contour[ verts[ v ] ].y;
  16433. cx = contour[ verts[ w ] ].x;
  16434. cy = contour[ verts[ w ] ].y;
  16435. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16436. var aX, aY, bX, bY, cX, cY;
  16437. var apx, apy, bpx, bpy, cpx, cpy;
  16438. var cCROSSap, bCROSScp, aCROSSbp;
  16439. aX = cx - bx; aY = cy - by;
  16440. bX = ax - cx; bY = ay - cy;
  16441. cX = bx - ax; cY = by - ay;
  16442. for ( p = 0; p < n; p++ ) {
  16443. px = contour[ verts[ p ] ].x
  16444. py = contour[ verts[ p ] ].y
  16445. if ( ( (px === ax) && (py === ay) ) ||
  16446. ( (px === bx) && (py === by) ) ||
  16447. ( (px === cx) && (py === cy) ) ) continue;
  16448. apx = px - ax; apy = py - ay;
  16449. bpx = px - bx; bpy = py - by;
  16450. cpx = px - cx; cpy = py - cy;
  16451. // see if p is inside triangle abc
  16452. aCROSSbp = aX*bpy - aY*bpx;
  16453. cCROSSap = cX*apy - cY*apx;
  16454. bCROSScp = bX*cpy - bY*cpx;
  16455. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16456. }
  16457. return true;
  16458. };
  16459. namespace.Triangulate = process;
  16460. namespace.Triangulate.area = area;
  16461. return namespace;
  16462. })(THREE.FontUtils);
  16463. // To use the typeface.js face files, hook up the API
  16464. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16465. THREE.typeface_js = self._typeface_js;
  16466. /**
  16467. * @author zz85 / http://www.lab4games.net/zz85/blog
  16468. * Extensible curve object
  16469. *
  16470. * Some common of Curve methods
  16471. * .getPoint(t), getTangent(t)
  16472. * .getPointAt(u), getTagentAt(u)
  16473. * .getPoints(), .getSpacedPoints()
  16474. * .getLength()
  16475. * .updateArcLengths()
  16476. *
  16477. * This following classes subclasses THREE.Curve:
  16478. *
  16479. * -- 2d classes --
  16480. * THREE.LineCurve
  16481. * THREE.QuadraticBezierCurve
  16482. * THREE.CubicBezierCurve
  16483. * THREE.SplineCurve
  16484. * THREE.ArcCurve
  16485. * THREE.EllipseCurve
  16486. *
  16487. * -- 3d classes --
  16488. * THREE.LineCurve3
  16489. * THREE.QuadraticBezierCurve3
  16490. * THREE.CubicBezierCurve3
  16491. * THREE.SplineCurve3
  16492. * THREE.ClosedSplineCurve3
  16493. *
  16494. * A series of curves can be represented as a THREE.CurvePath
  16495. *
  16496. **/
  16497. /**************************************************************
  16498. * Abstract Curve base class
  16499. **************************************************************/
  16500. THREE.Curve = function () {
  16501. };
  16502. // Virtual base class method to overwrite and implement in subclasses
  16503. // - t [0 .. 1]
  16504. THREE.Curve.prototype.getPoint = function ( t ) {
  16505. console.log( "Warning, getPoint() not implemented!" );
  16506. return null;
  16507. };
  16508. // Get point at relative position in curve according to arc length
  16509. // - u [0 .. 1]
  16510. THREE.Curve.prototype.getPointAt = function ( u ) {
  16511. var t = this.getUtoTmapping( u );
  16512. return this.getPoint( t );
  16513. };
  16514. // Get sequence of points using getPoint( t )
  16515. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16516. if ( !divisions ) divisions = 5;
  16517. var d, pts = [];
  16518. for ( d = 0; d <= divisions; d ++ ) {
  16519. pts.push( this.getPoint( d / divisions ) );
  16520. }
  16521. return pts;
  16522. };
  16523. // Get sequence of points using getPointAt( u )
  16524. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16525. if ( !divisions ) divisions = 5;
  16526. var d, pts = [];
  16527. for ( d = 0; d <= divisions; d ++ ) {
  16528. pts.push( this.getPointAt( d / divisions ) );
  16529. }
  16530. return pts;
  16531. };
  16532. // Get total curve arc length
  16533. THREE.Curve.prototype.getLength = function () {
  16534. var lengths = this.getLengths();
  16535. return lengths[ lengths.length - 1 ];
  16536. };
  16537. // Get list of cumulative segment lengths
  16538. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16539. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16540. if ( this.cacheArcLengths
  16541. && ( this.cacheArcLengths.length == divisions + 1 )
  16542. && !this.needsUpdate) {
  16543. //console.log( "cached", this.cacheArcLengths );
  16544. return this.cacheArcLengths;
  16545. }
  16546. this.needsUpdate = false;
  16547. var cache = [];
  16548. var current, last = this.getPoint( 0 );
  16549. var p, sum = 0;
  16550. cache.push( 0 );
  16551. for ( p = 1; p <= divisions; p ++ ) {
  16552. current = this.getPoint ( p / divisions );
  16553. sum += current.distanceTo( last );
  16554. cache.push( sum );
  16555. last = current;
  16556. }
  16557. this.cacheArcLengths = cache;
  16558. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16559. };
  16560. THREE.Curve.prototype.updateArcLengths = function() {
  16561. this.needsUpdate = true;
  16562. this.getLengths();
  16563. };
  16564. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16565. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16566. var arcLengths = this.getLengths();
  16567. var i = 0, il = arcLengths.length;
  16568. var targetArcLength; // The targeted u distance value to get
  16569. if ( distance ) {
  16570. targetArcLength = distance;
  16571. } else {
  16572. targetArcLength = u * arcLengths[ il - 1 ];
  16573. }
  16574. //var time = Date.now();
  16575. // binary search for the index with largest value smaller than target u distance
  16576. var low = 0, high = il - 1, comparison;
  16577. while ( low <= high ) {
  16578. 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
  16579. comparison = arcLengths[ i ] - targetArcLength;
  16580. if ( comparison < 0 ) {
  16581. low = i + 1;
  16582. continue;
  16583. } else if ( comparison > 0 ) {
  16584. high = i - 1;
  16585. continue;
  16586. } else {
  16587. high = i;
  16588. break;
  16589. // DONE
  16590. }
  16591. }
  16592. i = high;
  16593. //console.log('b' , i, low, high, Date.now()- time);
  16594. if ( arcLengths[ i ] == targetArcLength ) {
  16595. var t = i / ( il - 1 );
  16596. return t;
  16597. }
  16598. // we could get finer grain at lengths, or use simple interpolatation between two points
  16599. var lengthBefore = arcLengths[ i ];
  16600. var lengthAfter = arcLengths[ i + 1 ];
  16601. var segmentLength = lengthAfter - lengthBefore;
  16602. // determine where we are between the 'before' and 'after' points
  16603. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16604. // add that fractional amount to t
  16605. var t = ( i + segmentFraction ) / ( il -1 );
  16606. return t;
  16607. };
  16608. // Returns a unit vector tangent at t
  16609. // In case any sub curve does not implement its tangent derivation,
  16610. // 2 points a small delta apart will be used to find its gradient
  16611. // which seems to give a reasonable approximation
  16612. THREE.Curve.prototype.getTangent = function( t ) {
  16613. var delta = 0.0001;
  16614. var t1 = t - delta;
  16615. var t2 = t + delta;
  16616. // Capping in case of danger
  16617. if ( t1 < 0 ) t1 = 0;
  16618. if ( t2 > 1 ) t2 = 1;
  16619. var pt1 = this.getPoint( t1 );
  16620. var pt2 = this.getPoint( t2 );
  16621. var vec = pt2.clone().sub(pt1);
  16622. return vec.normalize();
  16623. };
  16624. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16625. var t = this.getUtoTmapping( u );
  16626. return this.getTangent( t );
  16627. };
  16628. /**************************************************************
  16629. * Utils
  16630. **************************************************************/
  16631. THREE.Curve.Utils = {
  16632. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16633. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16634. },
  16635. // Puay Bing, thanks for helping with this derivative!
  16636. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16637. return -3 * p0 * (1 - t) * (1 - t) +
  16638. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16639. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16640. 3 * t * t * p3;
  16641. },
  16642. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16643. // To check if my formulas are correct
  16644. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16645. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16646. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16647. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16648. return h00 + h10 + h01 + h11;
  16649. },
  16650. // Catmull-Rom
  16651. interpolate: function( p0, p1, p2, p3, t ) {
  16652. var v0 = ( p2 - p0 ) * 0.5;
  16653. var v1 = ( p3 - p1 ) * 0.5;
  16654. var t2 = t * t;
  16655. var t3 = t * t2;
  16656. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16657. }
  16658. };
  16659. // TODO: Transformation for Curves?
  16660. /**************************************************************
  16661. * 3D Curves
  16662. **************************************************************/
  16663. // A Factory method for creating new curve subclasses
  16664. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16665. constructor.prototype = Object.create( THREE.Curve.prototype );
  16666. constructor.prototype.getPoint = getPointFunc;
  16667. return constructor;
  16668. };
  16669. /**
  16670. * @author zz85 / http://www.lab4games.net/zz85/blog
  16671. *
  16672. **/
  16673. /**************************************************************
  16674. * Curved Path - a curve path is simply a array of connected
  16675. * curves, but retains the api of a curve
  16676. **************************************************************/
  16677. THREE.CurvePath = function () {
  16678. this.curves = [];
  16679. this.bends = [];
  16680. this.autoClose = false; // Automatically closes the path
  16681. };
  16682. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16683. THREE.CurvePath.prototype.add = function ( curve ) {
  16684. this.curves.push( curve );
  16685. };
  16686. THREE.CurvePath.prototype.checkConnection = function() {
  16687. // TODO
  16688. // If the ending of curve is not connected to the starting
  16689. // or the next curve, then, this is not a real path
  16690. };
  16691. THREE.CurvePath.prototype.closePath = function() {
  16692. // TODO Test
  16693. // and verify for vector3 (needs to implement equals)
  16694. // Add a line curve if start and end of lines are not connected
  16695. var startPoint = this.curves[0].getPoint(0);
  16696. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16697. if (!startPoint.equals(endPoint)) {
  16698. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16699. }
  16700. };
  16701. // To get accurate point with reference to
  16702. // entire path distance at time t,
  16703. // following has to be done:
  16704. // 1. Length of each sub path have to be known
  16705. // 2. Locate and identify type of curve
  16706. // 3. Get t for the curve
  16707. // 4. Return curve.getPointAt(t')
  16708. THREE.CurvePath.prototype.getPoint = function( t ) {
  16709. var d = t * this.getLength();
  16710. var curveLengths = this.getCurveLengths();
  16711. var i = 0, diff, curve;
  16712. // To think about boundaries points.
  16713. while ( i < curveLengths.length ) {
  16714. if ( curveLengths[ i ] >= d ) {
  16715. diff = curveLengths[ i ] - d;
  16716. curve = this.curves[ i ];
  16717. var u = 1 - diff / curve.getLength();
  16718. return curve.getPointAt( u );
  16719. break;
  16720. }
  16721. i ++;
  16722. }
  16723. return null;
  16724. // loop where sum != 0, sum > d , sum+1 <d
  16725. };
  16726. /*
  16727. THREE.CurvePath.prototype.getTangent = function( t ) {
  16728. };*/
  16729. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16730. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16731. // getPoint() depends on getLength
  16732. THREE.CurvePath.prototype.getLength = function() {
  16733. var lens = this.getCurveLengths();
  16734. return lens[ lens.length - 1 ];
  16735. };
  16736. // Compute lengths and cache them
  16737. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16738. THREE.CurvePath.prototype.getCurveLengths = function() {
  16739. // We use cache values if curves and cache array are same length
  16740. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16741. return this.cacheLengths;
  16742. };
  16743. // Get length of subsurve
  16744. // Push sums into cached array
  16745. var lengths = [], sums = 0;
  16746. var i, il = this.curves.length;
  16747. for ( i = 0; i < il; i ++ ) {
  16748. sums += this.curves[ i ].getLength();
  16749. lengths.push( sums );
  16750. }
  16751. this.cacheLengths = lengths;
  16752. return lengths;
  16753. };
  16754. // Returns min and max coordinates
  16755. THREE.CurvePath.prototype.getBoundingBox = function () {
  16756. var points = this.getPoints();
  16757. var maxX, maxY, maxZ;
  16758. var minX, minY, minZ;
  16759. maxX = maxY = Number.NEGATIVE_INFINITY;
  16760. minX = minY = Number.POSITIVE_INFINITY;
  16761. var p, i, il, sum;
  16762. var v3 = points[0] instanceof THREE.Vector3;
  16763. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16764. for ( i = 0, il = points.length; i < il; i ++ ) {
  16765. p = points[ i ];
  16766. if ( p.x > maxX ) maxX = p.x;
  16767. else if ( p.x < minX ) minX = p.x;
  16768. if ( p.y > maxY ) maxY = p.y;
  16769. else if ( p.y < minY ) minY = p.y;
  16770. if ( v3 ) {
  16771. if ( p.z > maxZ ) maxZ = p.z;
  16772. else if ( p.z < minZ ) minZ = p.z;
  16773. }
  16774. sum.add( p );
  16775. }
  16776. var ret = {
  16777. minX: minX,
  16778. minY: minY,
  16779. maxX: maxX,
  16780. maxY: maxY
  16781. };
  16782. if ( v3 ) {
  16783. ret.maxZ = maxZ;
  16784. ret.minZ = minZ;
  16785. }
  16786. return ret;
  16787. };
  16788. /**************************************************************
  16789. * Create Geometries Helpers
  16790. **************************************************************/
  16791. /// Generate geometry from path points (for Line or Points objects)
  16792. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16793. var pts = this.getPoints( divisions, true );
  16794. return this.createGeometry( pts );
  16795. };
  16796. // Generate geometry from equidistance sampling along the path
  16797. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16798. var pts = this.getSpacedPoints( divisions, true );
  16799. return this.createGeometry( pts );
  16800. };
  16801. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16802. var geometry = new THREE.Geometry();
  16803. for ( var i = 0; i < points.length; i ++ ) {
  16804. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16805. }
  16806. return geometry;
  16807. };
  16808. /**************************************************************
  16809. * Bend / Wrap Helper Methods
  16810. **************************************************************/
  16811. // Wrap path / Bend modifiers?
  16812. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16813. this.bends.push( bendpath );
  16814. };
  16815. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16816. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16817. var i, il;
  16818. if ( !bends ) {
  16819. bends = this.bends;
  16820. }
  16821. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16822. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16823. }
  16824. return oldPts;
  16825. };
  16826. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16827. var oldPts = this.getSpacedPoints( segments );
  16828. var i, il;
  16829. if ( !bends ) {
  16830. bends = this.bends;
  16831. }
  16832. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16833. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16834. }
  16835. return oldPts;
  16836. };
  16837. // This returns getPoints() bend/wrapped around the contour of a path.
  16838. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16839. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16840. var bounds = this.getBoundingBox();
  16841. var i, il, p, oldX, oldY, xNorm;
  16842. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16843. p = oldPts[ i ];
  16844. oldX = p.x;
  16845. oldY = p.y;
  16846. xNorm = oldX / bounds.maxX;
  16847. // If using actual distance, for length > path, requires line extrusions
  16848. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16849. xNorm = path.getUtoTmapping( xNorm, oldX );
  16850. // check for out of bounds?
  16851. var pathPt = path.getPoint( xNorm );
  16852. var normal = path.getTangent( xNorm );
  16853. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  16854. p.x = pathPt.x + normal.x;
  16855. p.y = pathPt.y + normal.y;
  16856. }
  16857. return oldPts;
  16858. };
  16859. /**
  16860. * @author alteredq / http://alteredqualia.com/
  16861. */
  16862. THREE.Gyroscope = function () {
  16863. THREE.Object3D.call( this );
  16864. };
  16865. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16866. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16867. this.matrixAutoUpdate && this.updateMatrix();
  16868. // update matrixWorld
  16869. if ( this.matrixWorldNeedsUpdate || force ) {
  16870. if ( this.parent ) {
  16871. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16872. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16873. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16874. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16875. } else {
  16876. this.matrixWorld.copy( this.matrix );
  16877. }
  16878. this.matrixWorldNeedsUpdate = false;
  16879. force = true;
  16880. }
  16881. // update children
  16882. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16883. this.children[ i ].updateMatrixWorld( force );
  16884. }
  16885. };
  16886. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16887. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16888. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16889. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16890. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16891. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16892. /**
  16893. * @author zz85 / http://www.lab4games.net/zz85/blog
  16894. * Creates free form 2d path using series of points, lines or curves.
  16895. *
  16896. **/
  16897. THREE.Path = function ( points ) {
  16898. THREE.CurvePath.call(this);
  16899. this.actions = [];
  16900. if ( points ) {
  16901. this.fromPoints( points );
  16902. }
  16903. };
  16904. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16905. THREE.PathActions = {
  16906. MOVE_TO: 'moveTo',
  16907. LINE_TO: 'lineTo',
  16908. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16909. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16910. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16911. ARC: 'arc', // Circle
  16912. ELLIPSE: 'ellipse'
  16913. };
  16914. // TODO Clean up PATH API
  16915. // Create path using straight lines to connect all points
  16916. // - vectors: array of Vector2
  16917. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16918. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16919. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16920. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16921. };
  16922. };
  16923. // startPath() endPath()?
  16924. THREE.Path.prototype.moveTo = function ( x, y ) {
  16925. var args = Array.prototype.slice.call( arguments );
  16926. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16927. };
  16928. THREE.Path.prototype.lineTo = function ( x, y ) {
  16929. var args = Array.prototype.slice.call( arguments );
  16930. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16931. var x0 = lastargs[ lastargs.length - 2 ];
  16932. var y0 = lastargs[ lastargs.length - 1 ];
  16933. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16934. this.curves.push( curve );
  16935. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16936. };
  16937. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16938. var args = Array.prototype.slice.call( arguments );
  16939. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16940. var x0 = lastargs[ lastargs.length - 2 ];
  16941. var y0 = lastargs[ lastargs.length - 1 ];
  16942. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16943. new THREE.Vector2( aCPx, aCPy ),
  16944. new THREE.Vector2( aX, aY ) );
  16945. this.curves.push( curve );
  16946. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16947. };
  16948. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16949. aCP2x, aCP2y,
  16950. aX, aY ) {
  16951. var args = Array.prototype.slice.call( arguments );
  16952. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16953. var x0 = lastargs[ lastargs.length - 2 ];
  16954. var y0 = lastargs[ lastargs.length - 1 ];
  16955. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16956. new THREE.Vector2( aCP1x, aCP1y ),
  16957. new THREE.Vector2( aCP2x, aCP2y ),
  16958. new THREE.Vector2( aX, aY ) );
  16959. this.curves.push( curve );
  16960. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16961. };
  16962. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16963. var args = Array.prototype.slice.call( arguments );
  16964. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16965. var x0 = lastargs[ lastargs.length - 2 ];
  16966. var y0 = lastargs[ lastargs.length - 1 ];
  16967. //---
  16968. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16969. Array.prototype.push.apply( npts, pts );
  16970. var curve = new THREE.SplineCurve( npts );
  16971. this.curves.push( curve );
  16972. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16973. };
  16974. // FUTURE: Change the API or follow canvas API?
  16975. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16976. aStartAngle, aEndAngle, aClockwise ) {
  16977. var lastargs = this.actions[ this.actions.length - 1].args;
  16978. var x0 = lastargs[ lastargs.length - 2 ];
  16979. var y0 = lastargs[ lastargs.length - 1 ];
  16980. this.absarc(aX + x0, aY + y0, aRadius,
  16981. aStartAngle, aEndAngle, aClockwise );
  16982. };
  16983. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16984. aStartAngle, aEndAngle, aClockwise ) {
  16985. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16986. };
  16987. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16988. aStartAngle, aEndAngle, aClockwise ) {
  16989. var lastargs = this.actions[ this.actions.length - 1].args;
  16990. var x0 = lastargs[ lastargs.length - 2 ];
  16991. var y0 = lastargs[ lastargs.length - 1 ];
  16992. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16993. aStartAngle, aEndAngle, aClockwise );
  16994. };
  16995. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16996. aStartAngle, aEndAngle, aClockwise ) {
  16997. var args = Array.prototype.slice.call( arguments );
  16998. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16999. aStartAngle, aEndAngle, aClockwise );
  17000. this.curves.push( curve );
  17001. var lastPoint = curve.getPoint(1);
  17002. args.push(lastPoint.x);
  17003. args.push(lastPoint.y);
  17004. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17005. };
  17006. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17007. if ( ! divisions ) divisions = 40;
  17008. var points = [];
  17009. for ( var i = 0; i < divisions; i ++ ) {
  17010. points.push( this.getPoint( i / divisions ) );
  17011. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17012. }
  17013. // if ( closedPath ) {
  17014. //
  17015. // points.push( points[ 0 ] );
  17016. //
  17017. // }
  17018. return points;
  17019. };
  17020. /* Return an array of vectors based on contour of the path */
  17021. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17022. if (this.useSpacedPoints) {
  17023. console.log('tata');
  17024. return this.getSpacedPoints( divisions, closedPath );
  17025. }
  17026. divisions = divisions || 12;
  17027. var points = [];
  17028. var i, il, item, action, args;
  17029. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17030. laste, j,
  17031. t, tx, ty;
  17032. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17033. item = this.actions[ i ];
  17034. action = item.action;
  17035. args = item.args;
  17036. switch( action ) {
  17037. case THREE.PathActions.MOVE_TO:
  17038. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17039. break;
  17040. case THREE.PathActions.LINE_TO:
  17041. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17042. break;
  17043. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17044. cpx = args[ 2 ];
  17045. cpy = args[ 3 ];
  17046. cpx1 = args[ 0 ];
  17047. cpy1 = args[ 1 ];
  17048. if ( points.length > 0 ) {
  17049. laste = points[ points.length - 1 ];
  17050. cpx0 = laste.x;
  17051. cpy0 = laste.y;
  17052. } else {
  17053. laste = this.actions[ i - 1 ].args;
  17054. cpx0 = laste[ laste.length - 2 ];
  17055. cpy0 = laste[ laste.length - 1 ];
  17056. }
  17057. for ( j = 1; j <= divisions; j ++ ) {
  17058. t = j / divisions;
  17059. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17060. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17061. points.push( new THREE.Vector2( tx, ty ) );
  17062. }
  17063. break;
  17064. case THREE.PathActions.BEZIER_CURVE_TO:
  17065. cpx = args[ 4 ];
  17066. cpy = args[ 5 ];
  17067. cpx1 = args[ 0 ];
  17068. cpy1 = args[ 1 ];
  17069. cpx2 = args[ 2 ];
  17070. cpy2 = args[ 3 ];
  17071. if ( points.length > 0 ) {
  17072. laste = points[ points.length - 1 ];
  17073. cpx0 = laste.x;
  17074. cpy0 = laste.y;
  17075. } else {
  17076. laste = this.actions[ i - 1 ].args;
  17077. cpx0 = laste[ laste.length - 2 ];
  17078. cpy0 = laste[ laste.length - 1 ];
  17079. }
  17080. for ( j = 1; j <= divisions; j ++ ) {
  17081. t = j / divisions;
  17082. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17083. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17084. points.push( new THREE.Vector2( tx, ty ) );
  17085. }
  17086. break;
  17087. case THREE.PathActions.CSPLINE_THRU:
  17088. laste = this.actions[ i - 1 ].args;
  17089. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17090. var spts = [ last ];
  17091. var n = divisions * args[ 0 ].length;
  17092. spts = spts.concat( args[ 0 ] );
  17093. var spline = new THREE.SplineCurve( spts );
  17094. for ( j = 1; j <= n; j ++ ) {
  17095. points.push( spline.getPointAt( j / n ) ) ;
  17096. }
  17097. break;
  17098. case THREE.PathActions.ARC:
  17099. var aX = args[ 0 ], aY = args[ 1 ],
  17100. aRadius = args[ 2 ],
  17101. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17102. aClockwise = !!args[ 5 ];
  17103. var deltaAngle = aEndAngle - aStartAngle;
  17104. var angle;
  17105. var tdivisions = divisions * 2;
  17106. for ( j = 1; j <= tdivisions; j ++ ) {
  17107. t = j / tdivisions;
  17108. if ( ! aClockwise ) {
  17109. t = 1 - t;
  17110. }
  17111. angle = aStartAngle + t * deltaAngle;
  17112. tx = aX + aRadius * Math.cos( angle );
  17113. ty = aY + aRadius * Math.sin( angle );
  17114. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17115. points.push( new THREE.Vector2( tx, ty ) );
  17116. }
  17117. //console.log(points);
  17118. break;
  17119. case THREE.PathActions.ELLIPSE:
  17120. var aX = args[ 0 ], aY = args[ 1 ],
  17121. xRadius = args[ 2 ],
  17122. yRadius = args[ 3 ],
  17123. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17124. aClockwise = !!args[ 6 ];
  17125. var deltaAngle = aEndAngle - aStartAngle;
  17126. var angle;
  17127. var tdivisions = divisions * 2;
  17128. for ( j = 1; j <= tdivisions; j ++ ) {
  17129. t = j / tdivisions;
  17130. if ( ! aClockwise ) {
  17131. t = 1 - t;
  17132. }
  17133. angle = aStartAngle + t * deltaAngle;
  17134. tx = aX + xRadius * Math.cos( angle );
  17135. ty = aY + yRadius * Math.sin( angle );
  17136. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17137. points.push( new THREE.Vector2( tx, ty ) );
  17138. }
  17139. //console.log(points);
  17140. break;
  17141. } // end switch
  17142. }
  17143. // Normalize to remove the closing point by default.
  17144. var lastPoint = points[ points.length - 1];
  17145. var EPSILON = 0.0000000001;
  17146. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17147. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17148. points.splice( points.length - 1, 1);
  17149. if ( closedPath ) {
  17150. points.push( points[ 0 ] );
  17151. }
  17152. return points;
  17153. };
  17154. //
  17155. // Breaks path into shapes
  17156. //
  17157. // Assumptions (if parameter isCCW==true the opposite holds):
  17158. // - solid shapes are defined clockwise (CW)
  17159. // - holes are defined counterclockwise (CCW)
  17160. //
  17161. // If parameter noHoles==true:
  17162. // - all subPaths are regarded as solid shapes
  17163. // - definition order CW/CCW has no relevance
  17164. //
  17165. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17166. function extractSubpaths( inActions ) {
  17167. var i, il, item, action, args;
  17168. var subPaths = [], lastPath = new THREE.Path();
  17169. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17170. item = inActions[ i ];
  17171. args = item.args;
  17172. action = item.action;
  17173. if ( action == THREE.PathActions.MOVE_TO ) {
  17174. if ( lastPath.actions.length != 0 ) {
  17175. subPaths.push( lastPath );
  17176. lastPath = new THREE.Path();
  17177. }
  17178. }
  17179. lastPath[ action ].apply( lastPath, args );
  17180. }
  17181. if ( lastPath.actions.length != 0 ) {
  17182. subPaths.push( lastPath );
  17183. }
  17184. // console.log(subPaths);
  17185. return subPaths;
  17186. }
  17187. function toShapesNoHoles( inSubpaths ) {
  17188. var shapes = [];
  17189. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17190. var tmpPath = inSubpaths[ i ];
  17191. var tmpShape = new THREE.Shape();
  17192. tmpShape.actions = tmpPath.actions;
  17193. tmpShape.curves = tmpPath.curves;
  17194. shapes.push( tmpShape );
  17195. }
  17196. //console.log("shape", shapes);
  17197. return shapes;
  17198. };
  17199. function isPointInsidePolygon( inPt, inPolygon ) {
  17200. var EPSILON = 0.0000000001;
  17201. var polyLen = inPolygon.length;
  17202. // inPt on polygon contour => immediate success or
  17203. // toggling of inside/outside at every single! intersection point of an edge
  17204. // with the horizontal line through inPt, left of inPt
  17205. // not counting lowerY endpoints of edges and whole edges on that line
  17206. var inside = false;
  17207. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17208. var edgeLowPt = inPolygon[ p ];
  17209. var edgeHighPt = inPolygon[ q ];
  17210. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17211. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17212. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17213. if ( edgeDy < 0 ) {
  17214. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17215. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17216. }
  17217. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17218. if ( inPt.y == edgeLowPt.y ) {
  17219. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17220. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17221. } else {
  17222. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17223. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17224. if ( perpEdge < 0 ) continue;
  17225. inside = !inside; // true intersection left of inPt
  17226. }
  17227. } else { // parallel or colinear
  17228. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17229. // egde lies on the same horizontal line as inPt
  17230. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17231. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17232. // continue;
  17233. }
  17234. }
  17235. return inside;
  17236. }
  17237. var subPaths = extractSubpaths( this.actions );
  17238. if ( subPaths.length == 0 ) return [];
  17239. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17240. var solid, tmpPath, tmpShape, shapes = [];
  17241. if ( subPaths.length == 1) {
  17242. tmpPath = subPaths[0];
  17243. tmpShape = new THREE.Shape();
  17244. tmpShape.actions = tmpPath.actions;
  17245. tmpShape.curves = tmpPath.curves;
  17246. shapes.push( tmpShape );
  17247. return shapes;
  17248. }
  17249. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17250. holesFirst = isCCW ? !holesFirst : holesFirst;
  17251. // console.log("Holes first", holesFirst);
  17252. var betterShapeHoles = [];
  17253. var newShapes = [];
  17254. var newShapeHoles = [];
  17255. var mainIdx = 0;
  17256. var tmpPoints;
  17257. newShapes[mainIdx] = undefined;
  17258. newShapeHoles[mainIdx] = [];
  17259. var i, il;
  17260. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17261. tmpPath = subPaths[ i ];
  17262. tmpPoints = tmpPath.getPoints();
  17263. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17264. solid = isCCW ? !solid : solid;
  17265. if ( solid ) {
  17266. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17267. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17268. newShapes[mainIdx].s.actions = tmpPath.actions;
  17269. newShapes[mainIdx].s.curves = tmpPath.curves;
  17270. if ( holesFirst ) mainIdx++;
  17271. newShapeHoles[mainIdx] = [];
  17272. //console.log('cw', i);
  17273. } else {
  17274. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17275. //console.log('ccw', i);
  17276. }
  17277. }
  17278. // only Holes? -> probably all Shapes with wrong orientation
  17279. if ( !newShapes[0] ) return toShapesNoHoles( subPaths );
  17280. if ( newShapes.length > 1 ) {
  17281. var ambigious = false;
  17282. var toChange = [];
  17283. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17284. betterShapeHoles[sIdx] = [];
  17285. }
  17286. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17287. var sh = newShapes[sIdx];
  17288. var sho = newShapeHoles[sIdx];
  17289. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17290. var ho = sho[hIdx];
  17291. var hole_unassigned = true;
  17292. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17293. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17294. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17295. if ( hole_unassigned ) {
  17296. hole_unassigned = false;
  17297. betterShapeHoles[s2Idx].push( ho );
  17298. } else {
  17299. ambigious = true;
  17300. }
  17301. }
  17302. }
  17303. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17304. }
  17305. }
  17306. // console.log("ambigious: ", ambigious);
  17307. if ( toChange.length > 0 ) {
  17308. // console.log("to change: ", toChange);
  17309. if (! ambigious) newShapeHoles = betterShapeHoles;
  17310. }
  17311. }
  17312. var tmpHoles, j, jl;
  17313. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17314. tmpShape = newShapes[i].s;
  17315. shapes.push( tmpShape );
  17316. tmpHoles = newShapeHoles[i];
  17317. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17318. tmpShape.holes.push( tmpHoles[j].h );
  17319. }
  17320. }
  17321. //console.log("shape", shapes);
  17322. return shapes;
  17323. };
  17324. /**
  17325. * @author zz85 / http://www.lab4games.net/zz85/blog
  17326. * Defines a 2d shape plane using paths.
  17327. **/
  17328. // STEP 1 Create a path.
  17329. // STEP 2 Turn path into shape.
  17330. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17331. // STEP 3a - Extract points from each shape, turn to vertices
  17332. // STEP 3b - Triangulate each shape, add faces.
  17333. THREE.Shape = function () {
  17334. THREE.Path.apply( this, arguments );
  17335. this.holes = [];
  17336. };
  17337. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17338. // Convenience method to return ExtrudeGeometry
  17339. THREE.Shape.prototype.extrude = function ( options ) {
  17340. var extruded = new THREE.ExtrudeGeometry( this, options );
  17341. return extruded;
  17342. };
  17343. // Convenience method to return ShapeGeometry
  17344. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17345. var geometry = new THREE.ShapeGeometry( this, options );
  17346. return geometry;
  17347. };
  17348. // Get points of holes
  17349. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17350. var i, il = this.holes.length, holesPts = [];
  17351. for ( i = 0; i < il; i ++ ) {
  17352. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17353. }
  17354. return holesPts;
  17355. };
  17356. // Get points of holes (spaced by regular distance)
  17357. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17358. var i, il = this.holes.length, holesPts = [];
  17359. for ( i = 0; i < il; i ++ ) {
  17360. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17361. }
  17362. return holesPts;
  17363. };
  17364. // Get points of shape and holes (keypoints based on segments parameter)
  17365. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17366. return {
  17367. shape: this.getTransformedPoints( divisions ),
  17368. holes: this.getPointsHoles( divisions )
  17369. };
  17370. };
  17371. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17372. if (this.useSpacedPoints) {
  17373. return this.extractAllSpacedPoints(divisions);
  17374. }
  17375. return this.extractAllPoints(divisions);
  17376. };
  17377. //
  17378. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17379. //
  17380. // return {
  17381. //
  17382. // shape: this.transform( bend, divisions ),
  17383. // holes: this.getPointsHoles( divisions, bend )
  17384. //
  17385. // };
  17386. //
  17387. // };
  17388. // Get points of shape and holes (spaced by regular distance)
  17389. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17390. return {
  17391. shape: this.getTransformedSpacedPoints( divisions ),
  17392. holes: this.getSpacedPointsHoles( divisions )
  17393. };
  17394. };
  17395. /**************************************************************
  17396. * Utils
  17397. **************************************************************/
  17398. THREE.Shape.Utils = {
  17399. triangulateShape: function ( contour, holes ) {
  17400. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17401. // inOtherPt needs to be colinear to the inSegment
  17402. if ( inSegPt1.x != inSegPt2.x ) {
  17403. if ( inSegPt1.x < inSegPt2.x ) {
  17404. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17405. } else {
  17406. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17407. }
  17408. } else {
  17409. if ( inSegPt1.y < inSegPt2.y ) {
  17410. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17411. } else {
  17412. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17413. }
  17414. }
  17415. }
  17416. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17417. var EPSILON = 0.0000000001;
  17418. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17419. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17420. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17421. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17422. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17423. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17424. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17425. var perpSeg2;
  17426. if ( limit > 0 ) {
  17427. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17428. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17429. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17430. } else {
  17431. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17432. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17433. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17434. }
  17435. // i.e. to reduce rounding errors
  17436. // intersection at endpoint of segment#1?
  17437. if ( perpSeg2 == 0 ) {
  17438. if ( ( inExcludeAdjacentSegs ) &&
  17439. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17440. return [ inSeg1Pt1 ];
  17441. }
  17442. if ( perpSeg2 == limit ) {
  17443. if ( ( inExcludeAdjacentSegs ) &&
  17444. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17445. return [ inSeg1Pt2 ];
  17446. }
  17447. // intersection at endpoint of segment#2?
  17448. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17449. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17450. // return real intersection point
  17451. var factorSeg1 = perpSeg2 / limit;
  17452. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17453. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17454. } else { // parallel or colinear
  17455. if ( ( perpSeg1 != 0 ) ||
  17456. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17457. // they are collinear or degenerate
  17458. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17459. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17460. // both segments are points
  17461. if ( seg1Pt && seg2Pt ) {
  17462. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17463. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17464. return [ inSeg1Pt1 ]; // they are the same point
  17465. }
  17466. // segment#1 is a single point
  17467. if ( seg1Pt ) {
  17468. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17469. return [ inSeg1Pt1 ];
  17470. }
  17471. // segment#2 is a single point
  17472. if ( seg2Pt ) {
  17473. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17474. return [ inSeg2Pt1 ];
  17475. }
  17476. // they are collinear segments, which might overlap
  17477. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17478. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17479. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17480. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17481. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17482. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17483. } else {
  17484. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17485. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17486. }
  17487. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17488. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17489. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17490. } else {
  17491. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17492. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17493. }
  17494. } else { // the segments are on a vertical line
  17495. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17496. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17497. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17498. } else {
  17499. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17500. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17501. }
  17502. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17503. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17504. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17505. } else {
  17506. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17507. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17508. }
  17509. }
  17510. if ( seg1minVal <= seg2minVal ) {
  17511. if ( seg1maxVal < seg2minVal ) return [];
  17512. if ( seg1maxVal == seg2minVal ) {
  17513. if ( inExcludeAdjacentSegs ) return [];
  17514. return [ seg2min ];
  17515. }
  17516. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17517. return [ seg2min, seg2max ];
  17518. } else {
  17519. if ( seg1minVal > seg2maxVal ) return [];
  17520. if ( seg1minVal == seg2maxVal ) {
  17521. if ( inExcludeAdjacentSegs ) return [];
  17522. return [ seg1min ];
  17523. }
  17524. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17525. return [ seg1min, seg2max ];
  17526. }
  17527. }
  17528. }
  17529. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17530. // The order of legs is important
  17531. var EPSILON = 0.0000000001;
  17532. // translation of all points, so that Vertex is at (0,0)
  17533. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17534. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17535. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17536. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17537. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17538. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17539. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17540. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17541. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17542. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17543. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17544. } else { // main angle > 180 deg.
  17545. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17546. }
  17547. } else { // angle == 180 deg.
  17548. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17549. return ( from2otherAngle > 0 );
  17550. }
  17551. }
  17552. function removeHoles( contour, holes ) {
  17553. var shape = contour.concat(); // work on this shape
  17554. var hole;
  17555. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17556. // Check if hole point lies within angle around shape point
  17557. var lastShapeIdx = shape.length - 1;
  17558. var prevShapeIdx = inShapeIdx - 1;
  17559. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17560. var nextShapeIdx = inShapeIdx + 1;
  17561. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17562. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17563. if (! insideAngle ) {
  17564. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17565. return false;
  17566. }
  17567. // Check if shape point lies within angle around hole point
  17568. var lastHoleIdx = hole.length - 1;
  17569. var prevHoleIdx = inHoleIdx - 1;
  17570. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17571. var nextHoleIdx = inHoleIdx + 1;
  17572. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17573. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17574. if (! insideAngle ) {
  17575. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17576. return false;
  17577. }
  17578. return true;
  17579. }
  17580. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17581. // checks for intersections with shape edges
  17582. var sIdx, nextIdx, intersection;
  17583. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17584. nextIdx = sIdx+1; nextIdx %= shape.length;
  17585. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17586. if ( intersection.length > 0 ) return true;
  17587. }
  17588. return false;
  17589. }
  17590. var indepHoles = [];
  17591. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17592. // checks for intersections with hole edges
  17593. var ihIdx, chkHole,
  17594. hIdx, nextIdx, intersection;
  17595. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17596. chkHole = holes[indepHoles[ihIdx]];
  17597. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17598. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17599. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17600. if ( intersection.length > 0 ) return true;
  17601. }
  17602. }
  17603. return false;
  17604. }
  17605. var holeIndex, shapeIndex,
  17606. shapePt, holePt,
  17607. holeIdx, cutKey, failedCuts = [],
  17608. tmpShape1, tmpShape2,
  17609. tmpHole1, tmpHole2;
  17610. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17611. indepHoles.push( h );
  17612. }
  17613. var minShapeIndex = 0;
  17614. var counter = indepHoles.length * 2;
  17615. while ( indepHoles.length > 0 ) {
  17616. counter --;
  17617. if ( counter < 0 ) {
  17618. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17619. break;
  17620. }
  17621. // search for shape-vertex and hole-vertex,
  17622. // which can be connected without intersections
  17623. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex++ ) {
  17624. shapePt = shape[ shapeIndex ];
  17625. holeIndex = -1;
  17626. // search for hole which can be reached without intersections
  17627. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17628. holeIdx = indepHoles[h];
  17629. // prevent multiple checks
  17630. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17631. if ( failedCuts[cutKey] !== undefined ) continue;
  17632. hole = holes[holeIdx];
  17633. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17634. holePt = hole[ h2 ];
  17635. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17636. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17637. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17638. holeIndex = h2;
  17639. indepHoles.splice(h,1);
  17640. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17641. tmpShape2 = shape.slice( shapeIndex );
  17642. tmpHole1 = hole.slice( holeIndex );
  17643. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17644. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17645. minShapeIndex = shapeIndex;
  17646. // Debug only, to show the selected cuts
  17647. // glob_CutLines.push( [ shapePt, holePt ] );
  17648. break;
  17649. }
  17650. if ( holeIndex >= 0 ) break; // hole-vertex found
  17651. failedCuts[cutKey] = true; // remember failure
  17652. }
  17653. if ( holeIndex >= 0 ) break; // hole-vertex found
  17654. }
  17655. }
  17656. return shape; /* shape with no holes */
  17657. }
  17658. var i, il, f, face,
  17659. key, index,
  17660. allPointsMap = {};
  17661. // 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.
  17662. var allpoints = contour.concat();
  17663. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17664. Array.prototype.push.apply( allpoints, holes[h] );
  17665. }
  17666. //console.log( "allpoints",allpoints, allpoints.length );
  17667. // prepare all points map
  17668. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17669. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17670. if ( allPointsMap[ key ] !== undefined ) {
  17671. console.log( "Duplicate point", key );
  17672. }
  17673. allPointsMap[ key ] = i;
  17674. }
  17675. // remove holes by cutting paths to holes and adding them to the shape
  17676. var shapeWithoutHoles = removeHoles( contour, holes );
  17677. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17678. //console.log( "triangles",triangles, triangles.length );
  17679. // check all face vertices against all points map
  17680. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17681. face = triangles[ i ];
  17682. for ( f = 0; f < 3; f ++ ) {
  17683. key = face[ f ].x + ":" + face[ f ].y;
  17684. index = allPointsMap[ key ];
  17685. if ( index !== undefined ) {
  17686. face[ f ] = index;
  17687. }
  17688. }
  17689. }
  17690. return triangles.concat();
  17691. },
  17692. isClockWise: function ( pts ) {
  17693. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17694. },
  17695. // Bezier Curves formulas obtained from
  17696. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17697. // Quad Bezier Functions
  17698. b2p0: function ( t, p ) {
  17699. var k = 1 - t;
  17700. return k * k * p;
  17701. },
  17702. b2p1: function ( t, p ) {
  17703. return 2 * ( 1 - t ) * t * p;
  17704. },
  17705. b2p2: function ( t, p ) {
  17706. return t * t * p;
  17707. },
  17708. b2: function ( t, p0, p1, p2 ) {
  17709. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17710. },
  17711. // Cubic Bezier Functions
  17712. b3p0: function ( t, p ) {
  17713. var k = 1 - t;
  17714. return k * k * k * p;
  17715. },
  17716. b3p1: function ( t, p ) {
  17717. var k = 1 - t;
  17718. return 3 * k * k * t * p;
  17719. },
  17720. b3p2: function ( t, p ) {
  17721. var k = 1 - t;
  17722. return 3 * k * t * t * p;
  17723. },
  17724. b3p3: function ( t, p ) {
  17725. return t * t * t * p;
  17726. },
  17727. b3: function ( t, p0, p1, p2, p3 ) {
  17728. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17729. }
  17730. };
  17731. /**************************************************************
  17732. * Line
  17733. **************************************************************/
  17734. THREE.LineCurve = function ( v1, v2 ) {
  17735. this.v1 = v1;
  17736. this.v2 = v2;
  17737. };
  17738. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17739. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17740. var point = this.v2.clone().sub(this.v1);
  17741. point.multiplyScalar( t ).add( this.v1 );
  17742. return point;
  17743. };
  17744. // Line curve is linear, so we can overwrite default getPointAt
  17745. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17746. return this.getPoint( u );
  17747. };
  17748. THREE.LineCurve.prototype.getTangent = function( t ) {
  17749. var tangent = this.v2.clone().sub(this.v1);
  17750. return tangent.normalize();
  17751. };
  17752. /**************************************************************
  17753. * Quadratic Bezier curve
  17754. **************************************************************/
  17755. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17756. this.v0 = v0;
  17757. this.v1 = v1;
  17758. this.v2 = v2;
  17759. };
  17760. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17761. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17762. var tx, ty;
  17763. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17764. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17765. return new THREE.Vector2( tx, ty );
  17766. };
  17767. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17768. var tx, ty;
  17769. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17770. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17771. // returns unit vector
  17772. var tangent = new THREE.Vector2( tx, ty );
  17773. tangent.normalize();
  17774. return tangent;
  17775. };
  17776. /**************************************************************
  17777. * Cubic Bezier curve
  17778. **************************************************************/
  17779. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17780. this.v0 = v0;
  17781. this.v1 = v1;
  17782. this.v2 = v2;
  17783. this.v3 = v3;
  17784. };
  17785. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17786. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17787. var tx, ty;
  17788. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17789. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17790. return new THREE.Vector2( tx, ty );
  17791. };
  17792. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17793. var tx, ty;
  17794. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17795. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17796. var tangent = new THREE.Vector2( tx, ty );
  17797. tangent.normalize();
  17798. return tangent;
  17799. };
  17800. /**************************************************************
  17801. * Spline curve
  17802. **************************************************************/
  17803. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17804. this.points = (points == undefined) ? [] : points;
  17805. };
  17806. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17807. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17808. var v = new THREE.Vector2();
  17809. var c = [];
  17810. var points = this.points, point, intPoint, weight;
  17811. point = ( points.length - 1 ) * t;
  17812. intPoint = Math.floor( point );
  17813. weight = point - intPoint;
  17814. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17815. c[ 1 ] = intPoint;
  17816. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17817. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17818. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17819. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17820. return v;
  17821. };
  17822. /**************************************************************
  17823. * Ellipse curve
  17824. **************************************************************/
  17825. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17826. this.aX = aX;
  17827. this.aY = aY;
  17828. this.xRadius = xRadius;
  17829. this.yRadius = yRadius;
  17830. this.aStartAngle = aStartAngle;
  17831. this.aEndAngle = aEndAngle;
  17832. this.aClockwise = aClockwise;
  17833. };
  17834. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17835. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17836. var angle;
  17837. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17838. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17839. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17840. if ( this.aClockwise === true ) {
  17841. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17842. } else {
  17843. angle = this.aStartAngle + t * deltaAngle;
  17844. }
  17845. var tx = this.aX + this.xRadius * Math.cos( angle );
  17846. var ty = this.aY + this.yRadius * Math.sin( angle );
  17847. return new THREE.Vector2( tx, ty );
  17848. };
  17849. /**************************************************************
  17850. * Arc curve
  17851. **************************************************************/
  17852. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17853. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17854. };
  17855. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17856. /**************************************************************
  17857. * Line3D
  17858. **************************************************************/
  17859. THREE.LineCurve3 = THREE.Curve.create(
  17860. function ( v1, v2 ) {
  17861. this.v1 = v1;
  17862. this.v2 = v2;
  17863. },
  17864. function ( t ) {
  17865. var r = new THREE.Vector3();
  17866. r.subVectors( this.v2, this.v1 ); // diff
  17867. r.multiplyScalar( t );
  17868. r.add( this.v1 );
  17869. return r;
  17870. }
  17871. );
  17872. /**************************************************************
  17873. * Quadratic Bezier 3D curve
  17874. **************************************************************/
  17875. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17876. function ( v0, v1, v2 ) {
  17877. this.v0 = v0;
  17878. this.v1 = v1;
  17879. this.v2 = v2;
  17880. },
  17881. function ( t ) {
  17882. var tx, ty, tz;
  17883. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17884. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17885. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17886. return new THREE.Vector3( tx, ty, tz );
  17887. }
  17888. );
  17889. /**************************************************************
  17890. * Cubic Bezier 3D curve
  17891. **************************************************************/
  17892. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17893. function ( v0, v1, v2, v3 ) {
  17894. this.v0 = v0;
  17895. this.v1 = v1;
  17896. this.v2 = v2;
  17897. this.v3 = v3;
  17898. },
  17899. function ( t ) {
  17900. var tx, ty, tz;
  17901. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17902. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17903. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17904. return new THREE.Vector3( tx, ty, tz );
  17905. }
  17906. );
  17907. /**************************************************************
  17908. * Spline 3D curve
  17909. **************************************************************/
  17910. THREE.SplineCurve3 = THREE.Curve.create(
  17911. function ( points /* array of Vector3 */) {
  17912. this.points = (points == undefined) ? [] : points;
  17913. },
  17914. function ( t ) {
  17915. var v = new THREE.Vector3();
  17916. var c = [];
  17917. var points = this.points, point, intPoint, weight;
  17918. point = ( points.length - 1 ) * t;
  17919. intPoint = Math.floor( point );
  17920. weight = point - intPoint;
  17921. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17922. c[ 1 ] = intPoint;
  17923. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17924. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17925. var pt0 = points[ c[0] ],
  17926. pt1 = points[ c[1] ],
  17927. pt2 = points[ c[2] ],
  17928. pt3 = points[ c[3] ];
  17929. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17930. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17931. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17932. return v;
  17933. }
  17934. );
  17935. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17936. // var v = new THREE.Vector3();
  17937. // var c = [];
  17938. // var points = this.points, point, intPoint, weight;
  17939. // point = ( points.length - 1 ) * t;
  17940. // intPoint = Math.floor( point );
  17941. // weight = point - intPoint;
  17942. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17943. // c[ 1 ] = intPoint;
  17944. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17945. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17946. // var pt0 = points[ c[0] ],
  17947. // pt1 = points[ c[1] ],
  17948. // pt2 = points[ c[2] ],
  17949. // pt3 = points[ c[3] ];
  17950. // // t = weight;
  17951. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17952. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17953. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17954. // return v;
  17955. // }
  17956. /**************************************************************
  17957. * Closed Spline 3D curve
  17958. **************************************************************/
  17959. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17960. function ( points /* array of Vector3 */) {
  17961. this.points = (points == undefined) ? [] : points;
  17962. },
  17963. function ( t ) {
  17964. var v = new THREE.Vector3();
  17965. var c = [];
  17966. var points = this.points, point, intPoint, weight;
  17967. point = ( points.length - 0 ) * t;
  17968. // This needs to be from 0-length +1
  17969. intPoint = Math.floor( point );
  17970. weight = point - intPoint;
  17971. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17972. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17973. c[ 1 ] = ( intPoint ) % points.length;
  17974. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17975. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17976. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17977. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17978. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17979. return v;
  17980. }
  17981. );
  17982. /**
  17983. * @author mikael emtinger / http://gomo.se/
  17984. */
  17985. THREE.AnimationHandler = {
  17986. LINEAR: 0,
  17987. CATMULLROM: 1,
  17988. CATMULLROM_FORWARD: 2,
  17989. //
  17990. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17991. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17992. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17993. //
  17994. animations: [],
  17995. init: function ( data ) {
  17996. if ( data.initialized === true ) return;
  17997. // loop through all keys
  17998. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17999. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18000. // remove minus times
  18001. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  18002. data.hierarchy[ h ].keys[ k ].time = 0;
  18003. }
  18004. // create quaternions
  18005. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18006. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18007. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18008. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  18009. }
  18010. }
  18011. // prepare morph target keys
  18012. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18013. // get all used
  18014. var usedMorphTargets = {};
  18015. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18016. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18017. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18018. usedMorphTargets[ morphTargetName ] = -1;
  18019. }
  18020. }
  18021. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18022. // set all used on all frames
  18023. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18024. var influences = {};
  18025. for ( var morphTargetName in usedMorphTargets ) {
  18026. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18027. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18028. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18029. break;
  18030. }
  18031. }
  18032. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18033. influences[ morphTargetName ] = 0;
  18034. }
  18035. }
  18036. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18037. }
  18038. }
  18039. // remove all keys that are on the same time
  18040. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18041. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18042. data.hierarchy[ h ].keys.splice( k, 1 );
  18043. k --;
  18044. }
  18045. }
  18046. // set index
  18047. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18048. data.hierarchy[ h ].keys[ k ].index = k;
  18049. }
  18050. }
  18051. data.initialized = true;
  18052. return data;
  18053. },
  18054. parse: function ( root ) {
  18055. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18056. hierarchy.push( root );
  18057. for ( var c = 0; c < root.children.length; c++ )
  18058. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18059. };
  18060. // setup hierarchy
  18061. var hierarchy = [];
  18062. if ( root instanceof THREE.SkinnedMesh ) {
  18063. for ( var b = 0; b < root.skeleton.bones.length; b++ ) {
  18064. hierarchy.push( root.skeleton.bones[ b ] );
  18065. }
  18066. } else {
  18067. parseRecurseHierarchy( root, hierarchy );
  18068. }
  18069. return hierarchy;
  18070. },
  18071. play: function ( animation ) {
  18072. if ( this.animations.indexOf( animation ) === -1 ) {
  18073. this.animations.push( animation );
  18074. }
  18075. },
  18076. stop: function ( animation ) {
  18077. var index = this.animations.indexOf( animation );
  18078. if ( index !== -1 ) {
  18079. this.animations.splice( index, 1 );
  18080. }
  18081. },
  18082. update: function ( deltaTimeMS ) {
  18083. for ( var i = 0; i < this.animations.length; i ++ ) {
  18084. this.animations[ i ].update( deltaTimeMS );
  18085. }
  18086. }
  18087. };
  18088. /**
  18089. * @author mikael emtinger / http://gomo.se/
  18090. * @author mrdoob / http://mrdoob.com/
  18091. * @author alteredq / http://alteredqualia.com/
  18092. */
  18093. THREE.Animation = function ( root, data ) {
  18094. this.root = root;
  18095. this.data = THREE.AnimationHandler.init( data );
  18096. this.hierarchy = THREE.AnimationHandler.parse( root );
  18097. this.currentTime = 0;
  18098. this.timeScale = 1;
  18099. this.isPlaying = false;
  18100. this.loop = true;
  18101. this.weight = 0;
  18102. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18103. };
  18104. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  18105. THREE.Animation.prototype.play = function ( startTime, weight ) {
  18106. this.currentTime = startTime !== undefined ? startTime : 0;
  18107. this.weight = weight !== undefined ? weight: 1;
  18108. this.isPlaying = true;
  18109. this.reset();
  18110. THREE.AnimationHandler.play( this );
  18111. };
  18112. THREE.Animation.prototype.stop = function() {
  18113. this.isPlaying = false;
  18114. THREE.AnimationHandler.stop( this );
  18115. };
  18116. THREE.Animation.prototype.reset = function () {
  18117. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18118. var object = this.hierarchy[ h ];
  18119. object.matrixAutoUpdate = true;
  18120. if ( object.animationCache === undefined ) {
  18121. object.animationCache = {};
  18122. }
  18123. if ( object.animationCache[this.data.name] === undefined ) {
  18124. object.animationCache[this.data.name] = {};
  18125. object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  18126. object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  18127. object.animationCache[this.data.name].originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18128. }
  18129. var animationCache = object.animationCache[this.data.name];
  18130. // Get keys to match our current time
  18131. for ( var t = 0; t < 3; t ++ ) {
  18132. var type = this.keyTypes[ t ];
  18133. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18134. var nextKey = this.getNextKeyWith( type, h, 1 );
  18135. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18136. prevKey = nextKey;
  18137. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18138. }
  18139. animationCache.prevKey[ type ] = prevKey;
  18140. animationCache.nextKey[ type ] = nextKey;
  18141. }
  18142. }
  18143. };
  18144. THREE.Animation.prototype.update = (function(){
  18145. var points = [];
  18146. var target = new THREE.Vector3();
  18147. var newVector = new THREE.Vector3();
  18148. var newQuat = new THREE.Quaternion();
  18149. // Catmull-Rom spline
  18150. var interpolateCatmullRom = function ( points, scale ) {
  18151. var c = [], v3 = [],
  18152. point, intPoint, weight, w2, w3,
  18153. pa, pb, pc, pd;
  18154. point = ( points.length - 1 ) * scale;
  18155. intPoint = Math.floor( point );
  18156. weight = point - intPoint;
  18157. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18158. c[ 1 ] = intPoint;
  18159. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18160. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18161. pa = points[ c[ 0 ] ];
  18162. pb = points[ c[ 1 ] ];
  18163. pc = points[ c[ 2 ] ];
  18164. pd = points[ c[ 3 ] ];
  18165. w2 = weight * weight;
  18166. w3 = weight * w2;
  18167. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18168. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18169. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18170. return v3;
  18171. };
  18172. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18173. var v0 = ( p2 - p0 ) * 0.5,
  18174. v1 = ( p3 - p1 ) * 0.5;
  18175. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18176. };
  18177. return function ( delta ) {
  18178. if ( this.isPlaying === false ) return;
  18179. this.currentTime += delta * this.timeScale;
  18180. if ( this.weight === 0 )
  18181. return;
  18182. //
  18183. var vector;
  18184. var duration = this.data.length;
  18185. if ( this.loop === true && this.currentTime > duration ) {
  18186. this.currentTime %= duration;
  18187. this.reset();
  18188. } else if ( this.loop === false && this.currentTime > duration ) {
  18189. this.stop();
  18190. return;
  18191. }
  18192. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18193. var object = this.hierarchy[ h ];
  18194. var animationCache = object.animationCache[this.data.name];
  18195. // loop through pos/rot/scl
  18196. for ( var t = 0; t < 3; t ++ ) {
  18197. // get keys
  18198. var type = this.keyTypes[ t ];
  18199. var prevKey = animationCache.prevKey[ type ];
  18200. var nextKey = animationCache.nextKey[ type ];
  18201. if ( nextKey.time <= this.currentTime ) {
  18202. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18203. nextKey = this.getNextKeyWith( type, h, 1 );
  18204. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18205. prevKey = nextKey;
  18206. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18207. }
  18208. animationCache.prevKey[ type ] = prevKey;
  18209. animationCache.nextKey[ type ] = nextKey;
  18210. }
  18211. object.matrixAutoUpdate = true;
  18212. object.matrixWorldNeedsUpdate = true;
  18213. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18214. var prevXYZ = prevKey[ type ];
  18215. var nextXYZ = nextKey[ type ];
  18216. if ( scale < 0 ) scale = 0;
  18217. if ( scale > 1 ) scale = 1;
  18218. // interpolate
  18219. if ( type === "pos" ) {
  18220. vector = object.position;
  18221. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18222. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18223. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18224. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18225. // blend
  18226. if (object instanceof THREE.Bone) {
  18227. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18228. vector.lerp( newVector, proportionalWeight );
  18229. object.accumulatedPosWeight += this.weight;
  18230. } else
  18231. vector = newVector;
  18232. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18233. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18234. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18235. points[ 1 ] = prevXYZ;
  18236. points[ 2 ] = nextXYZ;
  18237. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18238. scale = scale * 0.33 + 0.33;
  18239. var currentPoint = interpolateCatmullRom( points, scale );
  18240. if ( object instanceof THREE.Bone ) {
  18241. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18242. object.accumulatedPosWeight += this.weight;
  18243. }
  18244. else
  18245. var proportionalWeight = 1;
  18246. // blend
  18247. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18248. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18249. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18250. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18251. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18252. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18253. target.sub( vector );
  18254. target.y = 0;
  18255. target.normalize();
  18256. var angle = Math.atan2( target.x, target.z );
  18257. object.rotation.set( 0, angle, 0 );
  18258. }
  18259. }
  18260. } else if ( type === "rot" ) {
  18261. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18262. // Avoid paying the cost of an additional slerp if we don't have to
  18263. if ( !( object instanceof THREE.Bone ) ) {
  18264. object.quaternion.copy(newQuat);
  18265. }
  18266. else if ( object.accumulatedRotWeight === 0) {
  18267. object.quaternion.copy(newQuat);
  18268. object.accumulatedRotWeight = this.weight;
  18269. }
  18270. else {
  18271. var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight );
  18272. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18273. object.accumulatedRotWeight += this.weight;
  18274. }
  18275. } else if ( type === "scl" ) {
  18276. vector = object.scale;
  18277. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18278. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18279. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18280. if ( object instanceof THREE.Bone ) {
  18281. var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight);
  18282. vector.lerp( newVector, proportionalWeight );
  18283. object.accumulatedSclWeight += this.weight;
  18284. } else
  18285. vector = newVector;
  18286. }
  18287. }
  18288. }
  18289. return true;
  18290. };
  18291. })();
  18292. // Get next key with
  18293. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18294. var keys = this.data.hierarchy[ h ].keys;
  18295. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18296. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18297. key = key < keys.length - 1 ? key : keys.length - 1;
  18298. } else {
  18299. key = key % keys.length;
  18300. }
  18301. for ( ; key < keys.length; key++ ) {
  18302. if ( keys[ key ][ type ] !== undefined ) {
  18303. return keys[ key ];
  18304. }
  18305. }
  18306. return this.data.hierarchy[ h ].keys[ 0 ];
  18307. };
  18308. // Get previous key with
  18309. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18310. var keys = this.data.hierarchy[ h ].keys;
  18311. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18312. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18313. key = key > 0 ? key : 0;
  18314. } else {
  18315. key = key >= 0 ? key : key + keys.length;
  18316. }
  18317. for ( ; key >= 0; key -- ) {
  18318. if ( keys[ key ][ type ] !== undefined ) {
  18319. return keys[ key ];
  18320. }
  18321. }
  18322. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18323. };
  18324. /**
  18325. * @author mikael emtinger / http://gomo.se/
  18326. * @author mrdoob / http://mrdoob.com/
  18327. * @author alteredq / http://alteredqualia.com/
  18328. * @author khang duong
  18329. * @author erik kitson
  18330. */
  18331. THREE.KeyFrameAnimation = function ( data ) {
  18332. this.root = data.node;
  18333. this.data = THREE.AnimationHandler.init( data );
  18334. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18335. this.currentTime = 0;
  18336. this.timeScale = 0.001;
  18337. this.isPlaying = false;
  18338. this.isPaused = true;
  18339. this.loop = true;
  18340. // initialize to first keyframes
  18341. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18342. var keys = this.data.hierarchy[h].keys,
  18343. sids = this.data.hierarchy[h].sids,
  18344. obj = this.hierarchy[h];
  18345. if ( keys.length && sids ) {
  18346. for ( var s = 0; s < sids.length; s++ ) {
  18347. var sid = sids[ s ],
  18348. next = this.getNextKeyWith( sid, h, 0 );
  18349. if ( next ) {
  18350. next.apply( sid );
  18351. }
  18352. }
  18353. obj.matrixAutoUpdate = false;
  18354. this.data.hierarchy[h].node.updateMatrix();
  18355. obj.matrixWorldNeedsUpdate = true;
  18356. }
  18357. }
  18358. };
  18359. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18360. this.currentTime = startTime !== undefined ? startTime : 0;
  18361. if ( this.isPlaying === false ) {
  18362. this.isPlaying = true;
  18363. // reset key cache
  18364. var h, hl = this.hierarchy.length,
  18365. object,
  18366. node;
  18367. for ( h = 0; h < hl; h++ ) {
  18368. object = this.hierarchy[ h ];
  18369. node = this.data.hierarchy[ h ];
  18370. if ( node.animationCache === undefined ) {
  18371. node.animationCache = {};
  18372. node.animationCache.prevKey = null;
  18373. node.animationCache.nextKey = null;
  18374. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18375. }
  18376. var keys = this.data.hierarchy[h].keys;
  18377. if (keys.length) {
  18378. node.animationCache.prevKey = keys[ 0 ];
  18379. node.animationCache.nextKey = keys[ 1 ];
  18380. this.startTime = Math.min( keys[0].time, this.startTime );
  18381. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18382. }
  18383. }
  18384. this.update( 0 );
  18385. }
  18386. this.isPaused = false;
  18387. THREE.AnimationHandler.play( this );
  18388. };
  18389. THREE.KeyFrameAnimation.prototype.stop = function() {
  18390. this.isPlaying = false;
  18391. this.isPaused = false;
  18392. THREE.AnimationHandler.stop( this );
  18393. // reset JIT matrix and remove cache
  18394. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18395. var obj = this.hierarchy[ h ];
  18396. var node = this.data.hierarchy[ h ];
  18397. if ( node.animationCache !== undefined ) {
  18398. var original = node.animationCache.originalMatrix;
  18399. if( obj instanceof THREE.Bone ) {
  18400. original.copy( obj.skinMatrix );
  18401. obj.skinMatrix = original;
  18402. } else {
  18403. original.copy( obj.matrix );
  18404. obj.matrix = original;
  18405. }
  18406. delete node.animationCache;
  18407. }
  18408. }
  18409. };
  18410. // Update
  18411. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18412. if ( this.isPlaying === false ) return;
  18413. this.currentTime += delta * this.timeScale;
  18414. //
  18415. var duration = this.data.length;
  18416. if ( this.loop === true && this.currentTime > duration ) {
  18417. this.currentTime %= duration;
  18418. }
  18419. this.currentTime = Math.min( this.currentTime, duration );
  18420. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18421. var object = this.hierarchy[ h ];
  18422. var node = this.data.hierarchy[ h ];
  18423. var keys = node.keys,
  18424. animationCache = node.animationCache;
  18425. if ( keys.length ) {
  18426. var prevKey = animationCache.prevKey;
  18427. var nextKey = animationCache.nextKey;
  18428. if ( nextKey.time <= this.currentTime ) {
  18429. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18430. prevKey = nextKey;
  18431. nextKey = keys[ prevKey.index + 1 ];
  18432. }
  18433. animationCache.prevKey = prevKey;
  18434. animationCache.nextKey = nextKey;
  18435. }
  18436. if ( nextKey.time >= this.currentTime ) {
  18437. prevKey.interpolate( nextKey, this.currentTime );
  18438. } else {
  18439. prevKey.interpolate( nextKey, nextKey.time );
  18440. }
  18441. this.data.hierarchy[ h ].node.updateMatrix();
  18442. object.matrixWorldNeedsUpdate = true;
  18443. }
  18444. }
  18445. };
  18446. // Get next key with
  18447. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18448. var keys = this.data.hierarchy[ h ].keys;
  18449. key = key % keys.length;
  18450. for ( ; key < keys.length; key++ ) {
  18451. if ( keys[ key ].hasTarget( sid ) ) {
  18452. return keys[ key ];
  18453. }
  18454. }
  18455. return keys[ 0 ];
  18456. };
  18457. // Get previous key with
  18458. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18459. var keys = this.data.hierarchy[ h ].keys;
  18460. key = key >= 0 ? key : key + keys.length;
  18461. for ( ; key >= 0; key-- ) {
  18462. if ( keys[ key ].hasTarget( sid ) ) {
  18463. return keys[ key ];
  18464. }
  18465. }
  18466. return keys[ keys.length - 1 ];
  18467. };
  18468. /**
  18469. * @author mrdoob / http://mrdoob.com
  18470. */
  18471. THREE.MorphAnimation = function ( mesh ) {
  18472. this.mesh = mesh;
  18473. this.frames = mesh.morphTargetInfluences.length;
  18474. this.currentTime = 0;
  18475. this.duration = 1000;
  18476. this.loop = true;
  18477. this.isPlaying = false;
  18478. };
  18479. THREE.MorphAnimation.prototype = {
  18480. play: function () {
  18481. this.isPlaying = true;
  18482. },
  18483. pause: function () {
  18484. this.isPlaying = false;
  18485. },
  18486. update: ( function () {
  18487. var lastFrame = 0;
  18488. var currentFrame = 0;
  18489. return function ( delta ) {
  18490. if ( this.isPlaying === false ) return;
  18491. this.currentTime += delta;
  18492. if ( this.loop === true && this.currentTime > this.duration ) {
  18493. this.currentTime %= this.duration;
  18494. }
  18495. this.currentTime = Math.min( this.currentTime, this.duration );
  18496. var interpolation = this.duration / this.frames;
  18497. var frame = Math.floor( this.currentTime / interpolation );
  18498. if ( frame != currentFrame ) {
  18499. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18500. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18501. this.mesh.morphTargetInfluences[ frame ] = 0;
  18502. lastFrame = currentFrame;
  18503. currentFrame = frame;
  18504. }
  18505. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18506. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18507. }
  18508. } )()
  18509. };
  18510. /**
  18511. * Camera for rendering cube maps
  18512. * - renders scene into axis-aligned cube
  18513. *
  18514. * @author alteredq / http://alteredqualia.com/
  18515. */
  18516. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18517. THREE.Object3D.call( this );
  18518. var fov = 90, aspect = 1;
  18519. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18520. cameraPX.up.set( 0, -1, 0 );
  18521. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18522. this.add( cameraPX );
  18523. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18524. cameraNX.up.set( 0, -1, 0 );
  18525. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18526. this.add( cameraNX );
  18527. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18528. cameraPY.up.set( 0, 0, 1 );
  18529. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18530. this.add( cameraPY );
  18531. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18532. cameraNY.up.set( 0, 0, -1 );
  18533. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18534. this.add( cameraNY );
  18535. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18536. cameraPZ.up.set( 0, -1, 0 );
  18537. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18538. this.add( cameraPZ );
  18539. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18540. cameraNZ.up.set( 0, -1, 0 );
  18541. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18542. this.add( cameraNZ );
  18543. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18544. this.updateCubeMap = function ( renderer, scene ) {
  18545. var renderTarget = this.renderTarget;
  18546. var generateMipmaps = renderTarget.generateMipmaps;
  18547. renderTarget.generateMipmaps = false;
  18548. renderTarget.activeCubeFace = 0;
  18549. renderer.render( scene, cameraPX, renderTarget );
  18550. renderTarget.activeCubeFace = 1;
  18551. renderer.render( scene, cameraNX, renderTarget );
  18552. renderTarget.activeCubeFace = 2;
  18553. renderer.render( scene, cameraPY, renderTarget );
  18554. renderTarget.activeCubeFace = 3;
  18555. renderer.render( scene, cameraNY, renderTarget );
  18556. renderTarget.activeCubeFace = 4;
  18557. renderer.render( scene, cameraPZ, renderTarget );
  18558. renderTarget.generateMipmaps = generateMipmaps;
  18559. renderTarget.activeCubeFace = 5;
  18560. renderer.render( scene, cameraNZ, renderTarget );
  18561. };
  18562. };
  18563. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18564. /**
  18565. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18566. *
  18567. * A general perpose camera, for setting FOV, Lens Focal Length,
  18568. * and switching between perspective and orthographic views easily.
  18569. * Use this only if you do not wish to manage
  18570. * both a Orthographic and Perspective Camera
  18571. *
  18572. */
  18573. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18574. THREE.Camera.call( this );
  18575. this.fov = fov;
  18576. this.left = -width / 2;
  18577. this.right = width / 2
  18578. this.top = height / 2;
  18579. this.bottom = -height / 2;
  18580. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18581. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18582. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18583. this.zoom = 1;
  18584. this.toPerspective();
  18585. var aspect = width/height;
  18586. };
  18587. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18588. THREE.CombinedCamera.prototype.toPerspective = function () {
  18589. // Switches to the Perspective Camera
  18590. this.near = this.cameraP.near;
  18591. this.far = this.cameraP.far;
  18592. this.cameraP.fov = this.fov / this.zoom ;
  18593. this.cameraP.updateProjectionMatrix();
  18594. this.projectionMatrix = this.cameraP.projectionMatrix;
  18595. this.inPerspectiveMode = true;
  18596. this.inOrthographicMode = false;
  18597. };
  18598. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18599. // Switches to the Orthographic camera estimating viewport from Perspective
  18600. var fov = this.fov;
  18601. var aspect = this.cameraP.aspect;
  18602. var near = this.cameraP.near;
  18603. var far = this.cameraP.far;
  18604. // The size that we set is the mid plane of the viewing frustum
  18605. var hyperfocus = ( near + far ) / 2;
  18606. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18607. var planeHeight = 2 * halfHeight;
  18608. var planeWidth = planeHeight * aspect;
  18609. var halfWidth = planeWidth / 2;
  18610. halfHeight /= this.zoom;
  18611. halfWidth /= this.zoom;
  18612. this.cameraO.left = -halfWidth;
  18613. this.cameraO.right = halfWidth;
  18614. this.cameraO.top = halfHeight;
  18615. this.cameraO.bottom = -halfHeight;
  18616. // this.cameraO.left = -farHalfWidth;
  18617. // this.cameraO.right = farHalfWidth;
  18618. // this.cameraO.top = farHalfHeight;
  18619. // this.cameraO.bottom = -farHalfHeight;
  18620. // this.cameraO.left = this.left / this.zoom;
  18621. // this.cameraO.right = this.right / this.zoom;
  18622. // this.cameraO.top = this.top / this.zoom;
  18623. // this.cameraO.bottom = this.bottom / this.zoom;
  18624. this.cameraO.updateProjectionMatrix();
  18625. this.near = this.cameraO.near;
  18626. this.far = this.cameraO.far;
  18627. this.projectionMatrix = this.cameraO.projectionMatrix;
  18628. this.inPerspectiveMode = false;
  18629. this.inOrthographicMode = true;
  18630. };
  18631. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18632. this.cameraP.aspect = width / height;
  18633. this.left = -width / 2;
  18634. this.right = width / 2
  18635. this.top = height / 2;
  18636. this.bottom = -height / 2;
  18637. };
  18638. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18639. this.fov = fov;
  18640. if ( this.inPerspectiveMode ) {
  18641. this.toPerspective();
  18642. } else {
  18643. this.toOrthographic();
  18644. }
  18645. };
  18646. // For mantaining similar API with PerspectiveCamera
  18647. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18648. if ( this.inPerspectiveMode ) {
  18649. this.toPerspective();
  18650. } else {
  18651. this.toPerspective();
  18652. this.toOrthographic();
  18653. }
  18654. };
  18655. /*
  18656. * Uses Focal Length (in mm) to estimate and set FOV
  18657. * 35mm (fullframe) camera is used if frame size is not specified;
  18658. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18659. */
  18660. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18661. if ( frameHeight === undefined ) frameHeight = 24;
  18662. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18663. this.setFov( fov );
  18664. return fov;
  18665. };
  18666. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18667. this.zoom = zoom;
  18668. if ( this.inPerspectiveMode ) {
  18669. this.toPerspective();
  18670. } else {
  18671. this.toOrthographic();
  18672. }
  18673. };
  18674. THREE.CombinedCamera.prototype.toFrontView = function() {
  18675. this.rotation.x = 0;
  18676. this.rotation.y = 0;
  18677. this.rotation.z = 0;
  18678. // should we be modifing the matrix instead?
  18679. this.rotationAutoUpdate = false;
  18680. };
  18681. THREE.CombinedCamera.prototype.toBackView = function() {
  18682. this.rotation.x = 0;
  18683. this.rotation.y = Math.PI;
  18684. this.rotation.z = 0;
  18685. this.rotationAutoUpdate = false;
  18686. };
  18687. THREE.CombinedCamera.prototype.toLeftView = function() {
  18688. this.rotation.x = 0;
  18689. this.rotation.y = - Math.PI / 2;
  18690. this.rotation.z = 0;
  18691. this.rotationAutoUpdate = false;
  18692. };
  18693. THREE.CombinedCamera.prototype.toRightView = function() {
  18694. this.rotation.x = 0;
  18695. this.rotation.y = Math.PI / 2;
  18696. this.rotation.z = 0;
  18697. this.rotationAutoUpdate = false;
  18698. };
  18699. THREE.CombinedCamera.prototype.toTopView = function() {
  18700. this.rotation.x = - Math.PI / 2;
  18701. this.rotation.y = 0;
  18702. this.rotation.z = 0;
  18703. this.rotationAutoUpdate = false;
  18704. };
  18705. THREE.CombinedCamera.prototype.toBottomView = function() {
  18706. this.rotation.x = Math.PI / 2;
  18707. this.rotation.y = 0;
  18708. this.rotation.z = 0;
  18709. this.rotationAutoUpdate = false;
  18710. };
  18711. /**
  18712. * @author mrdoob / http://mrdoob.com/
  18713. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18714. */
  18715. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18716. THREE.Geometry.call( this );
  18717. this.parameters = {
  18718. width: width,
  18719. height: height,
  18720. depth: depth,
  18721. widthSegments: widthSegments,
  18722. heightSegments: heightSegments,
  18723. depthSegments: depthSegments
  18724. };
  18725. this.widthSegments = widthSegments || 1;
  18726. this.heightSegments = heightSegments || 1;
  18727. this.depthSegments = depthSegments || 1;
  18728. var scope = this;
  18729. var width_half = width / 2;
  18730. var height_half = height / 2;
  18731. var depth_half = depth / 2;
  18732. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18733. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18734. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18735. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18736. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18737. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18738. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18739. var w, ix, iy,
  18740. gridX = scope.widthSegments,
  18741. gridY = scope.heightSegments,
  18742. width_half = width / 2,
  18743. height_half = height / 2,
  18744. offset = scope.vertices.length;
  18745. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18746. w = 'z';
  18747. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18748. w = 'y';
  18749. gridY = scope.depthSegments;
  18750. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18751. w = 'x';
  18752. gridX = scope.depthSegments;
  18753. }
  18754. var gridX1 = gridX + 1,
  18755. gridY1 = gridY + 1,
  18756. segment_width = width / gridX,
  18757. segment_height = height / gridY,
  18758. normal = new THREE.Vector3();
  18759. normal[ w ] = depth > 0 ? 1 : - 1;
  18760. for ( iy = 0; iy < gridY1; iy ++ ) {
  18761. for ( ix = 0; ix < gridX1; ix ++ ) {
  18762. var vector = new THREE.Vector3();
  18763. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18764. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18765. vector[ w ] = depth;
  18766. scope.vertices.push( vector );
  18767. }
  18768. }
  18769. for ( iy = 0; iy < gridY; iy++ ) {
  18770. for ( ix = 0; ix < gridX; ix++ ) {
  18771. var a = ix + gridX1 * iy;
  18772. var b = ix + gridX1 * ( iy + 1 );
  18773. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18774. var d = ( ix + 1 ) + gridX1 * iy;
  18775. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18776. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18777. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18778. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18779. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18780. face.normal.copy( normal );
  18781. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18782. face.materialIndex = materialIndex;
  18783. scope.faces.push( face );
  18784. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18785. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18786. face.normal.copy( normal );
  18787. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18788. face.materialIndex = materialIndex;
  18789. scope.faces.push( face );
  18790. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18791. }
  18792. }
  18793. }
  18794. this.mergeVertices();
  18795. };
  18796. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18797. /**
  18798. * @author hughes
  18799. */
  18800. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18801. THREE.Geometry.call( this );
  18802. this.parameters = {
  18803. radius: radius,
  18804. segments: segments,
  18805. thetaStart: thetaStart,
  18806. thetaLength: thetaLength
  18807. };
  18808. radius = radius || 50;
  18809. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18810. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18811. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18812. var i, uvs = [],
  18813. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18814. this.vertices.push(center);
  18815. uvs.push( centerUV );
  18816. for ( i = 0; i <= segments; i ++ ) {
  18817. var vertex = new THREE.Vector3();
  18818. var segment = thetaStart + i / segments * thetaLength;
  18819. vertex.x = radius * Math.cos( segment );
  18820. vertex.y = radius * Math.sin( segment );
  18821. this.vertices.push( vertex );
  18822. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18823. }
  18824. var n = new THREE.Vector3( 0, 0, 1 );
  18825. for ( i = 1; i <= segments; i ++ ) {
  18826. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18827. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18828. }
  18829. this.computeFaceNormals();
  18830. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18831. };
  18832. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18833. // DEPRECATED
  18834. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18835. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  18836. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18837. };
  18838. /**
  18839. * @author mrdoob / http://mrdoob.com/
  18840. */
  18841. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18842. THREE.Geometry.call( this );
  18843. this.parameters = {
  18844. radiusTop: radiusTop,
  18845. radiusBottom: radiusBottom,
  18846. height: height,
  18847. radialSegments: radialSegments,
  18848. heightSegments: heightSegments,
  18849. openEnded: openEnded
  18850. };
  18851. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18852. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18853. height = height !== undefined ? height : 100;
  18854. radialSegments = radialSegments || 8;
  18855. heightSegments = heightSegments || 1;
  18856. openEnded = openEnded !== undefined ? openEnded : false;
  18857. var heightHalf = height / 2;
  18858. var x, y, vertices = [], uvs = [];
  18859. for ( y = 0; y <= heightSegments; y ++ ) {
  18860. var verticesRow = [];
  18861. var uvsRow = [];
  18862. var v = y / heightSegments;
  18863. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18864. for ( x = 0; x <= radialSegments; x ++ ) {
  18865. var u = x / radialSegments;
  18866. var vertex = new THREE.Vector3();
  18867. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18868. vertex.y = - v * height + heightHalf;
  18869. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18870. this.vertices.push( vertex );
  18871. verticesRow.push( this.vertices.length - 1 );
  18872. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18873. }
  18874. vertices.push( verticesRow );
  18875. uvs.push( uvsRow );
  18876. }
  18877. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18878. var na, nb;
  18879. for ( x = 0; x < radialSegments; x ++ ) {
  18880. if ( radiusTop !== 0 ) {
  18881. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18882. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18883. } else {
  18884. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18885. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18886. }
  18887. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18888. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18889. for ( y = 0; y < heightSegments; y ++ ) {
  18890. var v1 = vertices[ y ][ x ];
  18891. var v2 = vertices[ y + 1 ][ x ];
  18892. var v3 = vertices[ y + 1 ][ x + 1 ];
  18893. var v4 = vertices[ y ][ x + 1 ];
  18894. var n1 = na.clone();
  18895. var n2 = na.clone();
  18896. var n3 = nb.clone();
  18897. var n4 = nb.clone();
  18898. var uv1 = uvs[ y ][ x ].clone();
  18899. var uv2 = uvs[ y + 1 ][ x ].clone();
  18900. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18901. var uv4 = uvs[ y ][ x + 1 ].clone();
  18902. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18903. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18904. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18905. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18906. }
  18907. }
  18908. // top cap
  18909. if ( openEnded === false && radiusTop > 0 ) {
  18910. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18911. for ( x = 0; x < radialSegments; x ++ ) {
  18912. var v1 = vertices[ 0 ][ x ];
  18913. var v2 = vertices[ 0 ][ x + 1 ];
  18914. var v3 = this.vertices.length - 1;
  18915. var n1 = new THREE.Vector3( 0, 1, 0 );
  18916. var n2 = new THREE.Vector3( 0, 1, 0 );
  18917. var n3 = new THREE.Vector3( 0, 1, 0 );
  18918. var uv1 = uvs[ 0 ][ x ].clone();
  18919. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18920. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18921. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18922. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18923. }
  18924. }
  18925. // bottom cap
  18926. if ( openEnded === false && radiusBottom > 0 ) {
  18927. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18928. for ( x = 0; x < radialSegments; x ++ ) {
  18929. var v1 = vertices[ y ][ x + 1 ];
  18930. var v2 = vertices[ y ][ x ];
  18931. var v3 = this.vertices.length - 1;
  18932. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18933. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18934. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18935. var uv1 = uvs[ y ][ x + 1 ].clone();
  18936. var uv2 = uvs[ y ][ x ].clone();
  18937. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18938. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18939. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18940. }
  18941. }
  18942. this.computeFaceNormals();
  18943. }
  18944. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18945. /**
  18946. * @author zz85 / http://www.lab4games.net/zz85/blog
  18947. *
  18948. * Creates extruded geometry from a path shape.
  18949. *
  18950. * parameters = {
  18951. *
  18952. * curveSegments: <int>, // number of points on the curves
  18953. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18954. * amount: <int>, // Depth to extrude the shape
  18955. *
  18956. * bevelEnabled: <bool>, // turn on bevel
  18957. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18958. * bevelSize: <float>, // how far from shape outline is bevel
  18959. * bevelSegments: <int>, // number of bevel layers
  18960. *
  18961. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18962. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18963. *
  18964. * material: <int> // material index for front and back faces
  18965. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18966. * uvGenerator: <Object> // object that provides UV generator functions
  18967. *
  18968. * }
  18969. **/
  18970. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18971. if ( typeof( shapes ) === "undefined" ) {
  18972. shapes = [];
  18973. return;
  18974. }
  18975. THREE.Geometry.call( this );
  18976. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18977. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18978. this.addShapeList( shapes, options );
  18979. this.computeFaceNormals();
  18980. // can't really use automatic vertex normals
  18981. // as then front and back sides get smoothed too
  18982. // should do separate smoothing just for sides
  18983. //this.computeVertexNormals();
  18984. //console.log( "took", ( Date.now() - startTime ) );
  18985. };
  18986. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18987. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18988. var sl = shapes.length;
  18989. for ( var s = 0; s < sl; s ++ ) {
  18990. var shape = shapes[ s ];
  18991. this.addShape( shape, options );
  18992. }
  18993. };
  18994. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18995. var amount = options.amount !== undefined ? options.amount : 100;
  18996. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18997. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18998. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18999. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19000. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19001. var steps = options.steps !== undefined ? options.steps : 1;
  19002. var extrudePath = options.extrudePath;
  19003. var extrudePts, extrudeByPath = false;
  19004. var material = options.material;
  19005. var extrudeMaterial = options.extrudeMaterial;
  19006. // Use default WorldUVGenerator if no UV generators are specified.
  19007. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19008. var shapebb = this.shapebb;
  19009. //shapebb = shape.getBoundingBox();
  19010. var splineTube, binormal, normal, position2;
  19011. if ( extrudePath ) {
  19012. extrudePts = extrudePath.getSpacedPoints( steps );
  19013. extrudeByPath = true;
  19014. bevelEnabled = false; // bevels not supported for path extrusion
  19015. // SETUP TNB variables
  19016. // Reuse TNB from TubeGeomtry for now.
  19017. // TODO1 - have a .isClosed in spline?
  19018. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19019. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19020. binormal = new THREE.Vector3();
  19021. normal = new THREE.Vector3();
  19022. position2 = new THREE.Vector3();
  19023. }
  19024. // Safeguards if bevels are not enabled
  19025. if ( ! bevelEnabled ) {
  19026. bevelSegments = 0;
  19027. bevelThickness = 0;
  19028. bevelSize = 0;
  19029. }
  19030. // Variables initalization
  19031. var ahole, h, hl; // looping of holes
  19032. var scope = this;
  19033. var bevelPoints = [];
  19034. var shapesOffset = this.vertices.length;
  19035. var shapePoints = shape.extractPoints( curveSegments );
  19036. var vertices = shapePoints.shape;
  19037. var holes = shapePoints.holes;
  19038. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19039. if ( reverse ) {
  19040. vertices = vertices.reverse();
  19041. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19042. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19043. ahole = holes[ h ];
  19044. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19045. holes[ h ] = ahole.reverse();
  19046. }
  19047. }
  19048. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19049. }
  19050. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19051. /* Vertices */
  19052. var contour = vertices; // vertices has all points but contour has only points of circumference
  19053. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19054. ahole = holes[ h ];
  19055. vertices = vertices.concat( ahole );
  19056. }
  19057. function scalePt2 ( pt, vec, size ) {
  19058. if ( !vec ) console.log( "die" );
  19059. return vec.clone().multiplyScalar( size ).add( pt );
  19060. }
  19061. var b, bs, t, z,
  19062. vert, vlen = vertices.length,
  19063. face, flen = faces.length,
  19064. cont, clen = contour.length;
  19065. // Find directions for point movement
  19066. var RAD_TO_DEGREES = 180 / Math.PI;
  19067. function getBevelVec( inPt, inPrev, inNext ) {
  19068. var EPSILON = 0.0000000001;
  19069. var sign = THREE.Math.sign;
  19070. // computes for inPt the corresponding point inPt' on a new contour
  19071. // shiftet by 1 unit (length of normalized vector) to the left
  19072. // if we walk along contour clockwise, this new contour is outside the old one
  19073. //
  19074. // inPt' is the intersection of the two lines parallel to the two
  19075. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19076. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19077. // good reading for geometry algorithms (here: line-line intersection)
  19078. // http://geomalgorithms.com/a05-_intersect-1.html
  19079. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19080. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19081. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19082. // check for colinear edges
  19083. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19084. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19085. // length of vectors for normalizing
  19086. var v_prev_len = Math.sqrt( v_prev_lensq );
  19087. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19088. // shift adjacent points by unit vectors to the left
  19089. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19090. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19091. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19092. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19093. // scaling factor for v_prev to intersection point
  19094. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19095. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19096. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19097. // vector from inPt to intersection point
  19098. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19099. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19100. // Don't normalize!, otherwise sharp corners become ugly
  19101. // but prevent crazy spikes
  19102. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19103. if ( v_trans_lensq <= 2 ) {
  19104. return new THREE.Vector2( v_trans_x, v_trans_y );
  19105. } else {
  19106. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19107. }
  19108. } else { // handle special case of colinear edges
  19109. var direction_eq = false; // assumes: opposite
  19110. if ( v_prev_x > EPSILON ) {
  19111. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19112. } else {
  19113. if ( v_prev_x < -EPSILON ) {
  19114. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19115. } else {
  19116. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19117. }
  19118. }
  19119. if ( direction_eq ) {
  19120. // console.log("Warning: lines are a straight sequence");
  19121. v_trans_x = -v_prev_y;
  19122. v_trans_y = v_prev_x;
  19123. shrink_by = Math.sqrt( v_prev_lensq );
  19124. } else {
  19125. // console.log("Warning: lines are a straight spike");
  19126. v_trans_x = v_prev_x;
  19127. v_trans_y = v_prev_y;
  19128. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19129. }
  19130. }
  19131. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19132. }
  19133. var contourMovements = [];
  19134. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19135. if ( j === il ) j = 0;
  19136. if ( k === il ) k = 0;
  19137. // (j)---(i)---(k)
  19138. // console.log('i,j,k', i, j , k)
  19139. var pt_i = contour[ i ];
  19140. var pt_j = contour[ j ];
  19141. var pt_k = contour[ k ];
  19142. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19143. }
  19144. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19145. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19146. ahole = holes[ h ];
  19147. oneHoleMovements = [];
  19148. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19149. if ( j === il ) j = 0;
  19150. if ( k === il ) k = 0;
  19151. // (j)---(i)---(k)
  19152. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19153. }
  19154. holesMovements.push( oneHoleMovements );
  19155. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19156. }
  19157. // Loop bevelSegments, 1 for the front, 1 for the back
  19158. for ( b = 0; b < bevelSegments; b ++ ) {
  19159. //for ( b = bevelSegments; b > 0; b -- ) {
  19160. t = b / bevelSegments;
  19161. z = bevelThickness * ( 1 - t );
  19162. //z = bevelThickness * t;
  19163. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19164. //bs = bevelSize * t ; // linear
  19165. // contract shape
  19166. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19167. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19168. v( vert.x, vert.y, - z );
  19169. }
  19170. // expand holes
  19171. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19172. ahole = holes[ h ];
  19173. oneHoleMovements = holesMovements[ h ];
  19174. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19175. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19176. v( vert.x, vert.y, -z );
  19177. }
  19178. }
  19179. }
  19180. bs = bevelSize;
  19181. // Back facing vertices
  19182. for ( i = 0; i < vlen; i ++ ) {
  19183. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19184. if ( !extrudeByPath ) {
  19185. v( vert.x, vert.y, 0 );
  19186. } else {
  19187. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19188. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19189. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19190. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19191. v( position2.x, position2.y, position2.z );
  19192. }
  19193. }
  19194. // Add stepped vertices...
  19195. // Including front facing vertices
  19196. var s;
  19197. for ( s = 1; s <= steps; s ++ ) {
  19198. for ( i = 0; i < vlen; i ++ ) {
  19199. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19200. if ( !extrudeByPath ) {
  19201. v( vert.x, vert.y, amount / steps * s );
  19202. } else {
  19203. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19204. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19205. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19206. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19207. v( position2.x, position2.y, position2.z );
  19208. }
  19209. }
  19210. }
  19211. // Add bevel segments planes
  19212. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19213. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19214. t = b / bevelSegments;
  19215. z = bevelThickness * ( 1 - t );
  19216. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19217. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19218. // contract shape
  19219. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19220. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19221. v( vert.x, vert.y, amount + z );
  19222. }
  19223. // expand holes
  19224. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19225. ahole = holes[ h ];
  19226. oneHoleMovements = holesMovements[ h ];
  19227. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19228. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19229. if ( !extrudeByPath ) {
  19230. v( vert.x, vert.y, amount + z );
  19231. } else {
  19232. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19233. }
  19234. }
  19235. }
  19236. }
  19237. /* Faces */
  19238. // Top and bottom faces
  19239. buildLidFaces();
  19240. // Sides faces
  19241. buildSideFaces();
  19242. ///// Internal functions
  19243. function buildLidFaces() {
  19244. if ( bevelEnabled ) {
  19245. var layer = 0 ; // steps + 1
  19246. var offset = vlen * layer;
  19247. // Bottom faces
  19248. for ( i = 0; i < flen; i ++ ) {
  19249. face = faces[ i ];
  19250. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19251. }
  19252. layer = steps + bevelSegments * 2;
  19253. offset = vlen * layer;
  19254. // Top faces
  19255. for ( i = 0; i < flen; i ++ ) {
  19256. face = faces[ i ];
  19257. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19258. }
  19259. } else {
  19260. // Bottom faces
  19261. for ( i = 0; i < flen; i++ ) {
  19262. face = faces[ i ];
  19263. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19264. }
  19265. // Top faces
  19266. for ( i = 0; i < flen; i ++ ) {
  19267. face = faces[ i ];
  19268. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19269. }
  19270. }
  19271. }
  19272. // Create faces for the z-sides of the shape
  19273. function buildSideFaces() {
  19274. var layeroffset = 0;
  19275. sidewalls( contour, layeroffset );
  19276. layeroffset += contour.length;
  19277. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19278. ahole = holes[ h ];
  19279. sidewalls( ahole, layeroffset );
  19280. //, true
  19281. layeroffset += ahole.length;
  19282. }
  19283. }
  19284. function sidewalls( contour, layeroffset ) {
  19285. var j, k;
  19286. i = contour.length;
  19287. while ( --i >= 0 ) {
  19288. j = i;
  19289. k = i - 1;
  19290. if ( k < 0 ) k = contour.length - 1;
  19291. //console.log('b', i,j, i-1, k,vertices.length);
  19292. var s = 0, sl = steps + bevelSegments * 2;
  19293. for ( s = 0; s < sl; s ++ ) {
  19294. var slen1 = vlen * s;
  19295. var slen2 = vlen * ( s + 1 );
  19296. var a = layeroffset + j + slen1,
  19297. b = layeroffset + k + slen1,
  19298. c = layeroffset + k + slen2,
  19299. d = layeroffset + j + slen2;
  19300. f4( a, b, c, d, contour, s, sl, j, k );
  19301. }
  19302. }
  19303. }
  19304. function v( x, y, z ) {
  19305. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19306. }
  19307. function f3( a, b, c, isBottom ) {
  19308. a += shapesOffset;
  19309. b += shapesOffset;
  19310. c += shapesOffset;
  19311. // normal, color, material
  19312. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19313. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19314. scope.faceVertexUvs[ 0 ].push( uvs );
  19315. }
  19316. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19317. a += shapesOffset;
  19318. b += shapesOffset;
  19319. c += shapesOffset;
  19320. d += shapesOffset;
  19321. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19322. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19323. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19324. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19325. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19326. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19327. }
  19328. };
  19329. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19330. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19331. var ax = geometry.vertices[ indexA ].x,
  19332. ay = geometry.vertices[ indexA ].y,
  19333. bx = geometry.vertices[ indexB ].x,
  19334. by = geometry.vertices[ indexB ].y,
  19335. cx = geometry.vertices[ indexC ].x,
  19336. cy = geometry.vertices[ indexC ].y;
  19337. return [
  19338. new THREE.Vector2( ax, ay ),
  19339. new THREE.Vector2( bx, by ),
  19340. new THREE.Vector2( cx, cy )
  19341. ];
  19342. },
  19343. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19344. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19345. },
  19346. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19347. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19348. contourIndex1, contourIndex2 ) {
  19349. var ax = geometry.vertices[ indexA ].x,
  19350. ay = geometry.vertices[ indexA ].y,
  19351. az = geometry.vertices[ indexA ].z,
  19352. bx = geometry.vertices[ indexB ].x,
  19353. by = geometry.vertices[ indexB ].y,
  19354. bz = geometry.vertices[ indexB ].z,
  19355. cx = geometry.vertices[ indexC ].x,
  19356. cy = geometry.vertices[ indexC ].y,
  19357. cz = geometry.vertices[ indexC ].z,
  19358. dx = geometry.vertices[ indexD ].x,
  19359. dy = geometry.vertices[ indexD ].y,
  19360. dz = geometry.vertices[ indexD ].z;
  19361. if ( Math.abs( ay - by ) < 0.01 ) {
  19362. return [
  19363. new THREE.Vector2( ax, 1 - az ),
  19364. new THREE.Vector2( bx, 1 - bz ),
  19365. new THREE.Vector2( cx, 1 - cz ),
  19366. new THREE.Vector2( dx, 1 - dz )
  19367. ];
  19368. } else {
  19369. return [
  19370. new THREE.Vector2( ay, 1 - az ),
  19371. new THREE.Vector2( by, 1 - bz ),
  19372. new THREE.Vector2( cy, 1 - cz ),
  19373. new THREE.Vector2( dy, 1 - dz )
  19374. ];
  19375. }
  19376. }
  19377. };
  19378. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19379. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19380. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19381. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19382. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19383. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19384. /**
  19385. * @author jonobr1 / http://jonobr1.com
  19386. *
  19387. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19388. * ExtrudeGeometry.
  19389. *
  19390. * parameters = {
  19391. *
  19392. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19393. *
  19394. * material: <int> // material index for front and back faces
  19395. * uvGenerator: <Object> // object that provides UV generator functions
  19396. *
  19397. * }
  19398. **/
  19399. THREE.ShapeGeometry = function ( shapes, options ) {
  19400. THREE.Geometry.call( this );
  19401. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19402. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19403. this.addShapeList( shapes, options );
  19404. this.computeFaceNormals();
  19405. };
  19406. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19407. /**
  19408. * Add an array of shapes to THREE.ShapeGeometry.
  19409. */
  19410. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19411. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19412. this.addShape( shapes[ i ], options );
  19413. }
  19414. return this;
  19415. };
  19416. /**
  19417. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19418. */
  19419. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19420. if ( options === undefined ) options = {};
  19421. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19422. var material = options.material;
  19423. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19424. var shapebb = this.shapebb;
  19425. //
  19426. var i, l, hole, s;
  19427. var shapesOffset = this.vertices.length;
  19428. var shapePoints = shape.extractPoints( curveSegments );
  19429. var vertices = shapePoints.shape;
  19430. var holes = shapePoints.holes;
  19431. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19432. if ( reverse ) {
  19433. vertices = vertices.reverse();
  19434. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19435. for ( i = 0, l = holes.length; i < l; i++ ) {
  19436. hole = holes[ i ];
  19437. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19438. holes[ i ] = hole.reverse();
  19439. }
  19440. }
  19441. reverse = false;
  19442. }
  19443. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19444. // Vertices
  19445. var contour = vertices;
  19446. for ( i = 0, l = holes.length; i < l; i++ ) {
  19447. hole = holes[ i ];
  19448. vertices = vertices.concat( hole );
  19449. }
  19450. //
  19451. var vert, vlen = vertices.length;
  19452. var face, flen = faces.length;
  19453. var cont, clen = contour.length;
  19454. for ( i = 0; i < vlen; i++ ) {
  19455. vert = vertices[ i ];
  19456. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19457. }
  19458. for ( i = 0; i < flen; i++ ) {
  19459. face = faces[ i ];
  19460. var a = face[ 0 ] + shapesOffset;
  19461. var b = face[ 1 ] + shapesOffset;
  19462. var c = face[ 2 ] + shapesOffset;
  19463. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19464. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19465. }
  19466. };
  19467. /**
  19468. * @author astrodud / http://astrodud.isgreat.org/
  19469. * @author zz85 / https://github.com/zz85
  19470. * @author bhouston / http://exocortex.com
  19471. */
  19472. // points - to create a closed torus, one must use a set of points
  19473. // like so: [ a, b, c, d, a ], see first is the same as last.
  19474. // segments - the number of circumference segments to create
  19475. // phiStart - the starting radian
  19476. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19477. // 2*pi is a closed lathe, less than 2PI is a portion.
  19478. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19479. THREE.Geometry.call( this );
  19480. segments = segments || 12;
  19481. phiStart = phiStart || 0;
  19482. phiLength = phiLength || 2 * Math.PI;
  19483. var inversePointLength = 1.0 / ( points.length - 1 );
  19484. var inverseSegments = 1.0 / segments;
  19485. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19486. var phi = phiStart + i * inverseSegments * phiLength;
  19487. var c = Math.cos( phi ),
  19488. s = Math.sin( phi );
  19489. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19490. var pt = points[ j ];
  19491. var vertex = new THREE.Vector3();
  19492. vertex.x = c * pt.x - s * pt.y;
  19493. vertex.y = s * pt.x + c * pt.y;
  19494. vertex.z = pt.z;
  19495. this.vertices.push( vertex );
  19496. }
  19497. }
  19498. var np = points.length;
  19499. for ( var i = 0, il = segments; i < il; i ++ ) {
  19500. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19501. var base = j + np * i;
  19502. var a = base;
  19503. var b = base + np;
  19504. var c = base + 1 + np;
  19505. var d = base + 1;
  19506. var u0 = i * inverseSegments;
  19507. var v0 = j * inversePointLength;
  19508. var u1 = u0 + inverseSegments;
  19509. var v1 = v0 + inversePointLength;
  19510. this.faces.push( new THREE.Face3( a, b, d ) );
  19511. this.faceVertexUvs[ 0 ].push( [
  19512. new THREE.Vector2( u0, v0 ),
  19513. new THREE.Vector2( u1, v0 ),
  19514. new THREE.Vector2( u0, v1 )
  19515. ] );
  19516. this.faces.push( new THREE.Face3( b, c, d ) );
  19517. this.faceVertexUvs[ 0 ].push( [
  19518. new THREE.Vector2( u1, v0 ),
  19519. new THREE.Vector2( u1, v1 ),
  19520. new THREE.Vector2( u0, v1 )
  19521. ] );
  19522. }
  19523. }
  19524. this.mergeVertices();
  19525. this.computeFaceNormals();
  19526. this.computeVertexNormals();
  19527. };
  19528. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19529. /**
  19530. * @author mrdoob / http://mrdoob.com/
  19531. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19532. */
  19533. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19534. THREE.Geometry.call( this );
  19535. this.parameters = {
  19536. width: width,
  19537. height: height,
  19538. widthSegments: widthSegments,
  19539. heightSegments: heightSegments
  19540. };
  19541. var ix, iz;
  19542. var width_half = width / 2;
  19543. var height_half = height / 2;
  19544. var gridX = widthSegments || 1;
  19545. var gridZ = heightSegments || 1;
  19546. var gridX1 = gridX + 1;
  19547. var gridZ1 = gridZ + 1;
  19548. var segment_width = width / gridX;
  19549. var segment_height = height / gridZ;
  19550. var normal = new THREE.Vector3( 0, 0, 1 );
  19551. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19552. var y = iz * segment_height - height_half;
  19553. for ( ix = 0; ix < gridX1; ix ++ ) {
  19554. var x = ix * segment_width - width_half;
  19555. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19556. }
  19557. }
  19558. for ( iz = 0; iz < gridZ; iz ++ ) {
  19559. for ( ix = 0; ix < gridX; ix ++ ) {
  19560. var a = ix + gridX1 * iz;
  19561. var b = ix + gridX1 * ( iz + 1 );
  19562. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19563. var d = ( ix + 1 ) + gridX1 * iz;
  19564. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19565. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19566. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19567. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19568. var face = new THREE.Face3( a, b, d );
  19569. face.normal.copy( normal );
  19570. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19571. this.faces.push( face );
  19572. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19573. face = new THREE.Face3( b, c, d );
  19574. face.normal.copy( normal );
  19575. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19576. this.faces.push( face );
  19577. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19578. }
  19579. }
  19580. };
  19581. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19582. /**
  19583. * @author Kaleb Murphy
  19584. */
  19585. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19586. THREE.Geometry.call( this );
  19587. innerRadius = innerRadius || 0;
  19588. outerRadius = outerRadius || 50;
  19589. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19590. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19591. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19592. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19593. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19594. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19595. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19596. var vertex = new THREE.Vector3();
  19597. var segment = thetaStart + o / thetaSegments * thetaLength;
  19598. vertex.x = radius * Math.cos( segment );
  19599. vertex.y = radius * Math.sin( segment );
  19600. this.vertices.push( vertex );
  19601. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19602. }
  19603. radius += radiusStep;
  19604. }
  19605. var n = new THREE.Vector3( 0, 0, 1 );
  19606. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19607. var thetaSegment = i * thetaSegments;
  19608. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19609. var segment = o + thetaSegment;
  19610. var v1 = segment + i;
  19611. var v2 = segment + thetaSegments + i;
  19612. var v3 = segment + thetaSegments + 1 + i;
  19613. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19614. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19615. v1 = segment + i;
  19616. v2 = segment + thetaSegments + 1 + i;
  19617. v3 = segment + 1 + i;
  19618. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19619. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19620. }
  19621. }
  19622. this.computeFaceNormals();
  19623. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19624. };
  19625. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19626. /**
  19627. * @author mrdoob / http://mrdoob.com/
  19628. */
  19629. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19630. THREE.Geometry.call( this );
  19631. this.parameters = {
  19632. radius: radius,
  19633. widthSegments: widthSegments,
  19634. heightSegments: heightSegments,
  19635. phiStart: phiStart,
  19636. phiLength: phiLength,
  19637. thetaStart: thetaStart,
  19638. thetaLength: thetaLength
  19639. };
  19640. radius = radius || 50;
  19641. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19642. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19643. phiStart = phiStart !== undefined ? phiStart : 0;
  19644. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19645. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19646. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19647. var x, y, vertices = [], uvs = [];
  19648. for ( y = 0; y <= heightSegments; y ++ ) {
  19649. var verticesRow = [];
  19650. var uvsRow = [];
  19651. for ( x = 0; x <= widthSegments; x ++ ) {
  19652. var u = x / widthSegments;
  19653. var v = y / heightSegments;
  19654. var vertex = new THREE.Vector3();
  19655. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19656. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19657. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19658. this.vertices.push( vertex );
  19659. verticesRow.push( this.vertices.length - 1 );
  19660. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19661. }
  19662. vertices.push( verticesRow );
  19663. uvs.push( uvsRow );
  19664. }
  19665. for ( y = 0; y < heightSegments; y ++ ) {
  19666. for ( x = 0; x < widthSegments; x ++ ) {
  19667. var v1 = vertices[ y ][ x + 1 ];
  19668. var v2 = vertices[ y ][ x ];
  19669. var v3 = vertices[ y + 1 ][ x ];
  19670. var v4 = vertices[ y + 1 ][ x + 1 ];
  19671. var n1 = this.vertices[ v1 ].clone().normalize();
  19672. var n2 = this.vertices[ v2 ].clone().normalize();
  19673. var n3 = this.vertices[ v3 ].clone().normalize();
  19674. var n4 = this.vertices[ v4 ].clone().normalize();
  19675. var uv1 = uvs[ y ][ x + 1 ].clone();
  19676. var uv2 = uvs[ y ][ x ].clone();
  19677. var uv3 = uvs[ y + 1 ][ x ].clone();
  19678. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19679. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19680. uv1.x = ( uv1.x + uv2.x ) / 2;
  19681. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19682. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19683. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19684. uv3.x = ( uv3.x + uv4.x ) / 2;
  19685. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19686. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19687. } else {
  19688. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19689. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19690. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19691. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19692. }
  19693. }
  19694. }
  19695. this.computeFaceNormals();
  19696. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19697. };
  19698. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19699. /**
  19700. * @author zz85 / http://www.lab4games.net/zz85/blog
  19701. * @author alteredq / http://alteredqualia.com/
  19702. *
  19703. * For creating 3D text geometry in three.js
  19704. *
  19705. * Text = 3D Text
  19706. *
  19707. * parameters = {
  19708. * size: <float>, // size of the text
  19709. * height: <float>, // thickness to extrude text
  19710. * curveSegments: <int>, // number of points on the curves
  19711. *
  19712. * font: <string>, // font name
  19713. * weight: <string>, // font weight (normal, bold)
  19714. * style: <string>, // font style (normal, italics)
  19715. *
  19716. * bevelEnabled: <bool>, // turn on bevel
  19717. * bevelThickness: <float>, // how deep into text bevel goes
  19718. * bevelSize: <float>, // how far from text outline is bevel
  19719. * }
  19720. *
  19721. */
  19722. /* Usage Examples
  19723. // TextGeometry wrapper
  19724. var text3d = new TextGeometry( text, options );
  19725. // Complete manner
  19726. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19727. var text3d = new ExtrudeGeometry( textShapes, options );
  19728. */
  19729. THREE.TextGeometry = function ( text, parameters ) {
  19730. parameters = parameters || {};
  19731. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19732. // translate parameters to ExtrudeGeometry API
  19733. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19734. // defaults
  19735. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19736. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19737. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19738. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19739. };
  19740. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19741. /**
  19742. * @author oosmoxiecode
  19743. * @author mrdoob / http://mrdoob.com/
  19744. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19745. */
  19746. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19747. THREE.Geometry.call( this );
  19748. this.parameters = {
  19749. radius: radius,
  19750. tube: tube,
  19751. radialSegments: radialSegments,
  19752. tubularSegments: tubularSegments,
  19753. arc: arc
  19754. };
  19755. radius = radius || 100;
  19756. tube = tube || 40;
  19757. radialSegments = radialSegments || 8;
  19758. tubularSegments = tubularSegments || 6;
  19759. arc = arc || Math.PI * 2;
  19760. var center = new THREE.Vector3(), uvs = [], normals = [];
  19761. for ( var j = 0; j <= radialSegments; j ++ ) {
  19762. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19763. var u = i / tubularSegments * arc;
  19764. var v = j / radialSegments * Math.PI * 2;
  19765. center.x = radius * Math.cos( u );
  19766. center.y = radius * Math.sin( u );
  19767. var vertex = new THREE.Vector3();
  19768. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19769. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19770. vertex.z = tube * Math.sin( v );
  19771. this.vertices.push( vertex );
  19772. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19773. normals.push( vertex.clone().sub( center ).normalize() );
  19774. }
  19775. }
  19776. for ( var j = 1; j <= radialSegments; j ++ ) {
  19777. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19778. var a = ( tubularSegments + 1 ) * j + i - 1;
  19779. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19780. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19781. var d = ( tubularSegments + 1 ) * j + i;
  19782. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19783. this.faces.push( face );
  19784. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19785. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19786. this.faces.push( face );
  19787. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19788. }
  19789. }
  19790. this.computeFaceNormals();
  19791. };
  19792. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19793. /**
  19794. * @author oosmoxiecode
  19795. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19796. */
  19797. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19798. THREE.Geometry.call( this );
  19799. this.parameters = {
  19800. radius: radius,
  19801. tube: tube,
  19802. radialSegments: radialSegments,
  19803. tubularSegments: tubularSegments,
  19804. p: p,
  19805. q: q,
  19806. heightScale: heightScale
  19807. };
  19808. radius = radius || 100;
  19809. tube = tube || 40;
  19810. radialSegments = radialSegments || 64;
  19811. tubularSegments = tubularSegments || 8;
  19812. p = p || 2;
  19813. q = q || 3;
  19814. heightScale = heightScale || 1;
  19815. var grid = new Array( radialSegments );
  19816. var tang = new THREE.Vector3();
  19817. var n = new THREE.Vector3();
  19818. var bitan = new THREE.Vector3();
  19819. for ( var i = 0; i < radialSegments; ++ i ) {
  19820. grid[ i ] = new Array( tubularSegments );
  19821. var u = i / radialSegments * 2 * p * Math.PI;
  19822. var p1 = getPos( u, q, p, radius, heightScale );
  19823. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19824. tang.subVectors( p2, p1 );
  19825. n.addVectors( p2, p1 );
  19826. bitan.crossVectors( tang, n );
  19827. n.crossVectors( bitan, tang );
  19828. bitan.normalize();
  19829. n.normalize();
  19830. for ( var j = 0; j < tubularSegments; ++ j ) {
  19831. var v = j / tubularSegments * 2 * Math.PI;
  19832. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19833. var cy = tube * Math.sin( v );
  19834. var pos = new THREE.Vector3();
  19835. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19836. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19837. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19838. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19839. }
  19840. }
  19841. for ( var i = 0; i < radialSegments; ++ i ) {
  19842. for ( var j = 0; j < tubularSegments; ++ j ) {
  19843. var ip = ( i + 1 ) % radialSegments;
  19844. var jp = ( j + 1 ) % tubularSegments;
  19845. var a = grid[ i ][ j ];
  19846. var b = grid[ ip ][ j ];
  19847. var c = grid[ ip ][ jp ];
  19848. var d = grid[ i ][ jp ];
  19849. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19850. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19851. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19852. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19853. this.faces.push( new THREE.Face3( a, b, d ) );
  19854. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19855. this.faces.push( new THREE.Face3( b, c, d ) );
  19856. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19857. }
  19858. }
  19859. this.computeFaceNormals();
  19860. this.computeVertexNormals();
  19861. function getPos( u, in_q, in_p, radius, heightScale ) {
  19862. var cu = Math.cos( u );
  19863. var su = Math.sin( u );
  19864. var quOverP = in_q / in_p * u;
  19865. var cs = Math.cos( quOverP );
  19866. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19867. var ty = radius * ( 2 + cs ) * su * 0.5;
  19868. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19869. return new THREE.Vector3( tx, ty, tz );
  19870. }
  19871. };
  19872. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19873. /**
  19874. * @author WestLangley / https://github.com/WestLangley
  19875. * @author zz85 / https://github.com/zz85
  19876. * @author miningold / https://github.com/miningold
  19877. *
  19878. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19879. *
  19880. * Creates a tube which extrudes along a 3d spline
  19881. *
  19882. * Uses parallel transport frames as described in
  19883. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19884. */
  19885. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  19886. THREE.Geometry.call( this );
  19887. this.parameters = {
  19888. path: path,
  19889. segments: segments,
  19890. radius: radius,
  19891. radialSegments: radialSegments,
  19892. closed: closed
  19893. };
  19894. segments = segments || 64;
  19895. radius = radius || 1;
  19896. radialSegments = radialSegments || 8;
  19897. closed = closed || false;
  19898. var grid = [];
  19899. var scope = this,
  19900. tangent,
  19901. normal,
  19902. binormal,
  19903. numpoints = segments + 1,
  19904. x, y, z,
  19905. tx, ty, tz,
  19906. u, v,
  19907. cx, cy,
  19908. pos, pos2 = new THREE.Vector3(),
  19909. i, j,
  19910. ip, jp,
  19911. a, b, c, d,
  19912. uva, uvb, uvc, uvd;
  19913. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19914. tangents = frames.tangents,
  19915. normals = frames.normals,
  19916. binormals = frames.binormals;
  19917. // proxy internals
  19918. this.tangents = tangents;
  19919. this.normals = normals;
  19920. this.binormals = binormals;
  19921. function vert( x, y, z ) {
  19922. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19923. }
  19924. // consruct the grid
  19925. for ( i = 0; i < numpoints; i++ ) {
  19926. grid[ i ] = [];
  19927. u = i / ( numpoints - 1 );
  19928. pos = path.getPointAt( u );
  19929. tangent = tangents[ i ];
  19930. normal = normals[ i ];
  19931. binormal = binormals[ i ];
  19932. for ( j = 0; j < radialSegments; j++ ) {
  19933. v = j / radialSegments * 2 * Math.PI;
  19934. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19935. cy = radius * Math.sin( v );
  19936. pos2.copy( pos );
  19937. pos2.x += cx * normal.x + cy * binormal.x;
  19938. pos2.y += cx * normal.y + cy * binormal.y;
  19939. pos2.z += cx * normal.z + cy * binormal.z;
  19940. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19941. }
  19942. }
  19943. // construct the mesh
  19944. for ( i = 0; i < segments; i++ ) {
  19945. for ( j = 0; j < radialSegments; j++ ) {
  19946. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19947. jp = (j + 1) % radialSegments;
  19948. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19949. b = grid[ ip ][ j ];
  19950. c = grid[ ip ][ jp ];
  19951. d = grid[ i ][ jp ];
  19952. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19953. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19954. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19955. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19956. this.faces.push( new THREE.Face3( a, b, d ) );
  19957. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19958. this.faces.push( new THREE.Face3( b, c, d ) );
  19959. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19960. }
  19961. }
  19962. this.computeFaceNormals();
  19963. this.computeVertexNormals();
  19964. };
  19965. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19966. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19967. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19968. var tangent = new THREE.Vector3(),
  19969. normal = new THREE.Vector3(),
  19970. binormal = new THREE.Vector3(),
  19971. tangents = [],
  19972. normals = [],
  19973. binormals = [],
  19974. vec = new THREE.Vector3(),
  19975. mat = new THREE.Matrix4(),
  19976. numpoints = segments + 1,
  19977. theta,
  19978. epsilon = 0.0001,
  19979. smallest,
  19980. tx, ty, tz,
  19981. i, u, v;
  19982. // expose internals
  19983. this.tangents = tangents;
  19984. this.normals = normals;
  19985. this.binormals = binormals;
  19986. // compute the tangent vectors for each segment on the path
  19987. for ( i = 0; i < numpoints; i++ ) {
  19988. u = i / ( numpoints - 1 );
  19989. tangents[ i ] = path.getTangentAt( u );
  19990. tangents[ i ].normalize();
  19991. }
  19992. initialNormal3();
  19993. function initialNormal1(lastBinormal) {
  19994. // fixed start binormal. Has dangers of 0 vectors
  19995. normals[ 0 ] = new THREE.Vector3();
  19996. binormals[ 0 ] = new THREE.Vector3();
  19997. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19998. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19999. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20000. }
  20001. function initialNormal2() {
  20002. // This uses the Frenet-Serret formula for deriving binormal
  20003. var t2 = path.getTangentAt( epsilon );
  20004. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20005. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20006. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20007. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20008. }
  20009. function initialNormal3() {
  20010. // select an initial normal vector perpenicular to the first tangent vector,
  20011. // and in the direction of the smallest tangent xyz component
  20012. normals[ 0 ] = new THREE.Vector3();
  20013. binormals[ 0 ] = new THREE.Vector3();
  20014. smallest = Number.MAX_VALUE;
  20015. tx = Math.abs( tangents[ 0 ].x );
  20016. ty = Math.abs( tangents[ 0 ].y );
  20017. tz = Math.abs( tangents[ 0 ].z );
  20018. if ( tx <= smallest ) {
  20019. smallest = tx;
  20020. normal.set( 1, 0, 0 );
  20021. }
  20022. if ( ty <= smallest ) {
  20023. smallest = ty;
  20024. normal.set( 0, 1, 0 );
  20025. }
  20026. if ( tz <= smallest ) {
  20027. normal.set( 0, 0, 1 );
  20028. }
  20029. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20030. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20031. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20032. }
  20033. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20034. for ( i = 1; i < numpoints; i++ ) {
  20035. normals[ i ] = normals[ i-1 ].clone();
  20036. binormals[ i ] = binormals[ i-1 ].clone();
  20037. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20038. if ( vec.length() > epsilon ) {
  20039. vec.normalize();
  20040. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20041. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20042. }
  20043. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20044. }
  20045. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20046. if ( closed ) {
  20047. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20048. theta /= ( numpoints - 1 );
  20049. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20050. theta = -theta;
  20051. }
  20052. for ( i = 1; i < numpoints; i++ ) {
  20053. // twist a little...
  20054. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20055. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20056. }
  20057. }
  20058. };
  20059. /**
  20060. * @author clockworkgeek / https://github.com/clockworkgeek
  20061. * @author timothypratley / https://github.com/timothypratley
  20062. * @author WestLangley / http://github.com/WestLangley
  20063. */
  20064. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  20065. THREE.Geometry.call( this );
  20066. radius = radius || 1;
  20067. detail = detail || 0;
  20068. var that = this;
  20069. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  20070. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  20071. }
  20072. var midpoints = [], p = this.vertices;
  20073. var faces = [];
  20074. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  20075. var v1 = p[ indices[ i ] ];
  20076. var v2 = p[ indices[ i + 1 ] ];
  20077. var v3 = p[ indices[ i + 2 ] ];
  20078. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20079. }
  20080. var centroid = new THREE.Vector3();
  20081. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20082. subdivide( faces[ i ], detail );
  20083. }
  20084. // Handle case when face straddles the seam
  20085. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20086. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20087. var x0 = uvs[ 0 ].x;
  20088. var x1 = uvs[ 1 ].x;
  20089. var x2 = uvs[ 2 ].x;
  20090. var max = Math.max( x0, Math.max( x1, x2 ) );
  20091. var min = Math.min( x0, Math.min( x1, x2 ) );
  20092. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20093. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20094. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20095. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20096. }
  20097. }
  20098. // Apply radius
  20099. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20100. this.vertices[ i ].multiplyScalar( radius );
  20101. }
  20102. // Merge vertices
  20103. this.mergeVertices();
  20104. this.computeFaceNormals();
  20105. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20106. // Project vector onto sphere's surface
  20107. function prepare( vector ) {
  20108. var vertex = vector.normalize().clone();
  20109. vertex.index = that.vertices.push( vertex ) - 1;
  20110. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20111. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20112. var v = inclination( vector ) / Math.PI + 0.5;
  20113. vertex.uv = new THREE.Vector2( u, 1 - v );
  20114. return vertex;
  20115. }
  20116. // Approximate a curved face with recursively sub-divided triangles.
  20117. function make( v1, v2, v3 ) {
  20118. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20119. that.faces.push( face );
  20120. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20121. var azi = azimuth( centroid );
  20122. that.faceVertexUvs[ 0 ].push( [
  20123. correctUV( v1.uv, v1, azi ),
  20124. correctUV( v2.uv, v2, azi ),
  20125. correctUV( v3.uv, v3, azi )
  20126. ] );
  20127. }
  20128. // Analytically subdivide a face to the required detail level.
  20129. function subdivide( face, detail ) {
  20130. var cols = Math.pow(2, detail);
  20131. var cells = Math.pow(4, detail);
  20132. var a = prepare( that.vertices[ face.a ] );
  20133. var b = prepare( that.vertices[ face.b ] );
  20134. var c = prepare( that.vertices[ face.c ] );
  20135. var v = [];
  20136. // Construct all of the vertices for this subdivision.
  20137. for ( var i = 0 ; i <= cols; i ++ ) {
  20138. v[ i ] = [];
  20139. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20140. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20141. var rows = cols - i;
  20142. for ( var j = 0; j <= rows; j ++) {
  20143. if ( j == 0 && i == cols ) {
  20144. v[ i ][ j ] = aj;
  20145. } else {
  20146. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20147. }
  20148. }
  20149. }
  20150. // Construct all of the faces.
  20151. for ( var i = 0; i < cols ; i ++ ) {
  20152. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20153. var k = Math.floor( j / 2 );
  20154. if ( j % 2 == 0 ) {
  20155. make(
  20156. v[ i ][ k + 1],
  20157. v[ i + 1 ][ k ],
  20158. v[ i ][ k ]
  20159. );
  20160. } else {
  20161. make(
  20162. v[ i ][ k + 1 ],
  20163. v[ i + 1][ k + 1],
  20164. v[ i + 1 ][ k ]
  20165. );
  20166. }
  20167. }
  20168. }
  20169. }
  20170. // Angle around the Y axis, counter-clockwise when looking from above.
  20171. function azimuth( vector ) {
  20172. return Math.atan2( vector.z, -vector.x );
  20173. }
  20174. // Angle above the XZ plane.
  20175. function inclination( vector ) {
  20176. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20177. }
  20178. // Texture fixing helper. Spheres have some odd behaviours.
  20179. function correctUV( uv, vector, azimuth ) {
  20180. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20181. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20182. return uv.clone();
  20183. }
  20184. };
  20185. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20186. /**
  20187. * @author timothypratley / https://github.com/timothypratley
  20188. */
  20189. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20190. this.parameters = {
  20191. radius: radius,
  20192. detail: detail
  20193. };
  20194. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20195. var vertices = [
  20196. -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  20197. 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
  20198. t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
  20199. ];
  20200. var indices = [
  20201. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20202. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20203. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20204. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20205. ];
  20206. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20207. };
  20208. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20209. /**
  20210. * @author timothypratley / https://github.com/timothypratley
  20211. */
  20212. THREE.OctahedronGeometry = function ( radius, detail ) {
  20213. this.parameters = {
  20214. radius: radius,
  20215. detail: detail
  20216. };
  20217. var vertices = [
  20218. 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1
  20219. ];
  20220. var indices = [
  20221. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20222. ];
  20223. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20224. };
  20225. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20226. /**
  20227. * @author timothypratley / https://github.com/timothypratley
  20228. */
  20229. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20230. var vertices = [
  20231. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  20232. ];
  20233. var indices = [
  20234. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20235. ];
  20236. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20237. };
  20238. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20239. /**
  20240. * @author zz85 / https://github.com/zz85
  20241. * Parametric Surfaces Geometry
  20242. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20243. *
  20244. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20245. *
  20246. */
  20247. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20248. THREE.Geometry.call( this );
  20249. var verts = this.vertices;
  20250. var faces = this.faces;
  20251. var uvs = this.faceVertexUvs[ 0 ];
  20252. var i, il, j, p;
  20253. var u, v;
  20254. var stackCount = stacks + 1;
  20255. var sliceCount = slices + 1;
  20256. for ( i = 0; i <= stacks; i ++ ) {
  20257. v = i / stacks;
  20258. for ( j = 0; j <= slices; j ++ ) {
  20259. u = j / slices;
  20260. p = func( u, v );
  20261. verts.push( p );
  20262. }
  20263. }
  20264. var a, b, c, d;
  20265. var uva, uvb, uvc, uvd;
  20266. for ( i = 0; i < stacks; i ++ ) {
  20267. for ( j = 0; j < slices; j ++ ) {
  20268. a = i * sliceCount + j;
  20269. b = i * sliceCount + j + 1;
  20270. c = (i + 1) * sliceCount + j + 1;
  20271. d = (i + 1) * sliceCount + j;
  20272. uva = new THREE.Vector2( j / slices, i / stacks );
  20273. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20274. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20275. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20276. faces.push( new THREE.Face3( a, b, d ) );
  20277. uvs.push( [ uva, uvb, uvd ] );
  20278. faces.push( new THREE.Face3( b, c, d ) );
  20279. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20280. }
  20281. }
  20282. // console.log(this);
  20283. // magic bullet
  20284. // var diff = this.mergeVertices();
  20285. // console.log('removed ', diff, ' vertices by merging');
  20286. this.computeFaceNormals();
  20287. this.computeVertexNormals();
  20288. };
  20289. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20290. /**
  20291. * @author sroucheray / http://sroucheray.org/
  20292. * @author mrdoob / http://mrdoob.com/
  20293. */
  20294. THREE.AxisHelper = function ( size ) {
  20295. size = size || 1;
  20296. var geometry = new THREE.Geometry();
  20297. geometry.vertices.push(
  20298. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20299. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20300. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20301. );
  20302. geometry.colors.push(
  20303. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20304. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20305. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20306. );
  20307. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20308. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20309. };
  20310. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20311. /**
  20312. * @author WestLangley / http://github.com/WestLangley
  20313. * @author zz85 / http://github.com/zz85
  20314. * @author bhouston / http://exocortex.com
  20315. *
  20316. * Creates an arrow for visualizing directions
  20317. *
  20318. * Parameters:
  20319. * dir - Vector3
  20320. * origin - Vector3
  20321. * length - Number
  20322. * color - color in hex value
  20323. * headLength - Number
  20324. * headWidth - Number
  20325. */
  20326. THREE.ArrowHelper = function ( dir, origin, length, color, headLength, headWidth ) {
  20327. // dir is assumed to be normalized
  20328. THREE.Object3D.call( this );
  20329. if ( color === undefined ) color = 0xffff00;
  20330. if ( length === undefined ) length = 1;
  20331. if ( headLength === undefined ) headLength = 0.2 * length;
  20332. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20333. this.position = origin;
  20334. var lineGeometry = new THREE.Geometry();
  20335. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20336. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20337. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20338. this.line.matrixAutoUpdate = false;
  20339. this.add( this.line );
  20340. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20341. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20342. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20343. this.cone.matrixAutoUpdate = false;
  20344. this.add( this.cone );
  20345. this.setDirection( dir );
  20346. this.setLength( length, headLength, headWidth );
  20347. };
  20348. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20349. THREE.ArrowHelper.prototype.setDirection = function () {
  20350. var axis = new THREE.Vector3();
  20351. var radians;
  20352. return function ( dir ) {
  20353. // dir is assumed to be normalized
  20354. if ( dir.y > 0.99999 ) {
  20355. this.quaternion.set( 0, 0, 0, 1 );
  20356. } else if ( dir.y < - 0.99999 ) {
  20357. this.quaternion.set( 1, 0, 0, 0 );
  20358. } else {
  20359. axis.set( dir.z, 0, - dir.x ).normalize();
  20360. radians = Math.acos( dir.y );
  20361. this.quaternion.setFromAxisAngle( axis, radians );
  20362. }
  20363. };
  20364. }();
  20365. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20366. if ( headLength === undefined ) headLength = 0.2 * length;
  20367. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20368. this.line.scale.set( 1, length, 1 );
  20369. this.line.updateMatrix();
  20370. this.cone.scale.set( headWidth, headLength, headWidth );
  20371. this.cone.position.y = length;
  20372. this.cone.updateMatrix();
  20373. };
  20374. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20375. this.line.material.color.set( color );
  20376. this.cone.material.color.set( color );
  20377. };
  20378. /**
  20379. * @author mrdoob / http://mrdoob.com/
  20380. */
  20381. THREE.BoxHelper = function ( object ) {
  20382. // 5____4
  20383. // 1/___0/|
  20384. // | 6__|_7
  20385. // 2/___3/
  20386. var vertices = [
  20387. new THREE.Vector3( 1, 1, 1 ),
  20388. new THREE.Vector3( - 1, 1, 1 ),
  20389. new THREE.Vector3( - 1, - 1, 1 ),
  20390. new THREE.Vector3( 1, - 1, 1 ),
  20391. new THREE.Vector3( 1, 1, - 1 ),
  20392. new THREE.Vector3( - 1, 1, - 1 ),
  20393. new THREE.Vector3( - 1, - 1, - 1 ),
  20394. new THREE.Vector3( 1, - 1, - 1 )
  20395. ];
  20396. this.vertices = vertices;
  20397. // TODO: Wouldn't be nice if Line had .segments?
  20398. var geometry = new THREE.Geometry();
  20399. geometry.vertices.push(
  20400. vertices[ 0 ], vertices[ 1 ],
  20401. vertices[ 1 ], vertices[ 2 ],
  20402. vertices[ 2 ], vertices[ 3 ],
  20403. vertices[ 3 ], vertices[ 0 ],
  20404. vertices[ 4 ], vertices[ 5 ],
  20405. vertices[ 5 ], vertices[ 6 ],
  20406. vertices[ 6 ], vertices[ 7 ],
  20407. vertices[ 7 ], vertices[ 4 ],
  20408. vertices[ 0 ], vertices[ 4 ],
  20409. vertices[ 1 ], vertices[ 5 ],
  20410. vertices[ 2 ], vertices[ 6 ],
  20411. vertices[ 3 ], vertices[ 7 ]
  20412. );
  20413. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20414. if ( object !== undefined ) {
  20415. this.update( object );
  20416. }
  20417. };
  20418. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20419. THREE.BoxHelper.prototype.update = function ( object ) {
  20420. var geometry = object.geometry;
  20421. if ( geometry.boundingBox === null ) {
  20422. geometry.computeBoundingBox();
  20423. }
  20424. var min = geometry.boundingBox.min;
  20425. var max = geometry.boundingBox.max;
  20426. var vertices = this.vertices;
  20427. vertices[ 0 ].set( max.x, max.y, max.z );
  20428. vertices[ 1 ].set( min.x, max.y, max.z );
  20429. vertices[ 2 ].set( min.x, min.y, max.z );
  20430. vertices[ 3 ].set( max.x, min.y, max.z );
  20431. vertices[ 4 ].set( max.x, max.y, min.z );
  20432. vertices[ 5 ].set( min.x, max.y, min.z );
  20433. vertices[ 6 ].set( min.x, min.y, min.z );
  20434. vertices[ 7 ].set( max.x, min.y, min.z );
  20435. this.geometry.computeBoundingSphere();
  20436. this.geometry.verticesNeedUpdate = true;
  20437. this.matrixAutoUpdate = false;
  20438. this.matrixWorld = object.matrixWorld;
  20439. };
  20440. /**
  20441. * @author WestLangley / http://github.com/WestLangley
  20442. */
  20443. // a helper to show the world-axis-aligned bounding box for an object
  20444. THREE.BoundingBoxHelper = function ( object, hex ) {
  20445. var color = ( hex !== undefined ) ? hex : 0x888888;
  20446. this.object = object;
  20447. this.box = new THREE.Box3();
  20448. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20449. };
  20450. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20451. THREE.BoundingBoxHelper.prototype.update = function () {
  20452. this.box.setFromObject( this.object );
  20453. this.box.size( this.scale );
  20454. this.box.center( this.position );
  20455. };
  20456. /**
  20457. * @author alteredq / http://alteredqualia.com/
  20458. *
  20459. * - shows frustum, line of sight and up of the camera
  20460. * - suitable for fast updates
  20461. * - based on frustum visualization in lightgl.js shadowmap example
  20462. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20463. */
  20464. THREE.CameraHelper = function ( camera ) {
  20465. var geometry = new THREE.Geometry();
  20466. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20467. var pointMap = {};
  20468. // colors
  20469. var hexFrustum = 0xffaa00;
  20470. var hexCone = 0xff0000;
  20471. var hexUp = 0x00aaff;
  20472. var hexTarget = 0xffffff;
  20473. var hexCross = 0x333333;
  20474. // near
  20475. addLine( "n1", "n2", hexFrustum );
  20476. addLine( "n2", "n4", hexFrustum );
  20477. addLine( "n4", "n3", hexFrustum );
  20478. addLine( "n3", "n1", hexFrustum );
  20479. // far
  20480. addLine( "f1", "f2", hexFrustum );
  20481. addLine( "f2", "f4", hexFrustum );
  20482. addLine( "f4", "f3", hexFrustum );
  20483. addLine( "f3", "f1", hexFrustum );
  20484. // sides
  20485. addLine( "n1", "f1", hexFrustum );
  20486. addLine( "n2", "f2", hexFrustum );
  20487. addLine( "n3", "f3", hexFrustum );
  20488. addLine( "n4", "f4", hexFrustum );
  20489. // cone
  20490. addLine( "p", "n1", hexCone );
  20491. addLine( "p", "n2", hexCone );
  20492. addLine( "p", "n3", hexCone );
  20493. addLine( "p", "n4", hexCone );
  20494. // up
  20495. addLine( "u1", "u2", hexUp );
  20496. addLine( "u2", "u3", hexUp );
  20497. addLine( "u3", "u1", hexUp );
  20498. // target
  20499. addLine( "c", "t", hexTarget );
  20500. addLine( "p", "c", hexCross );
  20501. // cross
  20502. addLine( "cn1", "cn2", hexCross );
  20503. addLine( "cn3", "cn4", hexCross );
  20504. addLine( "cf1", "cf2", hexCross );
  20505. addLine( "cf3", "cf4", hexCross );
  20506. function addLine( a, b, hex ) {
  20507. addPoint( a, hex );
  20508. addPoint( b, hex );
  20509. }
  20510. function addPoint( id, hex ) {
  20511. geometry.vertices.push( new THREE.Vector3() );
  20512. geometry.colors.push( new THREE.Color( hex ) );
  20513. if ( pointMap[ id ] === undefined ) {
  20514. pointMap[ id ] = [];
  20515. }
  20516. pointMap[ id ].push( geometry.vertices.length - 1 );
  20517. }
  20518. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20519. this.camera = camera;
  20520. this.matrixWorld = camera.matrixWorld;
  20521. this.matrixAutoUpdate = false;
  20522. this.pointMap = pointMap;
  20523. this.update();
  20524. };
  20525. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20526. THREE.CameraHelper.prototype.update = function () {
  20527. var vector = new THREE.Vector3();
  20528. var camera = new THREE.Camera();
  20529. var projector = new THREE.Projector();
  20530. return function () {
  20531. var scope = this;
  20532. var w = 1, h = 1;
  20533. // we need just camera projection matrix
  20534. // world matrix must be identity
  20535. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20536. // center / target
  20537. setPoint( "c", 0, 0, -1 );
  20538. setPoint( "t", 0, 0, 1 );
  20539. // near
  20540. setPoint( "n1", -w, -h, -1 );
  20541. setPoint( "n2", w, -h, -1 );
  20542. setPoint( "n3", -w, h, -1 );
  20543. setPoint( "n4", w, h, -1 );
  20544. // far
  20545. setPoint( "f1", -w, -h, 1 );
  20546. setPoint( "f2", w, -h, 1 );
  20547. setPoint( "f3", -w, h, 1 );
  20548. setPoint( "f4", w, h, 1 );
  20549. // up
  20550. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20551. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20552. setPoint( "u3", 0, h * 2, -1 );
  20553. // cross
  20554. setPoint( "cf1", -w, 0, 1 );
  20555. setPoint( "cf2", w, 0, 1 );
  20556. setPoint( "cf3", 0, -h, 1 );
  20557. setPoint( "cf4", 0, h, 1 );
  20558. setPoint( "cn1", -w, 0, -1 );
  20559. setPoint( "cn2", w, 0, -1 );
  20560. setPoint( "cn3", 0, -h, -1 );
  20561. setPoint( "cn4", 0, h, -1 );
  20562. function setPoint( point, x, y, z ) {
  20563. vector.set( x, y, z );
  20564. projector.unprojectVector( vector, camera );
  20565. var points = scope.pointMap[ point ];
  20566. if ( points !== undefined ) {
  20567. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20568. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20569. }
  20570. }
  20571. }
  20572. this.geometry.verticesNeedUpdate = true;
  20573. };
  20574. }();
  20575. /**
  20576. * @author alteredq / http://alteredqualia.com/
  20577. * @author mrdoob / http://mrdoob.com/
  20578. * @author WestLangley / http://github.com/WestLangley
  20579. */
  20580. THREE.DirectionalLightHelper = function ( light, size ) {
  20581. THREE.Object3D.call( this );
  20582. this.light = light;
  20583. this.light.updateMatrixWorld();
  20584. this.matrixWorld = light.matrixWorld;
  20585. this.matrixAutoUpdate = false;
  20586. size = size || 1;
  20587. var geometry = new THREE.Geometry();
  20588. geometry.vertices.push(
  20589. new THREE.Vector3( - size, size, 0 ),
  20590. new THREE.Vector3( size, size, 0 ),
  20591. new THREE.Vector3( size, - size, 0 ),
  20592. new THREE.Vector3( - size, - size, 0 ),
  20593. new THREE.Vector3( - size, size, 0 )
  20594. );
  20595. var material = new THREE.LineBasicMaterial( { fog: false } );
  20596. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20597. this.lightPlane = new THREE.Line( geometry, material );
  20598. this.add( this.lightPlane );
  20599. geometry = new THREE.Geometry();
  20600. geometry.vertices.push(
  20601. new THREE.Vector3(),
  20602. new THREE.Vector3()
  20603. );
  20604. material = new THREE.LineBasicMaterial( { fog: false } );
  20605. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20606. this.targetLine = new THREE.Line( geometry, material );
  20607. this.add( this.targetLine );
  20608. this.update();
  20609. };
  20610. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20611. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20612. this.lightPlane.geometry.dispose();
  20613. this.lightPlane.material.dispose();
  20614. this.targetLine.geometry.dispose();
  20615. this.targetLine.material.dispose();
  20616. };
  20617. THREE.DirectionalLightHelper.prototype.update = function () {
  20618. var v1 = new THREE.Vector3();
  20619. var v2 = new THREE.Vector3();
  20620. var v3 = new THREE.Vector3();
  20621. return function () {
  20622. v1.setFromMatrixPosition( this.light.matrixWorld );
  20623. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20624. v3.subVectors( v2, v1 );
  20625. this.lightPlane.lookAt( v3 );
  20626. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20627. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20628. this.targetLine.geometry.verticesNeedUpdate = true;
  20629. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20630. }
  20631. }();
  20632. /**
  20633. * @author WestLangley / http://github.com/WestLangley
  20634. */
  20635. THREE.EdgesHelper = function ( object, hex ) {
  20636. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20637. var edge = [ 0, 0 ], hash = {};
  20638. var sortFunction = function ( a, b ) { return a - b };
  20639. var keys = [ 'a', 'b', 'c' ];
  20640. var geometry = new THREE.BufferGeometry();
  20641. var geometry2 = object.geometry.clone();
  20642. geometry2.mergeVertices();
  20643. geometry2.computeFaceNormals();
  20644. var vertices = geometry2.vertices;
  20645. var faces = geometry2.faces;
  20646. var numEdges = 0;
  20647. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20648. var face = faces[ i ];
  20649. for ( var j = 0; j < 3; j ++ ) {
  20650. edge[ 0 ] = face[ keys[ j ] ];
  20651. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20652. edge.sort( sortFunction );
  20653. var key = edge.toString();
  20654. if ( hash[ key ] === undefined ) {
  20655. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20656. numEdges ++;
  20657. } else {
  20658. hash[ key ].face2 = i;
  20659. }
  20660. }
  20661. }
  20662. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  20663. var coords = geometry.attributes.position.array;
  20664. var index = 0;
  20665. for ( var key in hash ) {
  20666. var h = hash[ key ];
  20667. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20668. var vertex = vertices[ h.vert1 ];
  20669. coords[ index ++ ] = vertex.x;
  20670. coords[ index ++ ] = vertex.y;
  20671. coords[ index ++ ] = vertex.z;
  20672. vertex = vertices[ h.vert2 ];
  20673. coords[ index ++ ] = vertex.x;
  20674. coords[ index ++ ] = vertex.y;
  20675. coords[ index ++ ] = vertex.z;
  20676. }
  20677. }
  20678. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20679. this.matrixAutoUpdate = false;
  20680. this.matrixWorld = object.matrixWorld;
  20681. };
  20682. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20683. /**
  20684. * @author mrdoob / http://mrdoob.com/
  20685. * @author WestLangley / http://github.com/WestLangley
  20686. */
  20687. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20688. this.object = object;
  20689. this.size = ( size !== undefined ) ? size : 1;
  20690. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20691. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20692. var geometry = new THREE.Geometry();
  20693. var faces = this.object.geometry.faces;
  20694. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20695. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20696. }
  20697. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20698. this.matrixAutoUpdate = false;
  20699. this.normalMatrix = new THREE.Matrix3();
  20700. this.update();
  20701. };
  20702. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20703. THREE.FaceNormalsHelper.prototype.update = function () {
  20704. var vertices = this.geometry.vertices;
  20705. var object = this.object;
  20706. var objectVertices = object.geometry.vertices;
  20707. var objectFaces = object.geometry.faces;
  20708. var objectWorldMatrix = object.matrixWorld;
  20709. object.updateMatrixWorld( true );
  20710. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20711. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20712. var face = objectFaces[ i ];
  20713. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20714. .add( objectVertices[ face.b ] )
  20715. .add( objectVertices[ face.c ] )
  20716. .divideScalar( 3 )
  20717. .applyMatrix4( objectWorldMatrix );
  20718. vertices[ i2 + 1 ].copy( face.normal )
  20719. .applyMatrix3( this.normalMatrix )
  20720. .normalize()
  20721. .multiplyScalar( this.size )
  20722. .add( vertices[ i2 ] );
  20723. }
  20724. this.geometry.verticesNeedUpdate = true;
  20725. return this;
  20726. };
  20727. /**
  20728. * @author mrdoob / http://mrdoob.com/
  20729. */
  20730. THREE.GridHelper = function ( size, step ) {
  20731. var geometry = new THREE.Geometry();
  20732. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20733. this.color1 = new THREE.Color( 0x444444 );
  20734. this.color2 = new THREE.Color( 0x888888 );
  20735. for ( var i = - size; i <= size; i += step ) {
  20736. geometry.vertices.push(
  20737. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20738. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20739. );
  20740. var color = i === 0 ? this.color1 : this.color2;
  20741. geometry.colors.push( color, color, color, color );
  20742. }
  20743. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20744. };
  20745. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20746. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20747. this.color1.set( colorCenterLine );
  20748. this.color2.set( colorGrid );
  20749. this.geometry.colorsNeedUpdate = true;
  20750. }
  20751. /**
  20752. * @author alteredq / http://alteredqualia.com/
  20753. * @author mrdoob / http://mrdoob.com/
  20754. */
  20755. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20756. THREE.Object3D.call( this );
  20757. this.light = light;
  20758. this.light.updateMatrixWorld();
  20759. this.matrixWorld = light.matrixWorld;
  20760. this.matrixAutoUpdate = false;
  20761. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20762. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20763. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20764. for ( var i = 0, il = 8; i < il; i ++ ) {
  20765. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20766. }
  20767. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20768. this.lightSphere = new THREE.Mesh( geometry, material );
  20769. this.add( this.lightSphere );
  20770. this.update();
  20771. };
  20772. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20773. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20774. this.lightSphere.geometry.dispose();
  20775. this.lightSphere.material.dispose();
  20776. };
  20777. THREE.HemisphereLightHelper.prototype.update = function () {
  20778. var vector = new THREE.Vector3();
  20779. return function () {
  20780. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20781. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20782. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20783. this.lightSphere.geometry.colorsNeedUpdate = true;
  20784. }
  20785. }();
  20786. /**
  20787. * @author alteredq / http://alteredqualia.com/
  20788. * @author mrdoob / http://mrdoob.com/
  20789. */
  20790. THREE.PointLightHelper = function ( light, sphereSize ) {
  20791. this.light = light;
  20792. this.light.updateMatrixWorld();
  20793. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20794. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20795. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20796. THREE.Mesh.call( this, geometry, material );
  20797. this.matrixWorld = this.light.matrixWorld;
  20798. this.matrixAutoUpdate = false;
  20799. /*
  20800. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20801. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20802. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20803. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20804. var d = light.distance;
  20805. if ( d === 0.0 ) {
  20806. this.lightDistance.visible = false;
  20807. } else {
  20808. this.lightDistance.scale.set( d, d, d );
  20809. }
  20810. this.add( this.lightDistance );
  20811. */
  20812. };
  20813. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20814. THREE.PointLightHelper.prototype.dispose = function () {
  20815. this.geometry.dispose();
  20816. this.material.dispose();
  20817. };
  20818. THREE.PointLightHelper.prototype.update = function () {
  20819. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20820. /*
  20821. var d = this.light.distance;
  20822. if ( d === 0.0 ) {
  20823. this.lightDistance.visible = false;
  20824. } else {
  20825. this.lightDistance.visible = true;
  20826. this.lightDistance.scale.set( d, d, d );
  20827. }
  20828. */
  20829. };
  20830. /**
  20831. * @author Sean Griffin / http://twitter.com/sgrif
  20832. * @author Michael Guerrero / http://realitymeltdown.com
  20833. * @author mrdoob / http://mrdoob.com/
  20834. */
  20835. THREE.SkeletonHelper = function ( object ) {
  20836. var skeleton = object.skeleton;
  20837. var geometry = new THREE.Geometry();
  20838. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  20839. var bone = skeleton.bones[ i ];
  20840. if ( bone.parent instanceof THREE.Bone ) {
  20841. geometry.vertices.push( new THREE.Vector3() );
  20842. geometry.vertices.push( new THREE.Vector3() );
  20843. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20844. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20845. }
  20846. }
  20847. var material = new THREE.LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, transparent: true } );
  20848. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20849. this.skeleton = skeleton;
  20850. this.matrixWorld = object.matrixWorld;
  20851. this.matrixAutoUpdate = false;
  20852. this.update();
  20853. };
  20854. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20855. THREE.SkeletonHelper.prototype.update = function () {
  20856. var geometry = this.geometry;
  20857. var j = 0;
  20858. for ( var i = 0; i < this.skeleton.bones.length; i ++ ) {
  20859. var bone = this.skeleton.bones[ i ];
  20860. if ( bone.parent instanceof THREE.Bone ) {
  20861. geometry.vertices[ j ].setFromMatrixPosition( bone.skinMatrix );
  20862. geometry.vertices[ j + 1 ].setFromMatrixPosition( bone.parent.skinMatrix );
  20863. j += 2;
  20864. }
  20865. }
  20866. geometry.verticesNeedUpdate = true;
  20867. geometry.computeBoundingSphere();
  20868. };
  20869. /**
  20870. * @author alteredq / http://alteredqualia.com/
  20871. * @author mrdoob / http://mrdoob.com/
  20872. * @author WestLangley / http://github.com/WestLangley
  20873. */
  20874. THREE.SpotLightHelper = function ( light ) {
  20875. THREE.Object3D.call( this );
  20876. this.light = light;
  20877. this.light.updateMatrixWorld();
  20878. this.matrixWorld = light.matrixWorld;
  20879. this.matrixAutoUpdate = false;
  20880. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20881. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20882. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20883. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20884. this.cone = new THREE.Mesh( geometry, material );
  20885. this.add( this.cone );
  20886. this.update();
  20887. };
  20888. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20889. THREE.SpotLightHelper.prototype.dispose = function () {
  20890. this.cone.geometry.dispose();
  20891. this.cone.material.dispose();
  20892. };
  20893. THREE.SpotLightHelper.prototype.update = function () {
  20894. var vector = new THREE.Vector3();
  20895. var vector2 = new THREE.Vector3();
  20896. return function () {
  20897. var coneLength = this.light.distance ? this.light.distance : 10000;
  20898. var coneWidth = coneLength * Math.tan( this.light.angle );
  20899. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20900. vector.setFromMatrixPosition( this.light.matrixWorld );
  20901. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20902. this.cone.lookAt( vector2.sub( vector ) );
  20903. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20904. };
  20905. }();
  20906. /**
  20907. * @author mrdoob / http://mrdoob.com/
  20908. * @author WestLangley / http://github.com/WestLangley
  20909. */
  20910. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20911. this.object = object;
  20912. this.size = ( size !== undefined ) ? size : 1;
  20913. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20914. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20915. var geometry = new THREE.Geometry();
  20916. var vertices = object.geometry.vertices;
  20917. var faces = object.geometry.faces;
  20918. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20919. var face = faces[ i ];
  20920. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20921. geometry.vertices.push( new THREE.Vector3() );
  20922. geometry.vertices.push( new THREE.Vector3() );
  20923. }
  20924. }
  20925. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20926. this.matrixAutoUpdate = false;
  20927. this.normalMatrix = new THREE.Matrix3();
  20928. this.update();
  20929. };
  20930. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20931. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20932. var v1 = new THREE.Vector3();
  20933. return function( object ) {
  20934. var keys = [ 'a', 'b', 'c', 'd' ];
  20935. this.object.updateMatrixWorld( true );
  20936. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20937. var vertices = this.geometry.vertices;
  20938. var verts = this.object.geometry.vertices;
  20939. var faces = this.object.geometry.faces;
  20940. var worldMatrix = this.object.matrixWorld;
  20941. var idx = 0;
  20942. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20943. var face = faces[ i ];
  20944. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20945. var vertexId = face[ keys[ j ] ];
  20946. var vertex = verts[ vertexId ];
  20947. var normal = face.vertexNormals[ j ];
  20948. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20949. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20950. v1.add( vertices[ idx ] );
  20951. idx = idx + 1;
  20952. vertices[ idx ].copy( v1 );
  20953. idx = idx + 1;
  20954. }
  20955. }
  20956. this.geometry.verticesNeedUpdate = true;
  20957. return this;
  20958. }
  20959. }());
  20960. /**
  20961. * @author mrdoob / http://mrdoob.com/
  20962. * @author WestLangley / http://github.com/WestLangley
  20963. */
  20964. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20965. this.object = object;
  20966. this.size = ( size !== undefined ) ? size : 1;
  20967. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20968. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20969. var geometry = new THREE.Geometry();
  20970. var vertices = object.geometry.vertices;
  20971. var faces = object.geometry.faces;
  20972. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20973. var face = faces[ i ];
  20974. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20975. geometry.vertices.push( new THREE.Vector3() );
  20976. geometry.vertices.push( new THREE.Vector3() );
  20977. }
  20978. }
  20979. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20980. this.matrixAutoUpdate = false;
  20981. this.update();
  20982. };
  20983. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20984. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20985. var v1 = new THREE.Vector3();
  20986. return function( object ) {
  20987. var keys = [ 'a', 'b', 'c', 'd' ];
  20988. this.object.updateMatrixWorld( true );
  20989. var vertices = this.geometry.vertices;
  20990. var verts = this.object.geometry.vertices;
  20991. var faces = this.object.geometry.faces;
  20992. var worldMatrix = this.object.matrixWorld;
  20993. var idx = 0;
  20994. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20995. var face = faces[ i ];
  20996. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20997. var vertexId = face[ keys[ j ] ];
  20998. var vertex = verts[ vertexId ];
  20999. var tangent = face.vertexTangents[ j ];
  21000. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21001. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21002. v1.add( vertices[ idx ] );
  21003. idx = idx + 1;
  21004. vertices[ idx ].copy( v1 );
  21005. idx = idx + 1;
  21006. }
  21007. }
  21008. this.geometry.verticesNeedUpdate = true;
  21009. return this;
  21010. }
  21011. }());
  21012. /**
  21013. * @author mrdoob / http://mrdoob.com/
  21014. */
  21015. THREE.WireframeHelper = function ( object, hex ) {
  21016. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21017. var edge = [ 0, 0 ], hash = {};
  21018. var sortFunction = function ( a, b ) { return a - b };
  21019. var keys = [ 'a', 'b', 'c' ];
  21020. var geometry = new THREE.BufferGeometry();
  21021. if ( object.geometry instanceof THREE.Geometry ) {
  21022. var vertices = object.geometry.vertices;
  21023. var faces = object.geometry.faces;
  21024. var numEdges = 0;
  21025. // allocate maximal size
  21026. var edges = new Uint32Array( 6 * faces.length );
  21027. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21028. var face = faces[ i ];
  21029. for ( var j = 0; j < 3; j ++ ) {
  21030. edge[ 0 ] = face[ keys[ j ] ];
  21031. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21032. edge.sort( sortFunction );
  21033. var key = edge.toString();
  21034. if ( hash[ key ] === undefined ) {
  21035. edges[ 2 * numEdges ] = edge[ 0 ];
  21036. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21037. hash[ key ] = true;
  21038. numEdges ++;
  21039. }
  21040. }
  21041. }
  21042. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  21043. var coords = geometry.attributes.position.array;
  21044. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21045. for ( var j = 0; j < 2; j ++ ) {
  21046. var vertex = vertices[ edges [ 2 * i + j] ];
  21047. var index = 6 * i + 3 * j;
  21048. coords[ index + 0 ] = vertex.x;
  21049. coords[ index + 1 ] = vertex.y;
  21050. coords[ index + 2 ] = vertex.z;
  21051. }
  21052. }
  21053. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21054. var vertices = object.geometry.attributes.position.array;
  21055. var indices = object.geometry.attributes.index.array;
  21056. var offsets = object.geometry.offsets;
  21057. var numEdges = 0;
  21058. // allocate maximal size
  21059. var edges = new Uint32Array( 2 * indices.length );
  21060. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21061. var start = offsets[ o ].start;
  21062. var count = offsets[ o ].count;
  21063. var index = offsets[ o ].index;
  21064. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21065. for ( var j = 0; j < 3; j ++ ) {
  21066. edge[ 0 ] = index + indices[ i + j ];
  21067. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21068. edge.sort( sortFunction );
  21069. var key = edge.toString();
  21070. if ( hash[ key ] === undefined ) {
  21071. edges[ 2 * numEdges ] = edge[ 0 ];
  21072. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21073. hash[ key ] = true;
  21074. numEdges ++;
  21075. }
  21076. }
  21077. }
  21078. }
  21079. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  21080. var coords = geometry.attributes.position.array;
  21081. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21082. for ( var j = 0; j < 2; j ++ ) {
  21083. var index = 6 * i + 3 * j;
  21084. var index2 = 3 * edges[ 2 * i + j];
  21085. coords[ index + 0 ] = vertices[ index2 ];
  21086. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21087. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21088. }
  21089. }
  21090. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21091. var vertices = object.geometry.attributes.position.array;
  21092. var numEdges = vertices.length / 3;
  21093. var numTris = numEdges / 3;
  21094. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  21095. var coords = geometry.attributes.position.array;
  21096. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21097. for ( var j = 0; j < 3; j ++ ) {
  21098. var index = 18 * i + 6 * j;
  21099. var index1 = 9 * i + 3 * j;
  21100. coords[ index + 0 ] = vertices[ index1 ];
  21101. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21102. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21103. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21104. coords[ index + 3 ] = vertices[ index2 ];
  21105. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21106. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21107. }
  21108. }
  21109. }
  21110. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21111. this.matrixAutoUpdate = false;
  21112. this.matrixWorld = object.matrixWorld;
  21113. };
  21114. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21115. /**
  21116. * @author alteredq / http://alteredqualia.com/
  21117. */
  21118. THREE.ImmediateRenderObject = function () {
  21119. THREE.Object3D.call( this );
  21120. this.render = function ( renderCallback ) { };
  21121. };
  21122. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21123. /**
  21124. * @author mikael emtinger / http://gomo.se/
  21125. * @author alteredq / http://alteredqualia.com/
  21126. */
  21127. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21128. THREE.Object3D.call( this );
  21129. this.lensFlares = [];
  21130. this.positionScreen = new THREE.Vector3();
  21131. this.customUpdateCallback = undefined;
  21132. if( texture !== undefined ) {
  21133. this.add( texture, size, distance, blending, color );
  21134. }
  21135. };
  21136. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21137. /*
  21138. * Add: adds another flare
  21139. */
  21140. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21141. if( size === undefined ) size = -1;
  21142. if( distance === undefined ) distance = 0;
  21143. if( opacity === undefined ) opacity = 1;
  21144. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21145. if( blending === undefined ) blending = THREE.NormalBlending;
  21146. distance = Math.min( distance, Math.max( 0, distance ) );
  21147. this.lensFlares.push( { texture: texture, // THREE.Texture
  21148. size: size, // size in pixels (-1 = use texture.width)
  21149. distance: distance, // distance (0-1) from light source (0=at light source)
  21150. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21151. scale: 1, // scale
  21152. rotation: 1, // rotation
  21153. opacity: opacity, // opacity
  21154. color: color, // color
  21155. blending: blending } ); // blending
  21156. };
  21157. /*
  21158. * Update lens flares update positions on all flares based on the screen position
  21159. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21160. */
  21161. THREE.LensFlare.prototype.updateLensFlares = function () {
  21162. var f, fl = this.lensFlares.length;
  21163. var flare;
  21164. var vecX = -this.positionScreen.x * 2;
  21165. var vecY = -this.positionScreen.y * 2;
  21166. for( f = 0; f < fl; f ++ ) {
  21167. flare = this.lensFlares[ f ];
  21168. flare.x = this.positionScreen.x + vecX * flare.distance;
  21169. flare.y = this.positionScreen.y + vecY * flare.distance;
  21170. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21171. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21172. }
  21173. };
  21174. /**
  21175. * @author alteredq / http://alteredqualia.com/
  21176. */
  21177. THREE.MorphBlendMesh = function( geometry, material ) {
  21178. THREE.Mesh.call( this, geometry, material );
  21179. this.animationsMap = {};
  21180. this.animationsList = [];
  21181. // prepare default animation
  21182. // (all frames played together in 1 second)
  21183. var numFrames = this.geometry.morphTargets.length;
  21184. var name = "__default";
  21185. var startFrame = 0;
  21186. var endFrame = numFrames - 1;
  21187. var fps = numFrames / 1;
  21188. this.createAnimation( name, startFrame, endFrame, fps );
  21189. this.setAnimationWeight( name, 1 );
  21190. };
  21191. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21192. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21193. var animation = {
  21194. startFrame: start,
  21195. endFrame: end,
  21196. length: end - start + 1,
  21197. fps: fps,
  21198. duration: ( end - start ) / fps,
  21199. lastFrame: 0,
  21200. currentFrame: 0,
  21201. active: false,
  21202. time: 0,
  21203. direction: 1,
  21204. weight: 1,
  21205. directionBackwards: false,
  21206. mirroredLoop: false
  21207. };
  21208. this.animationsMap[ name ] = animation;
  21209. this.animationsList.push( animation );
  21210. };
  21211. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21212. var pattern = /([a-z]+)(\d+)/;
  21213. var firstAnimation, frameRanges = {};
  21214. var geometry = this.geometry;
  21215. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21216. var morph = geometry.morphTargets[ i ];
  21217. var chunks = morph.name.match( pattern );
  21218. if ( chunks && chunks.length > 1 ) {
  21219. var name = chunks[ 1 ];
  21220. var num = chunks[ 2 ];
  21221. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21222. var range = frameRanges[ name ];
  21223. if ( i < range.start ) range.start = i;
  21224. if ( i > range.end ) range.end = i;
  21225. if ( ! firstAnimation ) firstAnimation = name;
  21226. }
  21227. }
  21228. for ( var name in frameRanges ) {
  21229. var range = frameRanges[ name ];
  21230. this.createAnimation( name, range.start, range.end, fps );
  21231. }
  21232. this.firstAnimation = firstAnimation;
  21233. };
  21234. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21235. var animation = this.animationsMap[ name ];
  21236. if ( animation ) {
  21237. animation.direction = 1;
  21238. animation.directionBackwards = false;
  21239. }
  21240. };
  21241. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21242. var animation = this.animationsMap[ name ];
  21243. if ( animation ) {
  21244. animation.direction = -1;
  21245. animation.directionBackwards = true;
  21246. }
  21247. };
  21248. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21249. var animation = this.animationsMap[ name ];
  21250. if ( animation ) {
  21251. animation.fps = fps;
  21252. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21253. }
  21254. };
  21255. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21256. var animation = this.animationsMap[ name ];
  21257. if ( animation ) {
  21258. animation.duration = duration;
  21259. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21260. }
  21261. };
  21262. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21263. var animation = this.animationsMap[ name ];
  21264. if ( animation ) {
  21265. animation.weight = weight;
  21266. }
  21267. };
  21268. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21269. var animation = this.animationsMap[ name ];
  21270. if ( animation ) {
  21271. animation.time = time;
  21272. }
  21273. };
  21274. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21275. var time = 0;
  21276. var animation = this.animationsMap[ name ];
  21277. if ( animation ) {
  21278. time = animation.time;
  21279. }
  21280. return time;
  21281. };
  21282. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21283. var duration = -1;
  21284. var animation = this.animationsMap[ name ];
  21285. if ( animation ) {
  21286. duration = animation.duration;
  21287. }
  21288. return duration;
  21289. };
  21290. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21291. var animation = this.animationsMap[ name ];
  21292. if ( animation ) {
  21293. animation.time = 0;
  21294. animation.active = true;
  21295. } else {
  21296. console.warn( "animation[" + name + "] undefined" );
  21297. }
  21298. };
  21299. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21300. var animation = this.animationsMap[ name ];
  21301. if ( animation ) {
  21302. animation.active = false;
  21303. }
  21304. };
  21305. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21306. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21307. var animation = this.animationsList[ i ];
  21308. if ( ! animation.active ) continue;
  21309. var frameTime = animation.duration / animation.length;
  21310. animation.time += animation.direction * delta;
  21311. if ( animation.mirroredLoop ) {
  21312. if ( animation.time > animation.duration || animation.time < 0 ) {
  21313. animation.direction *= -1;
  21314. if ( animation.time > animation.duration ) {
  21315. animation.time = animation.duration;
  21316. animation.directionBackwards = true;
  21317. }
  21318. if ( animation.time < 0 ) {
  21319. animation.time = 0;
  21320. animation.directionBackwards = false;
  21321. }
  21322. }
  21323. } else {
  21324. animation.time = animation.time % animation.duration;
  21325. if ( animation.time < 0 ) animation.time += animation.duration;
  21326. }
  21327. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21328. var weight = animation.weight;
  21329. if ( keyframe !== animation.currentFrame ) {
  21330. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21331. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21332. this.morphTargetInfluences[ keyframe ] = 0;
  21333. animation.lastFrame = animation.currentFrame;
  21334. animation.currentFrame = keyframe;
  21335. }
  21336. var mix = ( animation.time % frameTime ) / frameTime;
  21337. if ( animation.directionBackwards ) mix = 1 - mix;
  21338. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21339. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21340. }
  21341. };
  21342. /**
  21343. * @author mikael emtinger / http://gomo.se/
  21344. * @author alteredq / http://alteredqualia.com/
  21345. */
  21346. THREE.LensFlarePlugin = function () {
  21347. var _gl, _renderer, _precision, _lensFlare = {};
  21348. this.init = function ( renderer ) {
  21349. _gl = renderer.context;
  21350. _renderer = renderer;
  21351. _precision = renderer.getPrecision();
  21352. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21353. _lensFlare.faces = new Uint16Array( 6 );
  21354. var i = 0;
  21355. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21356. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21357. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21358. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21359. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21360. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21361. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21362. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21363. i = 0;
  21364. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21365. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21366. // buffers
  21367. _lensFlare.vertexBuffer = _gl.createBuffer();
  21368. _lensFlare.elementBuffer = _gl.createBuffer();
  21369. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21370. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21371. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21372. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21373. // textures
  21374. _lensFlare.tempTexture = _gl.createTexture();
  21375. _lensFlare.occlusionTexture = _gl.createTexture();
  21376. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21377. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21378. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21379. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21380. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21381. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21382. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21383. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21384. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21385. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21386. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21387. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21388. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21389. _lensFlare.hasVertexTexture = false;
  21390. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21391. } else {
  21392. _lensFlare.hasVertexTexture = true;
  21393. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21394. }
  21395. _lensFlare.attributes = {};
  21396. _lensFlare.uniforms = {};
  21397. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21398. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21399. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21400. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21401. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21402. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21403. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21404. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21405. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21406. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21407. };
  21408. /*
  21409. * Render lens flares
  21410. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21411. * reads these back and calculates occlusion.
  21412. * Then _lensFlare.update_lensFlares() is called to re-position and
  21413. * update transparency of flares. Then they are rendered.
  21414. *
  21415. */
  21416. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21417. var flares = scene.__webglFlares,
  21418. nFlares = flares.length;
  21419. if ( ! nFlares ) return;
  21420. var tempPosition = new THREE.Vector3();
  21421. var invAspect = viewportHeight / viewportWidth,
  21422. halfViewportWidth = viewportWidth * 0.5,
  21423. halfViewportHeight = viewportHeight * 0.5;
  21424. var size = 16 / viewportHeight,
  21425. scale = new THREE.Vector2( size * invAspect, size );
  21426. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21427. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21428. var uniforms = _lensFlare.uniforms,
  21429. attributes = _lensFlare.attributes;
  21430. // set _lensFlare program and reset blending
  21431. _gl.useProgram( _lensFlare.program );
  21432. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21433. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21434. // loop through all lens flares to update their occlusion and positions
  21435. // setup gl and common used attribs/unforms
  21436. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21437. _gl.uniform1i( uniforms.map, 1 );
  21438. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21439. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21440. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21441. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21442. _gl.disable( _gl.CULL_FACE );
  21443. _gl.depthMask( false );
  21444. var i, j, jl, flare, sprite;
  21445. for ( i = 0; i < nFlares; i ++ ) {
  21446. size = 16 / viewportHeight;
  21447. scale.set( size * invAspect, size );
  21448. // calc object screen position
  21449. flare = flares[ i ];
  21450. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21451. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21452. tempPosition.applyProjection( camera.projectionMatrix );
  21453. // setup arrays for gl programs
  21454. screenPosition.copy( tempPosition )
  21455. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21456. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21457. // screen cull
  21458. if ( _lensFlare.hasVertexTexture || (
  21459. screenPositionPixels.x > 0 &&
  21460. screenPositionPixels.x < viewportWidth &&
  21461. screenPositionPixels.y > 0 &&
  21462. screenPositionPixels.y < viewportHeight ) ) {
  21463. // save current RGB to temp texture
  21464. _gl.activeTexture( _gl.TEXTURE1 );
  21465. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21466. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21467. // render pink quad
  21468. _gl.uniform1i( uniforms.renderType, 0 );
  21469. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21470. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21471. _gl.disable( _gl.BLEND );
  21472. _gl.enable( _gl.DEPTH_TEST );
  21473. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21474. // copy result to occlusionMap
  21475. _gl.activeTexture( _gl.TEXTURE0 );
  21476. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21477. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21478. // restore graphics
  21479. _gl.uniform1i( uniforms.renderType, 1 );
  21480. _gl.disable( _gl.DEPTH_TEST );
  21481. _gl.activeTexture( _gl.TEXTURE1 );
  21482. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21483. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21484. // update object positions
  21485. flare.positionScreen.copy( screenPosition )
  21486. if ( flare.customUpdateCallback ) {
  21487. flare.customUpdateCallback( flare );
  21488. } else {
  21489. flare.updateLensFlares();
  21490. }
  21491. // render flares
  21492. _gl.uniform1i( uniforms.renderType, 2 );
  21493. _gl.enable( _gl.BLEND );
  21494. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21495. sprite = flare.lensFlares[ j ];
  21496. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21497. screenPosition.x = sprite.x;
  21498. screenPosition.y = sprite.y;
  21499. screenPosition.z = sprite.z;
  21500. size = sprite.size * sprite.scale / viewportHeight;
  21501. scale.x = size * invAspect;
  21502. scale.y = size;
  21503. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21504. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21505. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21506. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21507. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21508. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21509. _renderer.setTexture( sprite.texture, 1 );
  21510. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21511. }
  21512. }
  21513. }
  21514. }
  21515. // restore gl
  21516. _gl.enable( _gl.CULL_FACE );
  21517. _gl.enable( _gl.DEPTH_TEST );
  21518. _gl.depthMask( true );
  21519. };
  21520. function createProgram ( shader, precision ) {
  21521. var program = _gl.createProgram();
  21522. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21523. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21524. var prefix = "precision " + precision + " float;\n";
  21525. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21526. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21527. _gl.compileShader( fragmentShader );
  21528. _gl.compileShader( vertexShader );
  21529. _gl.attachShader( program, fragmentShader );
  21530. _gl.attachShader( program, vertexShader );
  21531. _gl.linkProgram( program );
  21532. return program;
  21533. };
  21534. };
  21535. /**
  21536. * @author alteredq / http://alteredqualia.com/
  21537. */
  21538. THREE.ShadowMapPlugin = function () {
  21539. var _gl,
  21540. _renderer,
  21541. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21542. _frustum = new THREE.Frustum(),
  21543. _projScreenMatrix = new THREE.Matrix4(),
  21544. _min = new THREE.Vector3(),
  21545. _max = new THREE.Vector3(),
  21546. _matrixPosition = new THREE.Vector3();
  21547. this.init = function ( renderer ) {
  21548. _gl = renderer.context;
  21549. _renderer = renderer;
  21550. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21551. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21552. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21553. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21554. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21555. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21556. _depthMaterial._shadowPass = true;
  21557. _depthMaterialMorph._shadowPass = true;
  21558. _depthMaterialSkin._shadowPass = true;
  21559. _depthMaterialMorphSkin._shadowPass = true;
  21560. };
  21561. this.render = function ( scene, camera ) {
  21562. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21563. this.update( scene, camera );
  21564. };
  21565. this.update = function ( scene, camera ) {
  21566. var i, il, j, jl, n,
  21567. shadowMap, shadowMatrix, shadowCamera,
  21568. program, buffer, material,
  21569. webglObject, object, light,
  21570. renderList,
  21571. lights = [],
  21572. k = 0,
  21573. fog = null;
  21574. // set GL state for depth map
  21575. _gl.clearColor( 1, 1, 1, 1 );
  21576. _gl.disable( _gl.BLEND );
  21577. _gl.enable( _gl.CULL_FACE );
  21578. _gl.frontFace( _gl.CCW );
  21579. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21580. _gl.cullFace( _gl.FRONT );
  21581. } else {
  21582. _gl.cullFace( _gl.BACK );
  21583. }
  21584. _renderer.setDepthTest( true );
  21585. // preprocess lights
  21586. // - skip lights that are not casting shadows
  21587. // - create virtual lights for cascaded shadow maps
  21588. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21589. light = scene.__lights[ i ];
  21590. if ( ! light.castShadow ) continue;
  21591. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21592. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21593. var virtualLight;
  21594. if ( ! light.shadowCascadeArray[ n ] ) {
  21595. virtualLight = createVirtualLight( light, n );
  21596. virtualLight.originalCamera = camera;
  21597. var gyro = new THREE.Gyroscope();
  21598. gyro.position.copy( light.shadowCascadeOffset );
  21599. gyro.add( virtualLight );
  21600. gyro.add( virtualLight.target );
  21601. camera.add( gyro );
  21602. light.shadowCascadeArray[ n ] = virtualLight;
  21603. console.log( "Created virtualLight", virtualLight );
  21604. } else {
  21605. virtualLight = light.shadowCascadeArray[ n ];
  21606. }
  21607. updateVirtualLight( light, n );
  21608. lights[ k ] = virtualLight;
  21609. k ++;
  21610. }
  21611. } else {
  21612. lights[ k ] = light;
  21613. k ++;
  21614. }
  21615. }
  21616. // render depth map
  21617. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21618. light = lights[ i ];
  21619. if ( ! light.shadowMap ) {
  21620. var shadowFilter = THREE.LinearFilter;
  21621. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21622. shadowFilter = THREE.NearestFilter;
  21623. }
  21624. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21625. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21626. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21627. light.shadowMatrix = new THREE.Matrix4();
  21628. }
  21629. if ( ! light.shadowCamera ) {
  21630. if ( light instanceof THREE.SpotLight ) {
  21631. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21632. } else if ( light instanceof THREE.DirectionalLight ) {
  21633. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21634. } else {
  21635. console.error( "Unsupported light type for shadow" );
  21636. continue;
  21637. }
  21638. scene.add( light.shadowCamera );
  21639. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21640. }
  21641. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21642. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21643. light.shadowCamera.add( light.cameraHelper );
  21644. }
  21645. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21646. updateShadowCamera( camera, light );
  21647. }
  21648. shadowMap = light.shadowMap;
  21649. shadowMatrix = light.shadowMatrix;
  21650. shadowCamera = light.shadowCamera;
  21651. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21652. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21653. shadowCamera.lookAt( _matrixPosition );
  21654. shadowCamera.updateMatrixWorld();
  21655. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21656. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21657. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21658. // compute shadow matrix
  21659. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21660. 0.0, 0.5, 0.0, 0.5,
  21661. 0.0, 0.0, 0.5, 0.5,
  21662. 0.0, 0.0, 0.0, 1.0 );
  21663. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21664. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21665. // update camera matrices and frustum
  21666. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21667. _frustum.setFromMatrix( _projScreenMatrix );
  21668. // render shadow map
  21669. _renderer.setRenderTarget( shadowMap );
  21670. _renderer.clear();
  21671. // set object matrices & frustum culling
  21672. renderList = scene.__webglObjects;
  21673. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21674. webglObject = renderList[ j ];
  21675. object = webglObject.object;
  21676. webglObject.render = false;
  21677. if ( object.visible && object.castShadow ) {
  21678. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  21679. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21680. webglObject.render = true;
  21681. }
  21682. }
  21683. }
  21684. // render regular objects
  21685. var objectMaterial, useMorphing, useSkinning;
  21686. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21687. webglObject = renderList[ j ];
  21688. if ( webglObject.render ) {
  21689. object = webglObject.object;
  21690. buffer = webglObject.buffer;
  21691. // culling is overriden globally for all objects
  21692. // while rendering depth map
  21693. // need to deal with MeshFaceMaterial somehow
  21694. // in that case just use the first of material.materials for now
  21695. // (proper solution would require to break objects by materials
  21696. // similarly to regular rendering and then set corresponding
  21697. // depth materials per each chunk instead of just once per object)
  21698. objectMaterial = getObjectMaterial( object );
  21699. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21700. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21701. if ( object.customDepthMaterial ) {
  21702. material = object.customDepthMaterial;
  21703. } else if ( useSkinning ) {
  21704. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21705. } else if ( useMorphing ) {
  21706. material = _depthMaterialMorph;
  21707. } else {
  21708. material = _depthMaterial;
  21709. }
  21710. _renderer.setMaterialFaces( objectMaterial );
  21711. if ( buffer instanceof THREE.BufferGeometry ) {
  21712. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21713. } else {
  21714. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21715. }
  21716. }
  21717. }
  21718. // set matrices and render immediate objects
  21719. renderList = scene.__webglObjectsImmediate;
  21720. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21721. webglObject = renderList[ j ];
  21722. object = webglObject.object;
  21723. if ( object.visible && object.castShadow ) {
  21724. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21725. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21726. }
  21727. }
  21728. }
  21729. // restore GL state
  21730. var clearColor = _renderer.getClearColor(),
  21731. clearAlpha = _renderer.getClearAlpha();
  21732. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21733. _gl.enable( _gl.BLEND );
  21734. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21735. _gl.cullFace( _gl.BACK );
  21736. }
  21737. };
  21738. function createVirtualLight( light, cascade ) {
  21739. var virtualLight = new THREE.DirectionalLight();
  21740. virtualLight.isVirtual = true;
  21741. virtualLight.onlyShadow = true;
  21742. virtualLight.castShadow = true;
  21743. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21744. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21745. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21746. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21747. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21748. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21749. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21750. virtualLight.shadowDarkness = light.shadowDarkness;
  21751. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21752. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21753. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21754. virtualLight.pointsWorld = [];
  21755. virtualLight.pointsFrustum = [];
  21756. var pointsWorld = virtualLight.pointsWorld,
  21757. pointsFrustum = virtualLight.pointsFrustum;
  21758. for ( var i = 0; i < 8; i ++ ) {
  21759. pointsWorld[ i ] = new THREE.Vector3();
  21760. pointsFrustum[ i ] = new THREE.Vector3();
  21761. }
  21762. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21763. var farZ = light.shadowCascadeFarZ[ cascade ];
  21764. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21765. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21766. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21767. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21768. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21769. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21770. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21771. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21772. return virtualLight;
  21773. }
  21774. // Synchronize virtual light with the original light
  21775. function updateVirtualLight( light, cascade ) {
  21776. var virtualLight = light.shadowCascadeArray[ cascade ];
  21777. virtualLight.position.copy( light.position );
  21778. virtualLight.target.position.copy( light.target.position );
  21779. virtualLight.lookAt( virtualLight.target );
  21780. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21781. virtualLight.shadowDarkness = light.shadowDarkness;
  21782. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21783. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21784. var farZ = light.shadowCascadeFarZ[ cascade ];
  21785. var pointsFrustum = virtualLight.pointsFrustum;
  21786. pointsFrustum[ 0 ].z = nearZ;
  21787. pointsFrustum[ 1 ].z = nearZ;
  21788. pointsFrustum[ 2 ].z = nearZ;
  21789. pointsFrustum[ 3 ].z = nearZ;
  21790. pointsFrustum[ 4 ].z = farZ;
  21791. pointsFrustum[ 5 ].z = farZ;
  21792. pointsFrustum[ 6 ].z = farZ;
  21793. pointsFrustum[ 7 ].z = farZ;
  21794. }
  21795. // Fit shadow camera's ortho frustum to camera frustum
  21796. function updateShadowCamera( camera, light ) {
  21797. var shadowCamera = light.shadowCamera,
  21798. pointsFrustum = light.pointsFrustum,
  21799. pointsWorld = light.pointsWorld;
  21800. _min.set( Infinity, Infinity, Infinity );
  21801. _max.set( -Infinity, -Infinity, -Infinity );
  21802. for ( var i = 0; i < 8; i ++ ) {
  21803. var p = pointsWorld[ i ];
  21804. p.copy( pointsFrustum[ i ] );
  21805. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21806. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21807. if ( p.x < _min.x ) _min.x = p.x;
  21808. if ( p.x > _max.x ) _max.x = p.x;
  21809. if ( p.y < _min.y ) _min.y = p.y;
  21810. if ( p.y > _max.y ) _max.y = p.y;
  21811. if ( p.z < _min.z ) _min.z = p.z;
  21812. if ( p.z > _max.z ) _max.z = p.z;
  21813. }
  21814. shadowCamera.left = _min.x;
  21815. shadowCamera.right = _max.x;
  21816. shadowCamera.top = _max.y;
  21817. shadowCamera.bottom = _min.y;
  21818. // can't really fit near/far
  21819. //shadowCamera.near = _min.z;
  21820. //shadowCamera.far = _max.z;
  21821. shadowCamera.updateProjectionMatrix();
  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 for shadow maps
  21825. function getObjectMaterial( object ) {
  21826. return object.material instanceof THREE.MeshFaceMaterial
  21827. ? object.material.materials[ 0 ]
  21828. : object.material;
  21829. };
  21830. };
  21831. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21832. /**
  21833. * @author mikael emtinger / http://gomo.se/
  21834. * @author alteredq / http://alteredqualia.com/
  21835. */
  21836. THREE.SpritePlugin = function () {
  21837. var _gl, _renderer, _texture;
  21838. var vertices, faces, vertexBuffer, elementBuffer;
  21839. var program, attributes, uniforms;
  21840. this.init = function ( renderer ) {
  21841. _gl = renderer.context;
  21842. _renderer = renderer;
  21843. vertices = new Float32Array( [
  21844. - 0.5, - 0.5, 0, 0,
  21845. 0.5, - 0.5, 1, 0,
  21846. 0.5, 0.5, 1, 1,
  21847. - 0.5, 0.5, 0, 1
  21848. ] );
  21849. faces = new Uint16Array( [
  21850. 0, 1, 2,
  21851. 0, 2, 3
  21852. ] );
  21853. vertexBuffer = _gl.createBuffer();
  21854. elementBuffer = _gl.createBuffer();
  21855. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21856. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21857. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21858. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21859. program = createProgram();
  21860. attributes = {
  21861. position: _gl.getAttribLocation ( program, 'position' ),
  21862. uv: _gl.getAttribLocation ( program, 'uv' )
  21863. };
  21864. uniforms = {
  21865. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21866. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21867. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21868. scale: _gl.getUniformLocation( program, 'scale' ),
  21869. color: _gl.getUniformLocation( program, 'color' ),
  21870. map: _gl.getUniformLocation( program, 'map' ),
  21871. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21872. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21873. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21874. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21875. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21876. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21877. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21878. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21879. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21880. };
  21881. var canvas = document.createElement( 'canvas' );
  21882. canvas.width = 8;
  21883. canvas.height = 8;
  21884. var context = canvas.getContext( '2d' );
  21885. context.fillStyle = '#ffffff';
  21886. context.fillRect( 0, 0, canvas.width, canvas.height );
  21887. _texture = new THREE.Texture( canvas );
  21888. _texture.needsUpdate = true;
  21889. };
  21890. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21891. var sprites = scene.__webglSprites,
  21892. nSprites = sprites.length;
  21893. if ( ! nSprites ) return;
  21894. // setup gl
  21895. _gl.useProgram( program );
  21896. _gl.enableVertexAttribArray( attributes.position );
  21897. _gl.enableVertexAttribArray( attributes.uv );
  21898. _gl.disable( _gl.CULL_FACE );
  21899. _gl.enable( _gl.BLEND );
  21900. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21901. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21902. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21903. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21904. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21905. _gl.activeTexture( _gl.TEXTURE0 );
  21906. _gl.uniform1i( uniforms.map, 0 );
  21907. var oldFogType = 0;
  21908. var sceneFogType = 0;
  21909. var fog = scene.fog;
  21910. if ( fog ) {
  21911. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21912. if ( fog instanceof THREE.Fog ) {
  21913. _gl.uniform1f( uniforms.fogNear, fog.near );
  21914. _gl.uniform1f( uniforms.fogFar, fog.far );
  21915. _gl.uniform1i( uniforms.fogType, 1 );
  21916. oldFogType = 1;
  21917. sceneFogType = 1;
  21918. } else if ( fog instanceof THREE.FogExp2 ) {
  21919. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21920. _gl.uniform1i( uniforms.fogType, 2 );
  21921. oldFogType = 2;
  21922. sceneFogType = 2;
  21923. }
  21924. } else {
  21925. _gl.uniform1i( uniforms.fogType, 0 );
  21926. oldFogType = 0;
  21927. sceneFogType = 0;
  21928. }
  21929. // update positions and sort
  21930. var i, sprite, material, fogType, scale = [];
  21931. for( i = 0; i < nSprites; i ++ ) {
  21932. sprite = sprites[ i ];
  21933. material = sprite.material;
  21934. if ( sprite.visible === false ) continue;
  21935. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21936. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21937. }
  21938. sprites.sort( painterSortStable );
  21939. // render all sprites
  21940. for( i = 0; i < nSprites; i ++ ) {
  21941. sprite = sprites[ i ];
  21942. if ( sprite.visible === false ) continue;
  21943. material = sprite.material;
  21944. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21945. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21946. scale[ 0 ] = sprite.scale.x;
  21947. scale[ 1 ] = sprite.scale.y;
  21948. if ( scene.fog && material.fog ) {
  21949. fogType = sceneFogType;
  21950. } else {
  21951. fogType = 0;
  21952. }
  21953. if ( oldFogType !== fogType ) {
  21954. _gl.uniform1i( uniforms.fogType, fogType );
  21955. oldFogType = fogType;
  21956. }
  21957. if ( material.map !== null ) {
  21958. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  21959. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  21960. } else {
  21961. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  21962. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  21963. }
  21964. _gl.uniform1f( uniforms.opacity, material.opacity );
  21965. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21966. _gl.uniform1f( uniforms.rotation, material.rotation );
  21967. _gl.uniform2fv( uniforms.scale, scale );
  21968. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21969. _renderer.setDepthTest( material.depthTest );
  21970. _renderer.setDepthWrite( material.depthWrite );
  21971. if ( material.map && material.map.image && material.map.image.width ) {
  21972. _renderer.setTexture( material.map, 0 );
  21973. } else {
  21974. _renderer.setTexture( _texture, 0 );
  21975. }
  21976. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21977. }
  21978. // restore gl
  21979. _gl.enable( _gl.CULL_FACE );
  21980. };
  21981. function createProgram () {
  21982. var program = _gl.createProgram();
  21983. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21984. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21985. _gl.shaderSource( vertexShader, [
  21986. 'precision ' + _renderer.getPrecision() + ' float;',
  21987. 'uniform mat4 modelViewMatrix;',
  21988. 'uniform mat4 projectionMatrix;',
  21989. 'uniform float rotation;',
  21990. 'uniform vec2 scale;',
  21991. 'uniform vec2 uvOffset;',
  21992. 'uniform vec2 uvScale;',
  21993. 'attribute vec2 position;',
  21994. 'attribute vec2 uv;',
  21995. 'varying vec2 vUV;',
  21996. 'void main() {',
  21997. 'vUV = uvOffset + uv * uvScale;',
  21998. 'vec2 alignedPosition = position * scale;',
  21999. 'vec2 rotatedPosition;',
  22000. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22001. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22002. 'vec4 finalPosition;',
  22003. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22004. 'finalPosition.xy += rotatedPosition;',
  22005. 'finalPosition = projectionMatrix * finalPosition;',
  22006. 'gl_Position = finalPosition;',
  22007. '}'
  22008. ].join( '\n' ) );
  22009. _gl.shaderSource( fragmentShader, [
  22010. 'precision ' + _renderer.getPrecision() + ' float;',
  22011. 'uniform vec3 color;',
  22012. 'uniform sampler2D map;',
  22013. 'uniform float opacity;',
  22014. 'uniform int fogType;',
  22015. 'uniform vec3 fogColor;',
  22016. 'uniform float fogDensity;',
  22017. 'uniform float fogNear;',
  22018. 'uniform float fogFar;',
  22019. 'uniform float alphaTest;',
  22020. 'varying vec2 vUV;',
  22021. 'void main() {',
  22022. 'vec4 texture = texture2D( map, vUV );',
  22023. 'if ( texture.a < alphaTest ) discard;',
  22024. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22025. 'if ( fogType > 0 ) {',
  22026. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22027. 'float fogFactor = 0.0;',
  22028. 'if ( fogType == 1 ) {',
  22029. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22030. '} else {',
  22031. 'const float LOG2 = 1.442695;',
  22032. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22033. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22034. '}',
  22035. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22036. '}',
  22037. '}'
  22038. ].join( '\n' ) );
  22039. _gl.compileShader( vertexShader );
  22040. _gl.compileShader( fragmentShader );
  22041. _gl.attachShader( program, vertexShader );
  22042. _gl.attachShader( program, fragmentShader );
  22043. _gl.linkProgram( program );
  22044. return program;
  22045. };
  22046. function painterSortStable ( a, b ) {
  22047. if ( a.z !== b.z ) {
  22048. return b.z - a.z;
  22049. } else {
  22050. return b.id - a.id;
  22051. }
  22052. };
  22053. };
  22054. /**
  22055. * @author alteredq / http://alteredqualia.com/
  22056. */
  22057. THREE.DepthPassPlugin = function () {
  22058. this.enabled = false;
  22059. this.renderTarget = null;
  22060. var _gl,
  22061. _renderer,
  22062. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22063. _frustum = new THREE.Frustum(),
  22064. _projScreenMatrix = new THREE.Matrix4();
  22065. this.init = function ( renderer ) {
  22066. _gl = renderer.context;
  22067. _renderer = renderer;
  22068. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22069. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22070. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22071. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22072. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22073. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22074. _depthMaterial._shadowPass = true;
  22075. _depthMaterialMorph._shadowPass = true;
  22076. _depthMaterialSkin._shadowPass = true;
  22077. _depthMaterialMorphSkin._shadowPass = true;
  22078. };
  22079. this.render = function ( scene, camera ) {
  22080. if ( ! this.enabled ) return;
  22081. this.update( scene, camera );
  22082. };
  22083. this.update = function ( scene, camera ) {
  22084. var i, il, j, jl, n,
  22085. program, buffer, material,
  22086. webglObject, object, light,
  22087. renderList,
  22088. fog = null;
  22089. // set GL state for depth map
  22090. _gl.clearColor( 1, 1, 1, 1 );
  22091. _gl.disable( _gl.BLEND );
  22092. _renderer.setDepthTest( true );
  22093. // update scene
  22094. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22095. // update camera matrices and frustum
  22096. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22097. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22098. _frustum.setFromMatrix( _projScreenMatrix );
  22099. // render depth map
  22100. _renderer.setRenderTarget( this.renderTarget );
  22101. _renderer.clear();
  22102. // set object matrices & frustum culling
  22103. renderList = scene.__webglObjects;
  22104. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22105. webglObject = renderList[ j ];
  22106. object = webglObject.object;
  22107. webglObject.render = false;
  22108. if ( object.visible ) {
  22109. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  22110. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22111. webglObject.render = true;
  22112. }
  22113. }
  22114. }
  22115. // render regular objects
  22116. var objectMaterial, useMorphing, useSkinning;
  22117. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22118. webglObject = renderList[ j ];
  22119. if ( webglObject.render ) {
  22120. object = webglObject.object;
  22121. buffer = webglObject.buffer;
  22122. // todo: create proper depth material for particles
  22123. if ( object instanceof THREE.PointCloud && !object.customDepthMaterial ) continue;
  22124. objectMaterial = getObjectMaterial( object );
  22125. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22126. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22127. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22128. if ( object.customDepthMaterial ) {
  22129. material = object.customDepthMaterial;
  22130. } else if ( useSkinning ) {
  22131. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22132. } else if ( useMorphing ) {
  22133. material = _depthMaterialMorph;
  22134. } else {
  22135. material = _depthMaterial;
  22136. }
  22137. if ( buffer instanceof THREE.BufferGeometry ) {
  22138. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22139. } else {
  22140. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22141. }
  22142. }
  22143. }
  22144. // set matrices and render immediate objects
  22145. renderList = scene.__webglObjectsImmediate;
  22146. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22147. webglObject = renderList[ j ];
  22148. object = webglObject.object;
  22149. if ( object.visible ) {
  22150. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22151. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22152. }
  22153. }
  22154. // restore GL state
  22155. var clearColor = _renderer.getClearColor(),
  22156. clearAlpha = _renderer.getClearAlpha();
  22157. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22158. _gl.enable( _gl.BLEND );
  22159. };
  22160. // For the moment just ignore objects that have multiple materials with different animation methods
  22161. // Only the first material will be taken into account for deciding which depth material to use
  22162. function getObjectMaterial( object ) {
  22163. return object.material instanceof THREE.MeshFaceMaterial
  22164. ? object.material.materials[ 0 ]
  22165. : object.material;
  22166. };
  22167. };
  22168. /**
  22169. * @author mikael emtinger / http://gomo.se/
  22170. */
  22171. THREE.ShaderFlares = {
  22172. 'lensFlareVertexTexture': {
  22173. vertexShader: [
  22174. "uniform lowp int renderType;",
  22175. "uniform vec3 screenPosition;",
  22176. "uniform vec2 scale;",
  22177. "uniform float rotation;",
  22178. "uniform sampler2D occlusionMap;",
  22179. "attribute vec2 position;",
  22180. "attribute vec2 uv;",
  22181. "varying vec2 vUV;",
  22182. "varying float vVisibility;",
  22183. "void main() {",
  22184. "vUV = uv;",
  22185. "vec2 pos = position;",
  22186. "if( renderType == 2 ) {",
  22187. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22188. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22189. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22190. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22191. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22192. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22193. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22194. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22195. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22196. "vVisibility = visibility.r / 9.0;",
  22197. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22198. "vVisibility *= visibility.b / 9.0;",
  22199. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22200. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22201. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22202. "}",
  22203. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22204. "}"
  22205. ].join( "\n" ),
  22206. fragmentShader: [
  22207. "uniform lowp int renderType;",
  22208. "uniform sampler2D map;",
  22209. "uniform float opacity;",
  22210. "uniform vec3 color;",
  22211. "varying vec2 vUV;",
  22212. "varying float vVisibility;",
  22213. "void main() {",
  22214. // pink square
  22215. "if( renderType == 0 ) {",
  22216. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22217. // restore
  22218. "} else if( renderType == 1 ) {",
  22219. "gl_FragColor = texture2D( map, vUV );",
  22220. // flare
  22221. "} else {",
  22222. "vec4 texture = texture2D( map, vUV );",
  22223. "texture.a *= opacity * vVisibility;",
  22224. "gl_FragColor = texture;",
  22225. "gl_FragColor.rgb *= color;",
  22226. "}",
  22227. "}"
  22228. ].join( "\n" )
  22229. },
  22230. 'lensFlare': {
  22231. vertexShader: [
  22232. "uniform lowp int renderType;",
  22233. "uniform vec3 screenPosition;",
  22234. "uniform vec2 scale;",
  22235. "uniform float rotation;",
  22236. "attribute vec2 position;",
  22237. "attribute vec2 uv;",
  22238. "varying vec2 vUV;",
  22239. "void main() {",
  22240. "vUV = uv;",
  22241. "vec2 pos = position;",
  22242. "if( renderType == 2 ) {",
  22243. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22244. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22245. "}",
  22246. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22247. "}"
  22248. ].join( "\n" ),
  22249. fragmentShader: [
  22250. "precision mediump float;",
  22251. "uniform lowp int renderType;",
  22252. "uniform sampler2D map;",
  22253. "uniform sampler2D occlusionMap;",
  22254. "uniform float opacity;",
  22255. "uniform vec3 color;",
  22256. "varying vec2 vUV;",
  22257. "void main() {",
  22258. // pink square
  22259. "if( renderType == 0 ) {",
  22260. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22261. // restore
  22262. "} else if( renderType == 1 ) {",
  22263. "gl_FragColor = texture2D( map, vUV );",
  22264. // flare
  22265. "} else {",
  22266. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22267. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22268. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22269. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22270. "visibility = ( 1.0 - visibility / 4.0 );",
  22271. "vec4 texture = texture2D( map, vUV );",
  22272. "texture.a *= opacity * visibility;",
  22273. "gl_FragColor = texture;",
  22274. "gl_FragColor.rgb *= color;",
  22275. "}",
  22276. "}"
  22277. ].join( "\n" )
  22278. }
  22279. };
粤ICP备19079148号