three.js 855 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405
  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: '67dev' };
  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. },
  2165. setFromPoints: function ( points ) {
  2166. if ( points.length > 0 ) {
  2167. var point = points[ 0 ];
  2168. this.min.copy( point );
  2169. this.max.copy( point );
  2170. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2171. this.addPoint( points[ i ] )
  2172. }
  2173. } else {
  2174. this.makeEmpty();
  2175. }
  2176. return this;
  2177. },
  2178. setFromCenterAndSize: function() {
  2179. var v1 = new THREE.Vector3();
  2180. return function ( center, size ) {
  2181. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2182. this.min.copy( center ).sub( halfSize );
  2183. this.max.copy( center ).add( halfSize );
  2184. return this;
  2185. };
  2186. }(),
  2187. setFromObject: function() {
  2188. // Computes the world-axis-aligned bounding box of an object (including its children),
  2189. // accounting for both the object's, and childrens', world transforms
  2190. var v1 = new THREE.Vector3();
  2191. return function( object ) {
  2192. var scope = this;
  2193. object.updateMatrixWorld( true );
  2194. this.makeEmpty();
  2195. object.traverse( function ( node ) {
  2196. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2197. var vertices = node.geometry.vertices;
  2198. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2199. v1.copy( vertices[ i ] );
  2200. v1.applyMatrix4( node.matrixWorld );
  2201. scope.expandByPoint( v1 );
  2202. }
  2203. }
  2204. } );
  2205. return this;
  2206. };
  2207. }(),
  2208. copy: function ( box ) {
  2209. this.min.copy( box.min );
  2210. this.max.copy( box.max );
  2211. return this;
  2212. },
  2213. makeEmpty: function () {
  2214. this.min.x = this.min.y = this.min.z = Infinity;
  2215. this.max.x = this.max.y = this.max.z = -Infinity;
  2216. return this;
  2217. },
  2218. empty: function () {
  2219. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2220. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2221. },
  2222. center: function ( optionalTarget ) {
  2223. var result = optionalTarget || new THREE.Vector3();
  2224. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2225. },
  2226. size: function ( optionalTarget ) {
  2227. var result = optionalTarget || new THREE.Vector3();
  2228. return result.subVectors( this.max, this.min );
  2229. },
  2230. expandByPoint: function ( point ) {
  2231. this.min.min( point );
  2232. this.max.max( point );
  2233. return this;
  2234. },
  2235. expandByVector: function ( vector ) {
  2236. this.min.sub( vector );
  2237. this.max.add( vector );
  2238. return this;
  2239. },
  2240. expandByScalar: function ( scalar ) {
  2241. this.min.addScalar( -scalar );
  2242. this.max.addScalar( scalar );
  2243. return this;
  2244. },
  2245. containsPoint: function ( point ) {
  2246. if ( point.x < this.min.x || point.x > this.max.x ||
  2247. point.y < this.min.y || point.y > this.max.y ||
  2248. point.z < this.min.z || point.z > this.max.z ) {
  2249. return false;
  2250. }
  2251. return true;
  2252. },
  2253. containsBox: function ( box ) {
  2254. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2255. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2256. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2257. return true;
  2258. }
  2259. return false;
  2260. },
  2261. getParameter: function ( point, optionalTarget ) {
  2262. // This can potentially have a divide by zero if the box
  2263. // has a size dimension of 0.
  2264. var result = optionalTarget || new THREE.Vector3();
  2265. return result.set(
  2266. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2267. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2268. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2269. );
  2270. },
  2271. isIntersectionBox: function ( box ) {
  2272. // using 6 splitting planes to rule out intersections.
  2273. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2274. box.max.y < this.min.y || box.min.y > this.max.y ||
  2275. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2276. return false;
  2277. }
  2278. return true;
  2279. },
  2280. clampPoint: function ( point, optionalTarget ) {
  2281. var result = optionalTarget || new THREE.Vector3();
  2282. return result.copy( point ).clamp( this.min, this.max );
  2283. },
  2284. distanceToPoint: function() {
  2285. var v1 = new THREE.Vector3();
  2286. return function ( point ) {
  2287. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2288. return clampedPoint.sub( point ).length();
  2289. };
  2290. }(),
  2291. getBoundingSphere: function() {
  2292. var v1 = new THREE.Vector3();
  2293. return function ( optionalTarget ) {
  2294. var result = optionalTarget || new THREE.Sphere();
  2295. result.center = this.center();
  2296. result.radius = this.size( v1 ).length() * 0.5;
  2297. return result;
  2298. };
  2299. }(),
  2300. intersect: function ( box ) {
  2301. this.min.max( box.min );
  2302. this.max.min( box.max );
  2303. return this;
  2304. },
  2305. union: function ( box ) {
  2306. this.min.min( box.min );
  2307. this.max.max( box.max );
  2308. return this;
  2309. },
  2310. applyMatrix4: function() {
  2311. var points = [
  2312. new THREE.Vector3(),
  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. ];
  2321. return function ( matrix ) {
  2322. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2323. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2324. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2325. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2326. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2327. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2328. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2329. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2330. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2331. this.makeEmpty();
  2332. this.setFromPoints( points );
  2333. return this;
  2334. };
  2335. }(),
  2336. translate: function ( offset ) {
  2337. this.min.add( offset );
  2338. this.max.add( offset );
  2339. return this;
  2340. },
  2341. equals: function ( box ) {
  2342. return box.min.equals( this.min ) && box.max.equals( this.max );
  2343. },
  2344. clone: function () {
  2345. return new THREE.Box3().copy( this );
  2346. }
  2347. };
  2348. /**
  2349. * @author alteredq / http://alteredqualia.com/
  2350. * @author WestLangley / http://github.com/WestLangley
  2351. * @author bhouston / http://exocortex.com
  2352. */
  2353. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2354. this.elements = new Float32Array( 9 );
  2355. var te = this.elements;
  2356. te[0] = ( n11 !== undefined ) ? n11 : 1; te[3] = n12 || 0; te[6] = n13 || 0;
  2357. te[1] = n21 || 0; te[4] = ( n22 !== undefined ) ? n22 : 1; te[7] = n23 || 0;
  2358. te[2] = n31 || 0; te[5] = n32 || 0; te[8] = ( n33 !== undefined ) ? n33 : 1;
  2359. };
  2360. THREE.Matrix3.prototype = {
  2361. constructor: THREE.Matrix3,
  2362. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2363. var te = this.elements;
  2364. te[0] = n11; te[3] = n12; te[6] = n13;
  2365. te[1] = n21; te[4] = n22; te[7] = n23;
  2366. te[2] = n31; te[5] = n32; te[8] = n33;
  2367. return this;
  2368. },
  2369. identity: function () {
  2370. this.set(
  2371. 1, 0, 0,
  2372. 0, 1, 0,
  2373. 0, 0, 1
  2374. );
  2375. return this;
  2376. },
  2377. copy: function ( m ) {
  2378. var me = m.elements;
  2379. this.set(
  2380. me[0], me[3], me[6],
  2381. me[1], me[4], me[7],
  2382. me[2], me[5], me[8]
  2383. );
  2384. return this;
  2385. },
  2386. multiplyVector3: function ( vector ) {
  2387. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2388. return vector.applyMatrix3( this );
  2389. },
  2390. multiplyVector3Array: function ( a ) {
  2391. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2392. return this.applyToVector3Array( a );
  2393. },
  2394. applyToVector3Array: function() {
  2395. var v1 = new THREE.Vector3();
  2396. return function ( a ) {
  2397. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2398. v1.x = a[ i ];
  2399. v1.y = a[ i + 1 ];
  2400. v1.z = a[ i + 2 ];
  2401. v1.applyMatrix3( this );
  2402. a[ i ] = v1.x;
  2403. a[ i + 1 ] = v1.y;
  2404. a[ i + 2 ] = v1.z;
  2405. }
  2406. return a;
  2407. };
  2408. }(),
  2409. multiplyScalar: function ( s ) {
  2410. var te = this.elements;
  2411. te[0] *= s; te[3] *= s; te[6] *= s;
  2412. te[1] *= s; te[4] *= s; te[7] *= s;
  2413. te[2] *= s; te[5] *= s; te[8] *= s;
  2414. return this;
  2415. },
  2416. determinant: function () {
  2417. var te = this.elements;
  2418. var a = te[0], b = te[1], c = te[2],
  2419. d = te[3], e = te[4], f = te[5],
  2420. g = te[6], h = te[7], i = te[8];
  2421. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2422. },
  2423. getInverse: function ( matrix, throwOnInvertible ) {
  2424. // input: THREE.Matrix4
  2425. // ( based on http://code.google.com/p/webgl-mjs/ )
  2426. var me = matrix.elements;
  2427. var te = this.elements;
  2428. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2429. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2430. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2431. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2432. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2433. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2434. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2435. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2436. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2437. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2438. // no inverse
  2439. if ( det === 0 ) {
  2440. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2441. if ( throwOnInvertible || false ) {
  2442. throw new Error( msg );
  2443. } else {
  2444. console.warn( msg );
  2445. }
  2446. this.identity();
  2447. return this;
  2448. }
  2449. this.multiplyScalar( 1.0 / det );
  2450. return this;
  2451. },
  2452. transpose: function () {
  2453. var tmp, m = this.elements;
  2454. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2455. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2456. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2457. return this;
  2458. },
  2459. flattenToArrayOffset: function( array, offset ) {
  2460. var te = this.elements;
  2461. array[ offset ] = te[0];
  2462. array[ offset + 1 ] = te[1];
  2463. array[ offset + 2 ] = te[2];
  2464. array[ offset + 3 ] = te[3];
  2465. array[ offset + 4 ] = te[4];
  2466. array[ offset + 5 ] = te[5];
  2467. array[ offset + 6 ] = te[6];
  2468. array[ offset + 7 ] = te[7];
  2469. array[ offset + 8 ] = te[8];
  2470. return array;
  2471. },
  2472. getNormalMatrix: function ( m ) {
  2473. // input: THREE.Matrix4
  2474. this.getInverse( m ).transpose();
  2475. return this;
  2476. },
  2477. transposeIntoArray: function ( r ) {
  2478. var m = this.elements;
  2479. r[ 0 ] = m[ 0 ];
  2480. r[ 1 ] = m[ 3 ];
  2481. r[ 2 ] = m[ 6 ];
  2482. r[ 3 ] = m[ 1 ];
  2483. r[ 4 ] = m[ 4 ];
  2484. r[ 5 ] = m[ 7 ];
  2485. r[ 6 ] = m[ 2 ];
  2486. r[ 7 ] = m[ 5 ];
  2487. r[ 8 ] = m[ 8 ];
  2488. return this;
  2489. },
  2490. fromArray: function ( array ) {
  2491. this.elements.set( array );
  2492. return this;
  2493. },
  2494. toArray: function () {
  2495. var te = this.elements;
  2496. return [
  2497. te[ 0 ], te[ 1 ], te[ 2 ],
  2498. te[ 3 ], te[ 4 ], te[ 5 ],
  2499. te[ 6 ], te[ 7 ], te[ 8 ]
  2500. ];
  2501. },
  2502. clone: function () {
  2503. var te = this.elements;
  2504. return new THREE.Matrix3(
  2505. te[0], te[3], te[6],
  2506. te[1], te[4], te[7],
  2507. te[2], te[5], te[8]
  2508. );
  2509. }
  2510. };
  2511. /**
  2512. * @author mrdoob / http://mrdoob.com/
  2513. * @author supereggbert / http://www.paulbrunt.co.uk/
  2514. * @author philogb / http://blog.thejit.org/
  2515. * @author jordi_ros / http://plattsoft.com
  2516. * @author D1plo1d / http://github.com/D1plo1d
  2517. * @author alteredq / http://alteredqualia.com/
  2518. * @author mikael emtinger / http://gomo.se/
  2519. * @author timknip / http://www.floorplanner.com/
  2520. * @author bhouston / http://exocortex.com
  2521. * @author WestLangley / http://github.com/WestLangley
  2522. */
  2523. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2524. this.elements = new Float32Array( 16 );
  2525. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2526. // we should not support semi specification of Matrix4, it is just weird.
  2527. var te = this.elements;
  2528. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2529. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2530. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2531. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2532. };
  2533. THREE.Matrix4.prototype = {
  2534. constructor: THREE.Matrix4,
  2535. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2536. var te = this.elements;
  2537. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2538. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2539. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2540. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2541. return this;
  2542. },
  2543. identity: function () {
  2544. this.set(
  2545. 1, 0, 0, 0,
  2546. 0, 1, 0, 0,
  2547. 0, 0, 1, 0,
  2548. 0, 0, 0, 1
  2549. );
  2550. return this;
  2551. },
  2552. copy: function ( m ) {
  2553. this.elements.set( m.elements );
  2554. return this;
  2555. },
  2556. extractPosition: function ( m ) {
  2557. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2558. return this.copyPosition( m );
  2559. },
  2560. copyPosition: function ( m ) {
  2561. var te = this.elements;
  2562. var me = m.elements;
  2563. te[12] = me[12];
  2564. te[13] = me[13];
  2565. te[14] = me[14];
  2566. return this;
  2567. },
  2568. extractRotation: function () {
  2569. var v1 = new THREE.Vector3();
  2570. return function ( m ) {
  2571. var te = this.elements;
  2572. var me = m.elements;
  2573. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2574. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2575. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2576. te[0] = me[0] * scaleX;
  2577. te[1] = me[1] * scaleX;
  2578. te[2] = me[2] * scaleX;
  2579. te[4] = me[4] * scaleY;
  2580. te[5] = me[5] * scaleY;
  2581. te[6] = me[6] * scaleY;
  2582. te[8] = me[8] * scaleZ;
  2583. te[9] = me[9] * scaleZ;
  2584. te[10] = me[10] * scaleZ;
  2585. return this;
  2586. };
  2587. }(),
  2588. makeRotationFromEuler: function ( euler ) {
  2589. if ( euler instanceof THREE.Euler === false ) {
  2590. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2591. }
  2592. var te = this.elements;
  2593. var x = euler.x, y = euler.y, z = euler.z;
  2594. var a = Math.cos( x ), b = Math.sin( x );
  2595. var c = Math.cos( y ), d = Math.sin( y );
  2596. var e = Math.cos( z ), f = Math.sin( z );
  2597. if ( euler.order === 'XYZ' ) {
  2598. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2599. te[0] = c * e;
  2600. te[4] = - c * f;
  2601. te[8] = d;
  2602. te[1] = af + be * d;
  2603. te[5] = ae - bf * d;
  2604. te[9] = - b * c;
  2605. te[2] = bf - ae * d;
  2606. te[6] = be + af * d;
  2607. te[10] = a * c;
  2608. } else if ( euler.order === 'YXZ' ) {
  2609. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2610. te[0] = ce + df * b;
  2611. te[4] = de * b - cf;
  2612. te[8] = a * d;
  2613. te[1] = a * f;
  2614. te[5] = a * e;
  2615. te[9] = - b;
  2616. te[2] = cf * b - de;
  2617. te[6] = df + ce * b;
  2618. te[10] = a * c;
  2619. } else if ( euler.order === 'ZXY' ) {
  2620. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2621. te[0] = ce - df * b;
  2622. te[4] = - a * f;
  2623. te[8] = de + cf * b;
  2624. te[1] = cf + de * b;
  2625. te[5] = a * e;
  2626. te[9] = df - ce * b;
  2627. te[2] = - a * d;
  2628. te[6] = b;
  2629. te[10] = a * c;
  2630. } else if ( euler.order === 'ZYX' ) {
  2631. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2632. te[0] = c * e;
  2633. te[4] = be * d - af;
  2634. te[8] = ae * d + bf;
  2635. te[1] = c * f;
  2636. te[5] = bf * d + ae;
  2637. te[9] = af * d - be;
  2638. te[2] = - d;
  2639. te[6] = b * c;
  2640. te[10] = a * c;
  2641. } else if ( euler.order === 'YZX' ) {
  2642. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2643. te[0] = c * e;
  2644. te[4] = bd - ac * f;
  2645. te[8] = bc * f + ad;
  2646. te[1] = f;
  2647. te[5] = a * e;
  2648. te[9] = - b * e;
  2649. te[2] = - d * e;
  2650. te[6] = ad * f + bc;
  2651. te[10] = ac - bd * f;
  2652. } else if ( euler.order === 'XZY' ) {
  2653. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2654. te[0] = c * e;
  2655. te[4] = - f;
  2656. te[8] = d * e;
  2657. te[1] = ac * f + bd;
  2658. te[5] = a * e;
  2659. te[9] = ad * f - bc;
  2660. te[2] = bc * f - ad;
  2661. te[6] = b * e;
  2662. te[10] = bd * f + ac;
  2663. }
  2664. // last column
  2665. te[3] = 0;
  2666. te[7] = 0;
  2667. te[11] = 0;
  2668. // bottom row
  2669. te[12] = 0;
  2670. te[13] = 0;
  2671. te[14] = 0;
  2672. te[15] = 1;
  2673. return this;
  2674. },
  2675. setRotationFromQuaternion: function ( q ) {
  2676. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2677. return this.makeRotationFromQuaternion( q );
  2678. },
  2679. makeRotationFromQuaternion: function ( q ) {
  2680. var te = this.elements;
  2681. var x = q.x, y = q.y, z = q.z, w = q.w;
  2682. var x2 = x + x, y2 = y + y, z2 = z + z;
  2683. var xx = x * x2, xy = x * y2, xz = x * z2;
  2684. var yy = y * y2, yz = y * z2, zz = z * z2;
  2685. var wx = w * x2, wy = w * y2, wz = w * z2;
  2686. te[0] = 1 - ( yy + zz );
  2687. te[4] = xy - wz;
  2688. te[8] = xz + wy;
  2689. te[1] = xy + wz;
  2690. te[5] = 1 - ( xx + zz );
  2691. te[9] = yz - wx;
  2692. te[2] = xz - wy;
  2693. te[6] = yz + wx;
  2694. te[10] = 1 - ( xx + yy );
  2695. // last column
  2696. te[3] = 0;
  2697. te[7] = 0;
  2698. te[11] = 0;
  2699. // bottom row
  2700. te[12] = 0;
  2701. te[13] = 0;
  2702. te[14] = 0;
  2703. te[15] = 1;
  2704. return this;
  2705. },
  2706. lookAt: function() {
  2707. var x = new THREE.Vector3();
  2708. var y = new THREE.Vector3();
  2709. var z = new THREE.Vector3();
  2710. return function ( eye, target, up ) {
  2711. var te = this.elements;
  2712. z.subVectors( eye, target ).normalize();
  2713. if ( z.length() === 0 ) {
  2714. z.z = 1;
  2715. }
  2716. x.crossVectors( up, z ).normalize();
  2717. if ( x.length() === 0 ) {
  2718. z.x += 0.0001;
  2719. x.crossVectors( up, z ).normalize();
  2720. }
  2721. y.crossVectors( z, x );
  2722. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2723. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2724. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2725. return this;
  2726. };
  2727. }(),
  2728. multiply: function ( m, n ) {
  2729. if ( n !== undefined ) {
  2730. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2731. return this.multiplyMatrices( m, n );
  2732. }
  2733. return this.multiplyMatrices( this, m );
  2734. },
  2735. multiplyMatrices: function ( a, b ) {
  2736. var ae = a.elements;
  2737. var be = b.elements;
  2738. var te = this.elements;
  2739. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2740. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2741. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2742. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2743. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2744. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2745. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2746. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2747. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2748. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2749. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2750. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2751. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2752. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2753. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2754. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2755. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2756. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2757. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2758. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2759. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2760. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2761. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2762. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2763. return this;
  2764. },
  2765. multiplyToArray: function ( a, b, r ) {
  2766. var te = this.elements;
  2767. this.multiplyMatrices( a, b );
  2768. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2769. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2770. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2771. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2772. return this;
  2773. },
  2774. multiplyScalar: function ( s ) {
  2775. var te = this.elements;
  2776. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2777. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2778. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2779. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2780. return this;
  2781. },
  2782. multiplyVector3: function ( vector ) {
  2783. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2784. return vector.applyProjection( this );
  2785. },
  2786. multiplyVector4: function ( vector ) {
  2787. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2788. return vector.applyMatrix4( this );
  2789. },
  2790. multiplyVector3Array: function ( a ) {
  2791. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2792. return this.applyToVector3Array( a );
  2793. },
  2794. applyToVector3Array: function() {
  2795. var v1 = new THREE.Vector3();
  2796. return function ( a ) {
  2797. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2798. v1.x = a[ i ];
  2799. v1.y = a[ i + 1 ];
  2800. v1.z = a[ i + 2 ];
  2801. v1.applyMatrix4( this );
  2802. a[ i ] = v1.x;
  2803. a[ i + 1 ] = v1.y;
  2804. a[ i + 2 ] = v1.z;
  2805. }
  2806. return a;
  2807. };
  2808. }(),
  2809. rotateAxis: function ( v ) {
  2810. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2811. v.transformDirection( this );
  2812. },
  2813. crossVector: function ( vector ) {
  2814. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2815. return vector.applyMatrix4( this );
  2816. },
  2817. determinant: function () {
  2818. var te = this.elements;
  2819. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2820. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2821. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2822. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2823. //TODO: make this more efficient
  2824. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2825. return (
  2826. n41 * (
  2827. +n14 * n23 * n32
  2828. -n13 * n24 * n32
  2829. -n14 * n22 * n33
  2830. +n12 * n24 * n33
  2831. +n13 * n22 * n34
  2832. -n12 * n23 * n34
  2833. ) +
  2834. n42 * (
  2835. +n11 * n23 * n34
  2836. -n11 * n24 * n33
  2837. +n14 * n21 * n33
  2838. -n13 * n21 * n34
  2839. +n13 * n24 * n31
  2840. -n14 * n23 * n31
  2841. ) +
  2842. n43 * (
  2843. +n11 * n24 * n32
  2844. -n11 * n22 * n34
  2845. -n14 * n21 * n32
  2846. +n12 * n21 * n34
  2847. +n14 * n22 * n31
  2848. -n12 * n24 * n31
  2849. ) +
  2850. n44 * (
  2851. -n13 * n22 * n31
  2852. -n11 * n23 * n32
  2853. +n11 * n22 * n33
  2854. +n13 * n21 * n32
  2855. -n12 * n21 * n33
  2856. +n12 * n23 * n31
  2857. )
  2858. );
  2859. },
  2860. transpose: function () {
  2861. var te = this.elements;
  2862. var tmp;
  2863. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2864. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2865. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2866. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2867. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2868. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2869. return this;
  2870. },
  2871. flattenToArrayOffset: function( array, offset ) {
  2872. var te = this.elements;
  2873. array[ offset ] = te[0];
  2874. array[ offset + 1 ] = te[1];
  2875. array[ offset + 2 ] = te[2];
  2876. array[ offset + 3 ] = te[3];
  2877. array[ offset + 4 ] = te[4];
  2878. array[ offset + 5 ] = te[5];
  2879. array[ offset + 6 ] = te[6];
  2880. array[ offset + 7 ] = te[7];
  2881. array[ offset + 8 ] = te[8];
  2882. array[ offset + 9 ] = te[9];
  2883. array[ offset + 10 ] = te[10];
  2884. array[ offset + 11 ] = te[11];
  2885. array[ offset + 12 ] = te[12];
  2886. array[ offset + 13 ] = te[13];
  2887. array[ offset + 14 ] = te[14];
  2888. array[ offset + 15 ] = te[15];
  2889. return array;
  2890. },
  2891. getPosition: function() {
  2892. var v1 = new THREE.Vector3();
  2893. return function () {
  2894. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2895. var te = this.elements;
  2896. return v1.set( te[12], te[13], te[14] );
  2897. };
  2898. }(),
  2899. setPosition: function ( v ) {
  2900. var te = this.elements;
  2901. te[12] = v.x;
  2902. te[13] = v.y;
  2903. te[14] = v.z;
  2904. return this;
  2905. },
  2906. getInverse: function ( m, throwOnInvertible ) {
  2907. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2908. var te = this.elements;
  2909. var me = m.elements;
  2910. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2911. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2912. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2913. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2914. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2915. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2916. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2917. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2918. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2919. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2920. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2921. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2922. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2923. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2924. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2925. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2926. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2927. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2928. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2929. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2930. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2931. if ( det == 0 ) {
  2932. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2933. if ( throwOnInvertible || false ) {
  2934. throw new Error( msg );
  2935. } else {
  2936. console.warn( msg );
  2937. }
  2938. this.identity();
  2939. return this;
  2940. }
  2941. this.multiplyScalar( 1 / det );
  2942. return this;
  2943. },
  2944. translate: function ( v ) {
  2945. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2946. },
  2947. rotateX: function ( angle ) {
  2948. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2949. },
  2950. rotateY: function ( angle ) {
  2951. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2952. },
  2953. rotateZ: function ( angle ) {
  2954. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2955. },
  2956. rotateByAxis: function ( axis, angle ) {
  2957. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2958. },
  2959. scale: function ( v ) {
  2960. var te = this.elements;
  2961. var x = v.x, y = v.y, z = v.z;
  2962. te[0] *= x; te[4] *= y; te[8] *= z;
  2963. te[1] *= x; te[5] *= y; te[9] *= z;
  2964. te[2] *= x; te[6] *= y; te[10] *= z;
  2965. te[3] *= x; te[7] *= y; te[11] *= z;
  2966. return this;
  2967. },
  2968. getMaxScaleOnAxis: function () {
  2969. var te = this.elements;
  2970. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2971. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2972. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2973. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2974. },
  2975. makeTranslation: function ( x, y, z ) {
  2976. this.set(
  2977. 1, 0, 0, x,
  2978. 0, 1, 0, y,
  2979. 0, 0, 1, z,
  2980. 0, 0, 0, 1
  2981. );
  2982. return this;
  2983. },
  2984. makeRotationX: function ( theta ) {
  2985. var c = Math.cos( theta ), s = Math.sin( theta );
  2986. this.set(
  2987. 1, 0, 0, 0,
  2988. 0, c, -s, 0,
  2989. 0, s, c, 0,
  2990. 0, 0, 0, 1
  2991. );
  2992. return this;
  2993. },
  2994. makeRotationY: function ( theta ) {
  2995. var c = Math.cos( theta ), s = Math.sin( theta );
  2996. this.set(
  2997. c, 0, s, 0,
  2998. 0, 1, 0, 0,
  2999. -s, 0, c, 0,
  3000. 0, 0, 0, 1
  3001. );
  3002. return this;
  3003. },
  3004. makeRotationZ: function ( theta ) {
  3005. var c = Math.cos( theta ), s = Math.sin( theta );
  3006. this.set(
  3007. c, -s, 0, 0,
  3008. s, c, 0, 0,
  3009. 0, 0, 1, 0,
  3010. 0, 0, 0, 1
  3011. );
  3012. return this;
  3013. },
  3014. makeRotationAxis: function ( axis, angle ) {
  3015. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3016. var c = Math.cos( angle );
  3017. var s = Math.sin( angle );
  3018. var t = 1 - c;
  3019. var x = axis.x, y = axis.y, z = axis.z;
  3020. var tx = t * x, ty = t * y;
  3021. this.set(
  3022. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3023. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3024. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3025. 0, 0, 0, 1
  3026. );
  3027. return this;
  3028. },
  3029. makeScale: function ( x, y, z ) {
  3030. this.set(
  3031. x, 0, 0, 0,
  3032. 0, y, 0, 0,
  3033. 0, 0, z, 0,
  3034. 0, 0, 0, 1
  3035. );
  3036. return this;
  3037. },
  3038. compose: function ( position, quaternion, scale ) {
  3039. this.makeRotationFromQuaternion( quaternion );
  3040. this.scale( scale );
  3041. this.setPosition( position );
  3042. return this;
  3043. },
  3044. decompose: function () {
  3045. var vector = new THREE.Vector3();
  3046. var matrix = new THREE.Matrix4();
  3047. return function ( position, quaternion, scale ) {
  3048. var te = this.elements;
  3049. var sx = vector.set( te[0], te[1], te[2] ).length();
  3050. var sy = vector.set( te[4], te[5], te[6] ).length();
  3051. var sz = vector.set( te[8], te[9], te[10] ).length();
  3052. // if determine is negative, we need to invert one scale
  3053. var det = this.determinant();
  3054. if( det < 0 ) {
  3055. sx = -sx;
  3056. }
  3057. position.x = te[12];
  3058. position.y = te[13];
  3059. position.z = te[14];
  3060. // scale the rotation part
  3061. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3062. var invSX = 1 / sx;
  3063. var invSY = 1 / sy;
  3064. var invSZ = 1 / sz;
  3065. matrix.elements[0] *= invSX;
  3066. matrix.elements[1] *= invSX;
  3067. matrix.elements[2] *= invSX;
  3068. matrix.elements[4] *= invSY;
  3069. matrix.elements[5] *= invSY;
  3070. matrix.elements[6] *= invSY;
  3071. matrix.elements[8] *= invSZ;
  3072. matrix.elements[9] *= invSZ;
  3073. matrix.elements[10] *= invSZ;
  3074. quaternion.setFromRotationMatrix( matrix );
  3075. scale.x = sx;
  3076. scale.y = sy;
  3077. scale.z = sz;
  3078. return this;
  3079. };
  3080. }(),
  3081. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3082. var te = this.elements;
  3083. var x = 2 * near / ( right - left );
  3084. var y = 2 * near / ( top - bottom );
  3085. var a = ( right + left ) / ( right - left );
  3086. var b = ( top + bottom ) / ( top - bottom );
  3087. var c = - ( far + near ) / ( far - near );
  3088. var d = - 2 * far * near / ( far - near );
  3089. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3090. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3091. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3092. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3093. return this;
  3094. },
  3095. makePerspective: function ( fov, aspect, near, far ) {
  3096. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3097. var ymin = - ymax;
  3098. var xmin = ymin * aspect;
  3099. var xmax = ymax * aspect;
  3100. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3101. },
  3102. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3103. var te = this.elements;
  3104. var w = right - left;
  3105. var h = top - bottom;
  3106. var p = far - near;
  3107. var x = ( right + left ) / w;
  3108. var y = ( top + bottom ) / h;
  3109. var z = ( far + near ) / p;
  3110. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3111. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3112. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3113. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3114. return this;
  3115. },
  3116. fromArray: function ( array ) {
  3117. this.elements.set( array );
  3118. return this;
  3119. },
  3120. toArray: function () {
  3121. var te = this.elements;
  3122. return [
  3123. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3124. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3125. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3126. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3127. ];
  3128. },
  3129. clone: function () {
  3130. var te = this.elements;
  3131. return new THREE.Matrix4(
  3132. te[0], te[4], te[8], te[12],
  3133. te[1], te[5], te[9], te[13],
  3134. te[2], te[6], te[10], te[14],
  3135. te[3], te[7], te[11], te[15]
  3136. );
  3137. }
  3138. };
  3139. /**
  3140. * @author bhouston / http://exocortex.com
  3141. */
  3142. THREE.Ray = function ( origin, direction ) {
  3143. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3144. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3145. };
  3146. THREE.Ray.prototype = {
  3147. constructor: THREE.Ray,
  3148. set: function ( origin, direction ) {
  3149. this.origin.copy( origin );
  3150. this.direction.copy( direction );
  3151. return this;
  3152. },
  3153. copy: function ( ray ) {
  3154. this.origin.copy( ray.origin );
  3155. this.direction.copy( ray.direction );
  3156. return this;
  3157. },
  3158. at: function ( t, optionalTarget ) {
  3159. var result = optionalTarget || new THREE.Vector3();
  3160. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3161. },
  3162. recast: function () {
  3163. var v1 = new THREE.Vector3();
  3164. return function ( t ) {
  3165. this.origin.copy( this.at( t, v1 ) );
  3166. return this;
  3167. };
  3168. }(),
  3169. closestPointToPoint: function ( point, optionalTarget ) {
  3170. var result = optionalTarget || new THREE.Vector3();
  3171. result.subVectors( point, this.origin );
  3172. var directionDistance = result.dot( this.direction );
  3173. if ( directionDistance < 0 ) {
  3174. return result.copy( this.origin );
  3175. }
  3176. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3177. },
  3178. distanceToPoint: function () {
  3179. var v1 = new THREE.Vector3();
  3180. return function ( point ) {
  3181. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3182. // point behind the ray
  3183. if ( directionDistance < 0 ) {
  3184. return this.origin.distanceTo( point );
  3185. }
  3186. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3187. return v1.distanceTo( point );
  3188. };
  3189. }(),
  3190. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3191. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3192. // It returns the min distance between the ray and the segment
  3193. // defined by v0 and v1
  3194. // It can also set two optional targets :
  3195. // - The closest point on the ray
  3196. // - The closest point on the segment
  3197. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3198. var segDir = v1.clone().sub( v0 ).normalize();
  3199. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3200. var diff = this.origin.clone().sub( segCenter );
  3201. var a01 = - this.direction.dot( segDir );
  3202. var b0 = diff.dot( this.direction );
  3203. var b1 = - diff.dot( segDir );
  3204. var c = diff.lengthSq();
  3205. var det = Math.abs( 1 - a01 * a01 );
  3206. var s0, s1, sqrDist, extDet;
  3207. if ( det >= 0 ) {
  3208. // The ray and segment are not parallel.
  3209. s0 = a01 * b1 - b0;
  3210. s1 = a01 * b0 - b1;
  3211. extDet = segExtent * det;
  3212. if ( s0 >= 0 ) {
  3213. if ( s1 >= - extDet ) {
  3214. if ( s1 <= extDet ) {
  3215. // region 0
  3216. // Minimum at interior points of ray and segment.
  3217. var invDet = 1 / det;
  3218. s0 *= invDet;
  3219. s1 *= invDet;
  3220. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3221. } else {
  3222. // region 1
  3223. s1 = segExtent;
  3224. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3225. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3226. }
  3227. } else {
  3228. // region 5
  3229. s1 = - segExtent;
  3230. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3231. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3232. }
  3233. } else {
  3234. if ( s1 <= - extDet) {
  3235. // region 4
  3236. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3237. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3238. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3239. } else if ( s1 <= extDet ) {
  3240. // region 3
  3241. s0 = 0;
  3242. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3243. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3244. } else {
  3245. // region 2
  3246. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3247. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3248. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3249. }
  3250. }
  3251. } else {
  3252. // Ray and segment are parallel.
  3253. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3254. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3255. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3256. }
  3257. if ( optionalPointOnRay ) {
  3258. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3259. }
  3260. if ( optionalPointOnSegment ) {
  3261. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3262. }
  3263. return sqrDist;
  3264. },
  3265. isIntersectionSphere: function ( sphere ) {
  3266. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3267. },
  3268. isIntersectionPlane: function ( plane ) {
  3269. // check if the ray lies on the plane first
  3270. var distToPoint = plane.distanceToPoint( this.origin );
  3271. if ( distToPoint === 0 ) {
  3272. return true;
  3273. }
  3274. var denominator = plane.normal.dot( this.direction );
  3275. if ( denominator * distToPoint < 0 ) {
  3276. return true
  3277. }
  3278. // ray origin is behind the plane (and is pointing behind it)
  3279. return false;
  3280. },
  3281. distanceToPlane: function ( plane ) {
  3282. var denominator = plane.normal.dot( this.direction );
  3283. if ( denominator == 0 ) {
  3284. // line is coplanar, return origin
  3285. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3286. return 0;
  3287. }
  3288. // Null is preferable to undefined since undefined means.... it is undefined
  3289. return null;
  3290. }
  3291. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3292. // Return if the ray never intersects the plane
  3293. return t >= 0 ? t : null;
  3294. },
  3295. intersectPlane: function ( plane, optionalTarget ) {
  3296. var t = this.distanceToPlane( plane );
  3297. if ( t === null ) {
  3298. return null;
  3299. }
  3300. return this.at( t, optionalTarget );
  3301. },
  3302. isIntersectionBox: function () {
  3303. var v = new THREE.Vector3();
  3304. return function ( box ) {
  3305. return this.intersectBox( box, v ) !== null;
  3306. }
  3307. }(),
  3308. intersectBox: function ( box , optionalTarget ) {
  3309. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3310. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3311. var invdirx = 1/this.direction.x,
  3312. invdiry = 1/this.direction.y,
  3313. invdirz = 1/this.direction.z;
  3314. var origin = this.origin;
  3315. if (invdirx >= 0) {
  3316. tmin = (box.min.x - origin.x) * invdirx;
  3317. tmax = (box.max.x - origin.x) * invdirx;
  3318. } else {
  3319. tmin = (box.max.x - origin.x) * invdirx;
  3320. tmax = (box.min.x - origin.x) * invdirx;
  3321. }
  3322. if (invdiry >= 0) {
  3323. tymin = (box.min.y - origin.y) * invdiry;
  3324. tymax = (box.max.y - origin.y) * invdiry;
  3325. } else {
  3326. tymin = (box.max.y - origin.y) * invdiry;
  3327. tymax = (box.min.y - origin.y) * invdiry;
  3328. }
  3329. if ((tmin > tymax) || (tymin > tmax)) return null;
  3330. // These lines also handle the case where tmin or tmax is NaN
  3331. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3332. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3333. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3334. if (invdirz >= 0) {
  3335. tzmin = (box.min.z - origin.z) * invdirz;
  3336. tzmax = (box.max.z - origin.z) * invdirz;
  3337. } else {
  3338. tzmin = (box.max.z - origin.z) * invdirz;
  3339. tzmax = (box.min.z - origin.z) * invdirz;
  3340. }
  3341. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3342. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3343. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3344. //return point closest to the ray (positive side)
  3345. if ( tmax < 0 ) return null;
  3346. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3347. },
  3348. intersectTriangle: function() {
  3349. // Compute the offset origin, edges, and normal.
  3350. var diff = new THREE.Vector3();
  3351. var edge1 = new THREE.Vector3();
  3352. var edge2 = new THREE.Vector3();
  3353. var normal = new THREE.Vector3();
  3354. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3355. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3356. edge1.subVectors( b, a );
  3357. edge2.subVectors( c, a );
  3358. normal.crossVectors( edge1, edge2 );
  3359. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3360. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3361. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3362. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3363. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3364. var DdN = this.direction.dot( normal );
  3365. var sign;
  3366. if ( DdN > 0 ) {
  3367. if ( backfaceCulling ) return null;
  3368. sign = 1;
  3369. } else if ( DdN < 0 ) {
  3370. sign = - 1;
  3371. DdN = - DdN;
  3372. } else {
  3373. return null;
  3374. }
  3375. diff.subVectors( this.origin, a );
  3376. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3377. // b1 < 0, no intersection
  3378. if ( DdQxE2 < 0 ) {
  3379. return null;
  3380. }
  3381. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3382. // b2 < 0, no intersection
  3383. if ( DdE1xQ < 0 ) {
  3384. return null;
  3385. }
  3386. // b1+b2 > 1, no intersection
  3387. if ( DdQxE2 + DdE1xQ > DdN ) {
  3388. return null;
  3389. }
  3390. // Line intersects triangle, check if ray does.
  3391. var QdN = - sign * diff.dot( normal );
  3392. // t < 0, no intersection
  3393. if ( QdN < 0 ) {
  3394. return null;
  3395. }
  3396. // Ray intersects triangle.
  3397. return this.at( QdN / DdN, optionalTarget );
  3398. }
  3399. }(),
  3400. applyMatrix4: function ( matrix4 ) {
  3401. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3402. this.origin.applyMatrix4( matrix4 );
  3403. this.direction.sub( this.origin );
  3404. this.direction.normalize();
  3405. return this;
  3406. },
  3407. equals: function ( ray ) {
  3408. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3409. },
  3410. clone: function () {
  3411. return new THREE.Ray().copy( this );
  3412. }
  3413. };
  3414. /**
  3415. * @author bhouston / http://exocortex.com
  3416. * @author mrdoob / http://mrdoob.com/
  3417. */
  3418. THREE.Sphere = function ( center, radius ) {
  3419. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3420. this.radius = ( radius !== undefined ) ? radius : 0;
  3421. };
  3422. THREE.Sphere.prototype = {
  3423. constructor: THREE.Sphere,
  3424. set: function ( center, radius ) {
  3425. this.center.copy( center );
  3426. this.radius = radius;
  3427. return this;
  3428. },
  3429. setFromPoints: function () {
  3430. var box = new THREE.Box3();
  3431. return function ( points, optionalCenter ) {
  3432. var center = this.center;
  3433. if ( optionalCenter !== undefined ) {
  3434. center.copy( optionalCenter );
  3435. } else {
  3436. box.setFromPoints( points ).center( center );
  3437. }
  3438. var maxRadiusSq = 0;
  3439. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3440. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3441. }
  3442. this.radius = Math.sqrt( maxRadiusSq );
  3443. return this;
  3444. };
  3445. }(),
  3446. copy: function ( sphere ) {
  3447. this.center.copy( sphere.center );
  3448. this.radius = sphere.radius;
  3449. return this;
  3450. },
  3451. empty: function () {
  3452. return ( this.radius <= 0 );
  3453. },
  3454. containsPoint: function ( point ) {
  3455. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3456. },
  3457. distanceToPoint: function ( point ) {
  3458. return ( point.distanceTo( this.center ) - this.radius );
  3459. },
  3460. intersectsSphere: function ( sphere ) {
  3461. var radiusSum = this.radius + sphere.radius;
  3462. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3463. },
  3464. clampPoint: function ( point, optionalTarget ) {
  3465. var deltaLengthSq = this.center.distanceToSquared( point );
  3466. var result = optionalTarget || new THREE.Vector3();
  3467. result.copy( point );
  3468. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3469. result.sub( this.center ).normalize();
  3470. result.multiplyScalar( this.radius ).add( this.center );
  3471. }
  3472. return result;
  3473. },
  3474. getBoundingBox: function ( optionalTarget ) {
  3475. var box = optionalTarget || new THREE.Box3();
  3476. box.set( this.center, this.center );
  3477. box.expandByScalar( this.radius );
  3478. return box;
  3479. },
  3480. applyMatrix4: function ( matrix ) {
  3481. this.center.applyMatrix4( matrix );
  3482. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3483. return this;
  3484. },
  3485. translate: function ( offset ) {
  3486. this.center.add( offset );
  3487. return this;
  3488. },
  3489. equals: function ( sphere ) {
  3490. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3491. },
  3492. clone: function () {
  3493. return new THREE.Sphere().copy( this );
  3494. }
  3495. };
  3496. /**
  3497. * @author mrdoob / http://mrdoob.com/
  3498. * @author alteredq / http://alteredqualia.com/
  3499. * @author bhouston / http://exocortex.com
  3500. */
  3501. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3502. this.planes = [
  3503. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3504. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3505. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3506. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3507. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3508. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3509. ];
  3510. };
  3511. THREE.Frustum.prototype = {
  3512. constructor: THREE.Frustum,
  3513. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3514. var planes = this.planes;
  3515. planes[0].copy( p0 );
  3516. planes[1].copy( p1 );
  3517. planes[2].copy( p2 );
  3518. planes[3].copy( p3 );
  3519. planes[4].copy( p4 );
  3520. planes[5].copy( p5 );
  3521. return this;
  3522. },
  3523. copy: function ( frustum ) {
  3524. var planes = this.planes;
  3525. for( var i = 0; i < 6; i ++ ) {
  3526. planes[i].copy( frustum.planes[i] );
  3527. }
  3528. return this;
  3529. },
  3530. setFromMatrix: function ( m ) {
  3531. var planes = this.planes;
  3532. var me = m.elements;
  3533. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3534. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3535. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3536. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3537. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3538. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3539. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3540. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3541. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3542. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3543. return this;
  3544. },
  3545. intersectsObject: function () {
  3546. var sphere = new THREE.Sphere();
  3547. return function ( object ) {
  3548. var geometry = object.geometry;
  3549. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3550. sphere.copy( geometry.boundingSphere );
  3551. sphere.applyMatrix4( object.matrixWorld );
  3552. return this.intersectsSphere( sphere );
  3553. };
  3554. }(),
  3555. intersectsSphere: function ( sphere ) {
  3556. var planes = this.planes;
  3557. var center = sphere.center;
  3558. var negRadius = -sphere.radius;
  3559. for ( var i = 0; i < 6; i ++ ) {
  3560. var distance = planes[ i ].distanceToPoint( center );
  3561. if ( distance < negRadius ) {
  3562. return false;
  3563. }
  3564. }
  3565. return true;
  3566. },
  3567. intersectsBox : function() {
  3568. var p1 = new THREE.Vector3(),
  3569. p2 = new THREE.Vector3();
  3570. return function( box ) {
  3571. var planes = this.planes;
  3572. for ( var i = 0; i < 6 ; i ++ ) {
  3573. var plane = planes[i];
  3574. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3575. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3576. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3577. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3578. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3579. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3580. var d1 = plane.distanceToPoint( p1 );
  3581. var d2 = plane.distanceToPoint( p2 );
  3582. // if both outside plane, no intersection
  3583. if ( d1 < 0 && d2 < 0 ) {
  3584. return false;
  3585. }
  3586. }
  3587. return true;
  3588. };
  3589. }(),
  3590. containsPoint: function ( point ) {
  3591. var planes = this.planes;
  3592. for ( var i = 0; i < 6; i ++ ) {
  3593. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3594. return false;
  3595. }
  3596. }
  3597. return true;
  3598. },
  3599. clone: function () {
  3600. return new THREE.Frustum().copy( this );
  3601. }
  3602. };
  3603. /**
  3604. * @author bhouston / http://exocortex.com
  3605. */
  3606. THREE.Plane = function ( normal, constant ) {
  3607. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3608. this.constant = ( constant !== undefined ) ? constant : 0;
  3609. };
  3610. THREE.Plane.prototype = {
  3611. constructor: THREE.Plane,
  3612. set: function ( normal, constant ) {
  3613. this.normal.copy( normal );
  3614. this.constant = constant;
  3615. return this;
  3616. },
  3617. setComponents: function ( x, y, z, w ) {
  3618. this.normal.set( x, y, z );
  3619. this.constant = w;
  3620. return this;
  3621. },
  3622. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3623. this.normal.copy( normal );
  3624. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3625. return this;
  3626. },
  3627. setFromCoplanarPoints: function() {
  3628. var v1 = new THREE.Vector3();
  3629. var v2 = new THREE.Vector3();
  3630. return function ( a, b, c ) {
  3631. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3632. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3633. this.setFromNormalAndCoplanarPoint( normal, a );
  3634. return this;
  3635. };
  3636. }(),
  3637. copy: function ( plane ) {
  3638. this.normal.copy( plane.normal );
  3639. this.constant = plane.constant;
  3640. return this;
  3641. },
  3642. normalize: function () {
  3643. // Note: will lead to a divide by zero if the plane is invalid.
  3644. var inverseNormalLength = 1.0 / this.normal.length();
  3645. this.normal.multiplyScalar( inverseNormalLength );
  3646. this.constant *= inverseNormalLength;
  3647. return this;
  3648. },
  3649. negate: function () {
  3650. this.constant *= -1;
  3651. this.normal.negate();
  3652. return this;
  3653. },
  3654. distanceToPoint: function ( point ) {
  3655. return this.normal.dot( point ) + this.constant;
  3656. },
  3657. distanceToSphere: function ( sphere ) {
  3658. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3659. },
  3660. projectPoint: function ( point, optionalTarget ) {
  3661. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3662. },
  3663. orthoPoint: function ( point, optionalTarget ) {
  3664. var perpendicularMagnitude = this.distanceToPoint( point );
  3665. var result = optionalTarget || new THREE.Vector3();
  3666. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3667. },
  3668. isIntersectionLine: function ( line ) {
  3669. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3670. var startSign = this.distanceToPoint( line.start );
  3671. var endSign = this.distanceToPoint( line.end );
  3672. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3673. },
  3674. intersectLine: function() {
  3675. var v1 = new THREE.Vector3();
  3676. return function ( line, optionalTarget ) {
  3677. var result = optionalTarget || new THREE.Vector3();
  3678. var direction = line.delta( v1 );
  3679. var denominator = this.normal.dot( direction );
  3680. if ( denominator == 0 ) {
  3681. // line is coplanar, return origin
  3682. if( this.distanceToPoint( line.start ) == 0 ) {
  3683. return result.copy( line.start );
  3684. }
  3685. // Unsure if this is the correct method to handle this case.
  3686. return undefined;
  3687. }
  3688. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3689. if( t < 0 || t > 1 ) {
  3690. return undefined;
  3691. }
  3692. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3693. };
  3694. }(),
  3695. coplanarPoint: function ( optionalTarget ) {
  3696. var result = optionalTarget || new THREE.Vector3();
  3697. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3698. },
  3699. applyMatrix4: function() {
  3700. var v1 = new THREE.Vector3();
  3701. var v2 = new THREE.Vector3();
  3702. var m1 = new THREE.Matrix3();
  3703. return function ( matrix, optionalNormalMatrix ) {
  3704. // compute new normal based on theory here:
  3705. // http://www.songho.ca/opengl/gl_normaltransform.html
  3706. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3707. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3708. var newCoplanarPoint = this.coplanarPoint( v2 );
  3709. newCoplanarPoint.applyMatrix4( matrix );
  3710. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3711. return this;
  3712. };
  3713. }(),
  3714. translate: function ( offset ) {
  3715. this.constant = this.constant - offset.dot( this.normal );
  3716. return this;
  3717. },
  3718. equals: function ( plane ) {
  3719. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3720. },
  3721. clone: function () {
  3722. return new THREE.Plane().copy( this );
  3723. }
  3724. };
  3725. /**
  3726. * @author alteredq / http://alteredqualia.com/
  3727. * @author mrdoob / http://mrdoob.com/
  3728. */
  3729. THREE.Math = {
  3730. generateUUID: function () {
  3731. // http://www.broofa.com/Tools/Math.uuid.htm
  3732. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3733. var uuid = new Array(36);
  3734. var rnd = 0, r;
  3735. return function () {
  3736. for ( var i = 0; i < 36; i ++ ) {
  3737. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3738. uuid[ i ] = '-';
  3739. } else if ( i == 14 ) {
  3740. uuid[ i ] = '4';
  3741. } else {
  3742. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3743. r = rnd & 0xf;
  3744. rnd = rnd >> 4;
  3745. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3746. }
  3747. }
  3748. return uuid.join('');
  3749. };
  3750. }(),
  3751. // Clamp value to range <a, b>
  3752. clamp: function ( x, a, b ) {
  3753. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3754. },
  3755. // Clamp value to range <a, inf)
  3756. clampBottom: function ( x, a ) {
  3757. return x < a ? a : x;
  3758. },
  3759. // Linear mapping from range <a1, a2> to range <b1, b2>
  3760. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3761. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3762. },
  3763. // http://en.wikipedia.org/wiki/Smoothstep
  3764. smoothstep: function ( x, min, max ) {
  3765. if ( x <= min ) return 0;
  3766. if ( x >= max ) return 1;
  3767. x = ( x - min )/( max - min );
  3768. return x*x*(3 - 2*x);
  3769. },
  3770. smootherstep: function ( x, min, max ) {
  3771. if ( x <= min ) return 0;
  3772. if ( x >= max ) return 1;
  3773. x = ( x - min )/( max - min );
  3774. return x*x*x*(x*(x*6 - 15) + 10);
  3775. },
  3776. // Random float from <0, 1> with 16 bits of randomness
  3777. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3778. random16: function () {
  3779. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3780. },
  3781. // Random integer from <low, high> interval
  3782. randInt: function ( low, high ) {
  3783. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3784. },
  3785. // Random float from <low, high> interval
  3786. randFloat: function ( low, high ) {
  3787. return low + Math.random() * ( high - low );
  3788. },
  3789. // Random float from <-range/2, range/2> interval
  3790. randFloatSpread: function ( range ) {
  3791. return range * ( 0.5 - Math.random() );
  3792. },
  3793. sign: function ( x ) {
  3794. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3795. },
  3796. degToRad: function() {
  3797. var degreeToRadiansFactor = Math.PI / 180;
  3798. return function ( degrees ) {
  3799. return degrees * degreeToRadiansFactor;
  3800. };
  3801. }(),
  3802. radToDeg: function() {
  3803. var radianToDegreesFactor = 180 / Math.PI;
  3804. return function ( radians ) {
  3805. return radians * radianToDegreesFactor;
  3806. };
  3807. }(),
  3808. isPowerOfTwo: function ( value ) {
  3809. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3810. }
  3811. };
  3812. /**
  3813. * Spline from Tween.js, slightly optimized (and trashed)
  3814. * http://sole.github.com/tween.js/examples/05_spline.html
  3815. *
  3816. * @author mrdoob / http://mrdoob.com/
  3817. * @author alteredq / http://alteredqualia.com/
  3818. */
  3819. THREE.Spline = function ( points ) {
  3820. this.points = points;
  3821. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3822. point, intPoint, weight, w2, w3,
  3823. pa, pb, pc, pd;
  3824. this.initFromArray = function( a ) {
  3825. this.points = [];
  3826. for ( var i = 0; i < a.length; i++ ) {
  3827. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3828. }
  3829. };
  3830. this.getPoint = function ( k ) {
  3831. point = ( this.points.length - 1 ) * k;
  3832. intPoint = Math.floor( point );
  3833. weight = point - intPoint;
  3834. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3835. c[ 1 ] = intPoint;
  3836. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3837. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3838. pa = this.points[ c[ 0 ] ];
  3839. pb = this.points[ c[ 1 ] ];
  3840. pc = this.points[ c[ 2 ] ];
  3841. pd = this.points[ c[ 3 ] ];
  3842. w2 = weight * weight;
  3843. w3 = weight * w2;
  3844. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3845. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3846. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3847. return v3;
  3848. };
  3849. this.getControlPointsArray = function () {
  3850. var i, p, l = this.points.length,
  3851. coords = [];
  3852. for ( i = 0; i < l; i ++ ) {
  3853. p = this.points[ i ];
  3854. coords[ i ] = [ p.x, p.y, p.z ];
  3855. }
  3856. return coords;
  3857. };
  3858. // approximate length by summing linear segments
  3859. this.getLength = function ( nSubDivisions ) {
  3860. var i, index, nSamples, position,
  3861. point = 0, intPoint = 0, oldIntPoint = 0,
  3862. oldPosition = new THREE.Vector3(),
  3863. tmpVec = new THREE.Vector3(),
  3864. chunkLengths = [],
  3865. totalLength = 0;
  3866. // first point has 0 length
  3867. chunkLengths[ 0 ] = 0;
  3868. if ( !nSubDivisions ) nSubDivisions = 100;
  3869. nSamples = this.points.length * nSubDivisions;
  3870. oldPosition.copy( this.points[ 0 ] );
  3871. for ( i = 1; i < nSamples; i ++ ) {
  3872. index = i / nSamples;
  3873. position = this.getPoint( index );
  3874. tmpVec.copy( position );
  3875. totalLength += tmpVec.distanceTo( oldPosition );
  3876. oldPosition.copy( position );
  3877. point = ( this.points.length - 1 ) * index;
  3878. intPoint = Math.floor( point );
  3879. if ( intPoint != oldIntPoint ) {
  3880. chunkLengths[ intPoint ] = totalLength;
  3881. oldIntPoint = intPoint;
  3882. }
  3883. }
  3884. // last point ends with total length
  3885. chunkLengths[ chunkLengths.length ] = totalLength;
  3886. return { chunks: chunkLengths, total: totalLength };
  3887. };
  3888. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3889. var i, j,
  3890. index, indexCurrent, indexNext,
  3891. linearDistance, realDistance,
  3892. sampling, position,
  3893. newpoints = [],
  3894. tmpVec = new THREE.Vector3(),
  3895. sl = this.getLength();
  3896. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3897. for ( i = 1; i < this.points.length; i++ ) {
  3898. //tmpVec.copy( this.points[ i - 1 ] );
  3899. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3900. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3901. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3902. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3903. indexNext = i / ( this.points.length - 1 );
  3904. for ( j = 1; j < sampling - 1; j++ ) {
  3905. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3906. position = this.getPoint( index );
  3907. newpoints.push( tmpVec.copy( position ).clone() );
  3908. }
  3909. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3910. }
  3911. this.points = newpoints;
  3912. };
  3913. // Catmull-Rom
  3914. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3915. var v0 = ( p2 - p0 ) * 0.5,
  3916. v1 = ( p3 - p1 ) * 0.5;
  3917. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3918. };
  3919. };
  3920. /**
  3921. * @author bhouston / http://exocortex.com
  3922. * @author mrdoob / http://mrdoob.com/
  3923. */
  3924. THREE.Triangle = function ( a, b, c ) {
  3925. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3926. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3927. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3928. };
  3929. THREE.Triangle.normal = function() {
  3930. var v0 = new THREE.Vector3();
  3931. return function ( a, b, c, optionalTarget ) {
  3932. var result = optionalTarget || new THREE.Vector3();
  3933. result.subVectors( c, b );
  3934. v0.subVectors( a, b );
  3935. result.cross( v0 );
  3936. var resultLengthSq = result.lengthSq();
  3937. if( resultLengthSq > 0 ) {
  3938. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3939. }
  3940. return result.set( 0, 0, 0 );
  3941. };
  3942. }();
  3943. // static/instance method to calculate barycoordinates
  3944. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3945. THREE.Triangle.barycoordFromPoint = function() {
  3946. var v0 = new THREE.Vector3();
  3947. var v1 = new THREE.Vector3();
  3948. var v2 = new THREE.Vector3();
  3949. return function ( point, a, b, c, optionalTarget ) {
  3950. v0.subVectors( c, a );
  3951. v1.subVectors( b, a );
  3952. v2.subVectors( point, a );
  3953. var dot00 = v0.dot( v0 );
  3954. var dot01 = v0.dot( v1 );
  3955. var dot02 = v0.dot( v2 );
  3956. var dot11 = v1.dot( v1 );
  3957. var dot12 = v1.dot( v2 );
  3958. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3959. var result = optionalTarget || new THREE.Vector3();
  3960. // colinear or singular triangle
  3961. if( denom == 0 ) {
  3962. // arbitrary location outside of triangle?
  3963. // not sure if this is the best idea, maybe should be returning undefined
  3964. return result.set( -2, -1, -1 );
  3965. }
  3966. var invDenom = 1 / denom;
  3967. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3968. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3969. // barycoordinates must always sum to 1
  3970. return result.set( 1 - u - v, v, u );
  3971. };
  3972. }();
  3973. THREE.Triangle.containsPoint = function() {
  3974. var v1 = new THREE.Vector3();
  3975. return function ( point, a, b, c ) {
  3976. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3977. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3978. };
  3979. }();
  3980. THREE.Triangle.prototype = {
  3981. constructor: THREE.Triangle,
  3982. set: function ( a, b, c ) {
  3983. this.a.copy( a );
  3984. this.b.copy( b );
  3985. this.c.copy( c );
  3986. return this;
  3987. },
  3988. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3989. this.a.copy( points[i0] );
  3990. this.b.copy( points[i1] );
  3991. this.c.copy( points[i2] );
  3992. return this;
  3993. },
  3994. copy: function ( triangle ) {
  3995. this.a.copy( triangle.a );
  3996. this.b.copy( triangle.b );
  3997. this.c.copy( triangle.c );
  3998. return this;
  3999. },
  4000. area: function() {
  4001. var v0 = new THREE.Vector3();
  4002. var v1 = new THREE.Vector3();
  4003. return function () {
  4004. v0.subVectors( this.c, this.b );
  4005. v1.subVectors( this.a, this.b );
  4006. return v0.cross( v1 ).length() * 0.5;
  4007. };
  4008. }(),
  4009. midpoint: function ( optionalTarget ) {
  4010. var result = optionalTarget || new THREE.Vector3();
  4011. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4012. },
  4013. normal: function ( optionalTarget ) {
  4014. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4015. },
  4016. plane: function ( optionalTarget ) {
  4017. var result = optionalTarget || new THREE.Plane();
  4018. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4019. },
  4020. barycoordFromPoint: function ( point, optionalTarget ) {
  4021. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4022. },
  4023. containsPoint: function ( point ) {
  4024. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4025. },
  4026. equals: function ( triangle ) {
  4027. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4028. },
  4029. clone: function () {
  4030. return new THREE.Triangle().copy( this );
  4031. }
  4032. };
  4033. /**
  4034. * @author mrdoob / http://mrdoob.com/
  4035. */
  4036. THREE.Vertex = function ( v ) {
  4037. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  4038. return v;
  4039. };
  4040. /**
  4041. * @author alteredq / http://alteredqualia.com/
  4042. */
  4043. THREE.Clock = function ( autoStart ) {
  4044. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4045. this.startTime = 0;
  4046. this.oldTime = 0;
  4047. this.elapsedTime = 0;
  4048. this.running = false;
  4049. };
  4050. THREE.Clock.prototype = {
  4051. constructor: THREE.Clock,
  4052. start: function () {
  4053. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4054. ? self.performance.now()
  4055. : Date.now();
  4056. this.oldTime = this.startTime;
  4057. this.running = true;
  4058. },
  4059. stop: function () {
  4060. this.getElapsedTime();
  4061. this.running = false;
  4062. },
  4063. getElapsedTime: function () {
  4064. this.getDelta();
  4065. return this.elapsedTime;
  4066. },
  4067. getDelta: function () {
  4068. var diff = 0;
  4069. if ( this.autoStart && ! this.running ) {
  4070. this.start();
  4071. }
  4072. if ( this.running ) {
  4073. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4074. ? self.performance.now()
  4075. : Date.now();
  4076. diff = 0.001 * ( newTime - this.oldTime );
  4077. this.oldTime = newTime;
  4078. this.elapsedTime += diff;
  4079. }
  4080. return diff;
  4081. }
  4082. };
  4083. /**
  4084. * https://github.com/mrdoob/eventdispatcher.js/
  4085. */
  4086. THREE.EventDispatcher = function () {}
  4087. THREE.EventDispatcher.prototype = {
  4088. constructor: THREE.EventDispatcher,
  4089. apply: function ( object ) {
  4090. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4091. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4092. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4093. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4094. },
  4095. addEventListener: function ( type, listener ) {
  4096. if ( this._listeners === undefined ) this._listeners = {};
  4097. var listeners = this._listeners;
  4098. if ( listeners[ type ] === undefined ) {
  4099. listeners[ type ] = [];
  4100. }
  4101. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4102. listeners[ type ].push( listener );
  4103. }
  4104. },
  4105. hasEventListener: function ( type, listener ) {
  4106. if ( this._listeners === undefined ) return false;
  4107. var listeners = this._listeners;
  4108. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4109. return true;
  4110. }
  4111. return false;
  4112. },
  4113. removeEventListener: function ( type, listener ) {
  4114. if ( this._listeners === undefined ) return;
  4115. var listeners = this._listeners;
  4116. var listenerArray = listeners[ type ];
  4117. if ( listenerArray !== undefined ) {
  4118. var index = listenerArray.indexOf( listener );
  4119. if ( index !== - 1 ) {
  4120. listenerArray.splice( index, 1 );
  4121. }
  4122. }
  4123. },
  4124. dispatchEvent: function ( event ) {
  4125. if ( this._listeners === undefined ) return;
  4126. var listeners = this._listeners;
  4127. var listenerArray = listeners[ event.type ];
  4128. if ( listenerArray !== undefined ) {
  4129. event.target = this;
  4130. var array = [];
  4131. var length = listenerArray.length;
  4132. for ( var i = 0; i < length; i ++ ) {
  4133. array[ i ] = listenerArray[ i ];
  4134. }
  4135. for ( var i = 0; i < length; i ++ ) {
  4136. array[ i ].call( this, event );
  4137. }
  4138. }
  4139. }
  4140. };
  4141. /**
  4142. * @author mrdoob / http://mrdoob.com/
  4143. * @author bhouston / http://exocortex.com/
  4144. * @author stephomi / http://stephaneginier.com/
  4145. */
  4146. ( function ( THREE ) {
  4147. THREE.Raycaster = function ( origin, direction, near, far ) {
  4148. this.ray = new THREE.Ray( origin, direction );
  4149. // direction is assumed to be normalized (for accurate distance calculations)
  4150. this.near = near || 0;
  4151. this.far = far || Infinity;
  4152. };
  4153. var sphere = new THREE.Sphere();
  4154. var localRay = new THREE.Ray();
  4155. var facePlane = new THREE.Plane();
  4156. var intersectPoint = new THREE.Vector3();
  4157. var matrixPosition = new THREE.Vector3();
  4158. var inverseMatrix = new THREE.Matrix4();
  4159. var descSort = function ( a, b ) {
  4160. return a.distance - b.distance;
  4161. };
  4162. var vA = new THREE.Vector3();
  4163. var vB = new THREE.Vector3();
  4164. var vC = new THREE.Vector3();
  4165. var intersectObject = function ( object, raycaster, intersects ) {
  4166. if ( object instanceof THREE.Sprite ) {
  4167. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4168. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4169. if ( distance > object.scale.x ) {
  4170. return intersects;
  4171. }
  4172. intersects.push( {
  4173. distance: distance,
  4174. point: object.position,
  4175. face: null,
  4176. object: object
  4177. } );
  4178. } else if ( object instanceof THREE.LOD ) {
  4179. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4180. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4181. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4182. } else if ( object instanceof THREE.Mesh ) {
  4183. var geometry = object.geometry;
  4184. // Checking boundingSphere distance to ray
  4185. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4186. sphere.copy( geometry.boundingSphere );
  4187. sphere.applyMatrix4( object.matrixWorld );
  4188. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4189. return intersects;
  4190. }
  4191. // Check boundingBox before continuing
  4192. inverseMatrix.getInverse( object.matrixWorld );
  4193. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4194. if ( geometry.boundingBox !== null ) {
  4195. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4196. return intersects;
  4197. }
  4198. }
  4199. if ( geometry instanceof THREE.BufferGeometry ) {
  4200. var material = object.material;
  4201. if ( material === undefined ) return intersects;
  4202. var attributes = geometry.attributes;
  4203. var a, b, c;
  4204. var precision = raycaster.precision;
  4205. if ( attributes.index !== undefined ) {
  4206. var indices = attributes.index.array;
  4207. var positions = attributes.position.array;
  4208. var offsets = geometry.offsets;
  4209. if ( offsets.length === 0 ) {
  4210. offsets = [ { start: 0, count: positions.length, index: 0 } ];
  4211. }
  4212. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4213. var start = offsets[ oi ].start;
  4214. var count = offsets[ oi ].count;
  4215. var index = offsets[ oi ].index;
  4216. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4217. a = index + indices[ i ];
  4218. b = index + indices[ i + 1 ];
  4219. c = index + indices[ i + 2 ];
  4220. vA.set(
  4221. positions[ a * 3 ],
  4222. positions[ a * 3 + 1 ],
  4223. positions[ a * 3 + 2 ]
  4224. );
  4225. vB.set(
  4226. positions[ b * 3 ],
  4227. positions[ b * 3 + 1 ],
  4228. positions[ b * 3 + 2 ]
  4229. );
  4230. vC.set(
  4231. positions[ c * 3 ],
  4232. positions[ c * 3 + 1 ],
  4233. positions[ c * 3 + 2 ]
  4234. );
  4235. if ( material.side === THREE.BackSide ) {
  4236. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4237. } else {
  4238. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4239. }
  4240. if ( intersectionPoint === null ) continue;
  4241. intersectionPoint.applyMatrix4( object.matrixWorld );
  4242. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4243. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4244. intersects.push( {
  4245. distance: distance,
  4246. point: intersectionPoint,
  4247. indices: [a, b, c],
  4248. face: null,
  4249. faceIndex: null,
  4250. object: object
  4251. } );
  4252. }
  4253. }
  4254. } else {
  4255. var offsets = geometry.offsets;
  4256. var positions = attributes.position.array;
  4257. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4258. a = i;
  4259. b = i + 1;
  4260. c = i + 2;
  4261. vA.set(
  4262. positions[ a * 3 ],
  4263. positions[ a * 3 + 1 ],
  4264. positions[ a * 3 + 2 ]
  4265. );
  4266. vB.set(
  4267. positions[ b * 3 ],
  4268. positions[ b * 3 + 1 ],
  4269. positions[ b * 3 + 2 ]
  4270. );
  4271. vC.set(
  4272. positions[ c * 3 ],
  4273. positions[ c * 3 + 1 ],
  4274. positions[ c * 3 + 2 ]
  4275. );
  4276. if ( material.side === THREE.BackSide ) {
  4277. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4278. } else {
  4279. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4280. }
  4281. if ( intersectionPoint === null ) continue;
  4282. intersectionPoint.applyMatrix4( object.matrixWorld );
  4283. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4284. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4285. intersects.push( {
  4286. distance: distance,
  4287. point: intersectionPoint,
  4288. indices: [a, b, c],
  4289. face: null,
  4290. faceIndex: null,
  4291. object: object
  4292. } );
  4293. }
  4294. }
  4295. } else if ( geometry instanceof THREE.Geometry ) {
  4296. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4297. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4298. var a, b, c, d;
  4299. var precision = raycaster.precision;
  4300. var vertices = geometry.vertices;
  4301. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4302. var face = geometry.faces[ f ];
  4303. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4304. if ( material === undefined ) continue;
  4305. a = vertices[ face.a ];
  4306. b = vertices[ face.b ];
  4307. c = vertices[ face.c ];
  4308. if ( material.morphTargets === true ) {
  4309. var morphTargets = geometry.morphTargets;
  4310. var morphInfluences = object.morphTargetInfluences;
  4311. vA.set( 0, 0, 0 );
  4312. vB.set( 0, 0, 0 );
  4313. vC.set( 0, 0, 0 );
  4314. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4315. var influence = morphInfluences[ t ];
  4316. if ( influence === 0 ) continue;
  4317. var targets = morphTargets[ t ].vertices;
  4318. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4319. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4320. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4321. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4322. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4323. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4324. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4325. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4326. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4327. }
  4328. vA.add( a );
  4329. vB.add( b );
  4330. vC.add( c );
  4331. a = vA;
  4332. b = vB;
  4333. c = vC;
  4334. }
  4335. if ( material.side === THREE.BackSide ) {
  4336. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4337. } else {
  4338. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4339. }
  4340. if ( intersectionPoint === null ) continue;
  4341. intersectionPoint.applyMatrix4( object.matrixWorld );
  4342. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4343. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4344. intersects.push( {
  4345. distance: distance,
  4346. point: intersectionPoint,
  4347. face: face,
  4348. faceIndex: f,
  4349. object: object
  4350. } );
  4351. }
  4352. }
  4353. } else if ( object instanceof THREE.Line ) {
  4354. var precision = raycaster.linePrecision;
  4355. var precisionSq = precision * precision;
  4356. var geometry = object.geometry;
  4357. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4358. // Checking boundingSphere distance to ray
  4359. sphere.copy( geometry.boundingSphere );
  4360. sphere.applyMatrix4( object.matrixWorld );
  4361. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4362. return intersects;
  4363. }
  4364. inverseMatrix.getInverse( object.matrixWorld );
  4365. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4366. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4367. } else */ if ( geometry instanceof THREE.Geometry ) {
  4368. var vertices = geometry.vertices;
  4369. var nbVertices = vertices.length;
  4370. var interSegment = new THREE.Vector3();
  4371. var interRay = new THREE.Vector3();
  4372. var step = object.type === THREE.LineStrip ? 1 : 2;
  4373. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4374. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4375. if ( distSq > precisionSq ) continue;
  4376. var distance = localRay.origin.distanceTo( interRay );
  4377. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4378. intersects.push( {
  4379. distance: distance,
  4380. // What do we want? intersection point on the ray or on the segment??
  4381. // point: raycaster.ray.at( distance ),
  4382. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4383. face: null,
  4384. faceIndex: null,
  4385. object: object
  4386. } );
  4387. }
  4388. }
  4389. }
  4390. };
  4391. var intersectDescendants = function ( object, raycaster, intersects ) {
  4392. var descendants = object.getDescendants();
  4393. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4394. intersectObject( descendants[ i ], raycaster, intersects );
  4395. }
  4396. };
  4397. //
  4398. THREE.Raycaster.prototype.precision = 0.0001;
  4399. THREE.Raycaster.prototype.linePrecision = 1;
  4400. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4401. this.ray.set( origin, direction );
  4402. // direction is assumed to be normalized (for accurate distance calculations)
  4403. };
  4404. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4405. var intersects = [];
  4406. if ( recursive === true ) {
  4407. intersectDescendants( object, this, intersects );
  4408. }
  4409. intersectObject( object, this, intersects );
  4410. intersects.sort( descSort );
  4411. return intersects;
  4412. };
  4413. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4414. var intersects = [];
  4415. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4416. intersectObject( objects[ i ], this, intersects );
  4417. if ( recursive === true ) {
  4418. intersectDescendants( objects[ i ], this, intersects );
  4419. }
  4420. }
  4421. intersects.sort( descSort );
  4422. return intersects;
  4423. };
  4424. }( THREE ) );
  4425. /**
  4426. * @author mrdoob / http://mrdoob.com/
  4427. * @author mikael emtinger / http://gomo.se/
  4428. * @author alteredq / http://alteredqualia.com/
  4429. * @author WestLangley / http://github.com/WestLangley
  4430. */
  4431. THREE.Object3D = function () {
  4432. this.id = THREE.Object3DIdCount ++;
  4433. this.uuid = THREE.Math.generateUUID();
  4434. this.name = '';
  4435. this.parent = undefined;
  4436. this.children = [];
  4437. this.up = new THREE.Vector3( 0, 1, 0 );
  4438. this.position = new THREE.Vector3();
  4439. var scope = this;
  4440. Object.defineProperties( this, {
  4441. rotation: {
  4442. enumerable: true,
  4443. value: new THREE.Euler().onChange( function () {
  4444. scope.quaternion.setFromEuler( scope.rotation, false );
  4445. } )
  4446. },
  4447. quaternion: {
  4448. enumerable: true,
  4449. value: new THREE.Quaternion().onChange( function () {
  4450. scope.rotation.setFromQuaternion( scope.quaternion, undefined, false );
  4451. } )
  4452. },
  4453. scale: {
  4454. enumerable: true,
  4455. value: new THREE.Vector3( 1, 1, 1 )
  4456. }
  4457. } );
  4458. this.renderDepth = null;
  4459. this.rotationAutoUpdate = true;
  4460. this.matrix = new THREE.Matrix4();
  4461. this.matrixWorld = new THREE.Matrix4();
  4462. this.matrixAutoUpdate = true;
  4463. this.matrixWorldNeedsUpdate = false;
  4464. this.visible = true;
  4465. this.castShadow = false;
  4466. this.receiveShadow = false;
  4467. this.frustumCulled = true;
  4468. this.userData = {};
  4469. };
  4470. THREE.Object3D.prototype = {
  4471. constructor: THREE.Object3D,
  4472. get eulerOrder () {
  4473. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4474. return this.rotation.order;
  4475. },
  4476. set eulerOrder ( value ) {
  4477. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4478. this.rotation.order = value;
  4479. },
  4480. get useQuaternion () {
  4481. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4482. },
  4483. set useQuaternion ( value ) {
  4484. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4485. },
  4486. applyMatrix: function ( matrix ) {
  4487. this.matrix.multiplyMatrices( matrix, this.matrix );
  4488. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4489. },
  4490. setRotationFromAxisAngle: function ( axis, angle ) {
  4491. // assumes axis is normalized
  4492. this.quaternion.setFromAxisAngle( axis, angle );
  4493. },
  4494. setRotationFromEuler: function ( euler ) {
  4495. this.quaternion.setFromEuler( euler, true );
  4496. },
  4497. setRotationFromMatrix: function ( m ) {
  4498. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4499. this.quaternion.setFromRotationMatrix( m );
  4500. },
  4501. setRotationFromQuaternion: function ( q ) {
  4502. // assumes q is normalized
  4503. this.quaternion.copy( q );
  4504. },
  4505. rotateOnAxis: function() {
  4506. // rotate object on axis in object space
  4507. // axis is assumed to be normalized
  4508. var q1 = new THREE.Quaternion();
  4509. return function ( axis, angle ) {
  4510. q1.setFromAxisAngle( axis, angle );
  4511. this.quaternion.multiply( q1 );
  4512. return this;
  4513. }
  4514. }(),
  4515. rotateX: function () {
  4516. var v1 = new THREE.Vector3( 1, 0, 0 );
  4517. return function ( angle ) {
  4518. return this.rotateOnAxis( v1, angle );
  4519. };
  4520. }(),
  4521. rotateY: function () {
  4522. var v1 = new THREE.Vector3( 0, 1, 0 );
  4523. return function ( angle ) {
  4524. return this.rotateOnAxis( v1, angle );
  4525. };
  4526. }(),
  4527. rotateZ: function () {
  4528. var v1 = new THREE.Vector3( 0, 0, 1 );
  4529. return function ( angle ) {
  4530. return this.rotateOnAxis( v1, angle );
  4531. };
  4532. }(),
  4533. translateOnAxis: function () {
  4534. // translate object by distance along axis in object space
  4535. // axis is assumed to be normalized
  4536. var v1 = new THREE.Vector3();
  4537. return function ( axis, distance ) {
  4538. v1.copy( axis );
  4539. v1.applyQuaternion( this.quaternion );
  4540. this.position.add( v1.multiplyScalar( distance ) );
  4541. return this;
  4542. }
  4543. }(),
  4544. translate: function ( distance, axis ) {
  4545. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4546. return this.translateOnAxis( axis, distance );
  4547. },
  4548. translateX: function () {
  4549. var v1 = new THREE.Vector3( 1, 0, 0 );
  4550. return function ( distance ) {
  4551. return this.translateOnAxis( v1, distance );
  4552. };
  4553. }(),
  4554. translateY: function () {
  4555. var v1 = new THREE.Vector3( 0, 1, 0 );
  4556. return function ( distance ) {
  4557. return this.translateOnAxis( v1, distance );
  4558. };
  4559. }(),
  4560. translateZ: function () {
  4561. var v1 = new THREE.Vector3( 0, 0, 1 );
  4562. return function ( distance ) {
  4563. return this.translateOnAxis( v1, distance );
  4564. };
  4565. }(),
  4566. localToWorld: function ( vector ) {
  4567. return vector.applyMatrix4( this.matrixWorld );
  4568. },
  4569. worldToLocal: function () {
  4570. var m1 = new THREE.Matrix4();
  4571. return function ( vector ) {
  4572. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4573. };
  4574. }(),
  4575. lookAt: function () {
  4576. // This routine does not support objects with rotated and/or translated parent(s)
  4577. var m1 = new THREE.Matrix4();
  4578. return function ( vector ) {
  4579. m1.lookAt( vector, this.position, this.up );
  4580. this.quaternion.setFromRotationMatrix( m1 );
  4581. };
  4582. }(),
  4583. add: function ( object ) {
  4584. if ( object === this ) {
  4585. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4586. return;
  4587. }
  4588. if ( object instanceof THREE.Object3D ) {
  4589. if ( object.parent !== undefined ) {
  4590. object.parent.remove( object );
  4591. }
  4592. object.parent = this;
  4593. object.dispatchEvent( { type: 'added' } );
  4594. this.children.push( object );
  4595. // add to scene
  4596. var scene = this;
  4597. while ( scene.parent !== undefined ) {
  4598. scene = scene.parent;
  4599. }
  4600. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4601. scene.__addObject( object );
  4602. }
  4603. }
  4604. },
  4605. remove: function ( object ) {
  4606. var index = this.children.indexOf( object );
  4607. if ( index !== - 1 ) {
  4608. object.parent = undefined;
  4609. object.dispatchEvent( { type: 'removed' } );
  4610. this.children.splice( index, 1 );
  4611. // remove from scene
  4612. var scene = this;
  4613. while ( scene.parent !== undefined ) {
  4614. scene = scene.parent;
  4615. }
  4616. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4617. scene.__removeObject( object );
  4618. }
  4619. }
  4620. },
  4621. traverse: function ( callback ) {
  4622. callback( this );
  4623. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4624. this.children[ i ].traverse( callback );
  4625. }
  4626. },
  4627. getObjectById: function ( id, recursive ) {
  4628. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4629. var child = this.children[ i ];
  4630. if ( child.id === id ) {
  4631. return child;
  4632. }
  4633. if ( recursive === true ) {
  4634. child = child.getObjectById( id, recursive );
  4635. if ( child !== undefined ) {
  4636. return child;
  4637. }
  4638. }
  4639. }
  4640. return undefined;
  4641. },
  4642. getObjectByName: function ( name, recursive ) {
  4643. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4644. var child = this.children[ i ];
  4645. if ( child.name === name ) {
  4646. return child;
  4647. }
  4648. if ( recursive === true ) {
  4649. child = child.getObjectByName( name, recursive );
  4650. if ( child !== undefined ) {
  4651. return child;
  4652. }
  4653. }
  4654. }
  4655. return undefined;
  4656. },
  4657. getChildByName: function ( name, recursive ) {
  4658. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4659. return this.getObjectByName( name, recursive );
  4660. },
  4661. getDescendants: function ( array ) {
  4662. if ( array === undefined ) array = [];
  4663. Array.prototype.push.apply( array, this.children );
  4664. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4665. this.children[ i ].getDescendants( array );
  4666. }
  4667. return array;
  4668. },
  4669. updateMatrix: function () {
  4670. this.matrix.compose( this.position, this.quaternion, this.scale );
  4671. this.matrixWorldNeedsUpdate = true;
  4672. },
  4673. updateMatrixWorld: function ( force ) {
  4674. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4675. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4676. if ( this.parent === undefined ) {
  4677. this.matrixWorld.copy( this.matrix );
  4678. } else {
  4679. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4680. }
  4681. this.matrixWorldNeedsUpdate = false;
  4682. force = true;
  4683. }
  4684. // update children
  4685. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4686. this.children[ i ].updateMatrixWorld( force );
  4687. }
  4688. },
  4689. clone: function ( object, recursive ) {
  4690. if ( object === undefined ) object = new THREE.Object3D();
  4691. if ( recursive === undefined ) recursive = true;
  4692. object.name = this.name;
  4693. object.up.copy( this.up );
  4694. object.position.copy( this.position );
  4695. object.quaternion.copy( this.quaternion );
  4696. object.scale.copy( this.scale );
  4697. object.renderDepth = this.renderDepth;
  4698. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4699. object.matrix.copy( this.matrix );
  4700. object.matrixWorld.copy( this.matrixWorld );
  4701. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4702. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4703. object.visible = this.visible;
  4704. object.castShadow = this.castShadow;
  4705. object.receiveShadow = this.receiveShadow;
  4706. object.frustumCulled = this.frustumCulled;
  4707. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4708. if ( recursive === true ) {
  4709. for ( var i = 0; i < this.children.length; i ++ ) {
  4710. var child = this.children[ i ];
  4711. object.add( child.clone() );
  4712. }
  4713. }
  4714. return object;
  4715. }
  4716. };
  4717. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4718. THREE.Object3DIdCount = 0;
  4719. /**
  4720. * @author mrdoob / http://mrdoob.com/
  4721. * @author supereggbert / http://www.paulbrunt.co.uk/
  4722. * @author julianwa / https://github.com/julianwa
  4723. */
  4724. THREE.Projector = function () {
  4725. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4726. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4727. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4728. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4729. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4730. _renderData = { objects: [], lights: [], elements: [] },
  4731. _vA = new THREE.Vector3(),
  4732. _vB = new THREE.Vector3(),
  4733. _vC = new THREE.Vector3(),
  4734. _vector3 = new THREE.Vector3(),
  4735. _vector4 = new THREE.Vector4(),
  4736. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4737. _boundingBox = new THREE.Box3(),
  4738. _points3 = new Array( 3 ),
  4739. _points4 = new Array( 4 ),
  4740. _viewMatrix = new THREE.Matrix4(),
  4741. _viewProjectionMatrix = new THREE.Matrix4(),
  4742. _modelMatrix,
  4743. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4744. _normalMatrix = new THREE.Matrix3(),
  4745. _frustum = new THREE.Frustum(),
  4746. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4747. _clippedVertex2PositionScreen = new THREE.Vector4();
  4748. this.projectVector = function ( vector, camera ) {
  4749. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4750. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4751. return vector.applyProjection( _viewProjectionMatrix );
  4752. };
  4753. this.unprojectVector = function () {
  4754. var projectionMatrixInverse = new THREE.Matrix4();
  4755. return function ( vector, camera ) {
  4756. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4757. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4758. return vector.applyProjection( _viewProjectionMatrix );
  4759. };
  4760. }();
  4761. this.pickingRay = function ( vector, camera ) {
  4762. // set two vectors with opposing z values
  4763. vector.z = -1.0;
  4764. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4765. this.unprojectVector( vector, camera );
  4766. this.unprojectVector( end, camera );
  4767. // find direction from vector to end
  4768. end.sub( vector ).normalize();
  4769. return new THREE.Raycaster( vector, end );
  4770. };
  4771. var projectObject = function ( object ) {
  4772. if ( object.visible === false ) return;
  4773. if ( object instanceof THREE.Light ) {
  4774. _renderData.lights.push( object );
  4775. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4776. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4777. _object = getNextObjectInPool();
  4778. _object.id = object.id;
  4779. _object.object = object;
  4780. if ( object.renderDepth !== null ) {
  4781. _object.z = object.renderDepth;
  4782. } else {
  4783. _vector3.setFromMatrixPosition( object.matrixWorld );
  4784. _vector3.applyProjection( _viewProjectionMatrix );
  4785. _object.z = _vector3.z;
  4786. }
  4787. _renderData.objects.push( _object );
  4788. }
  4789. }
  4790. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4791. projectObject( object.children[ i ] );
  4792. }
  4793. };
  4794. var projectGraph = function ( root, sortObjects ) {
  4795. _objectCount = 0;
  4796. _renderData.objects.length = 0;
  4797. _renderData.lights.length = 0;
  4798. projectObject( root );
  4799. if ( sortObjects === true ) {
  4800. _renderData.objects.sort( painterSort );
  4801. }
  4802. };
  4803. var RenderList = function () {
  4804. var normals = [];
  4805. var uvs = [];
  4806. var object = null;
  4807. var material = null;
  4808. var normalMatrix = new THREE.Matrix3();
  4809. var setObject = function ( value ) {
  4810. object = value;
  4811. material = object.material;
  4812. normalMatrix.getNormalMatrix( object.matrixWorld );
  4813. normals.length = 0;
  4814. uvs.length = 0;
  4815. };
  4816. var projectVertex = function ( vertex ) {
  4817. var position = vertex.position;
  4818. var positionWorld = vertex.positionWorld;
  4819. var positionScreen = vertex.positionScreen;
  4820. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4821. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4822. var invW = 1 / positionScreen.w;
  4823. positionScreen.x *= invW;
  4824. positionScreen.y *= invW;
  4825. positionScreen.z *= invW;
  4826. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4827. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4828. positionScreen.z >= -1 && positionScreen.z <= 1;
  4829. };
  4830. var pushVertex = function ( x, y, z ) {
  4831. _vertex = getNextVertexInPool();
  4832. _vertex.position.set( x, y, z );
  4833. projectVertex( _vertex );
  4834. };
  4835. var pushNormal = function ( x, y, z ) {
  4836. normals.push( x, y, z );
  4837. };
  4838. var pushUv = function ( x, y ) {
  4839. uvs.push( x, y );
  4840. };
  4841. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4842. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4843. _points3[ 0 ] = v1.positionScreen;
  4844. _points3[ 1 ] = v2.positionScreen;
  4845. _points3[ 2 ] = v3.positionScreen;
  4846. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4847. };
  4848. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4849. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4850. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4851. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4852. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4853. };
  4854. var pushLine = function ( a, b ) {
  4855. var v1 = _vertexPool[ a ];
  4856. var v2 = _vertexPool[ b ];
  4857. _line = getNextLineInPool();
  4858. _line.id = object.id;
  4859. _line.v1.copy( v1 );
  4860. _line.v2.copy( v2 );
  4861. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4862. _line.material = object.material;
  4863. _renderData.elements.push( _line );
  4864. };
  4865. var pushTriangle = function ( a, b, c ) {
  4866. var v1 = _vertexPool[ a ];
  4867. var v2 = _vertexPool[ b ];
  4868. var v3 = _vertexPool[ c ];
  4869. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4870. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4871. _face = getNextFaceInPool();
  4872. _face.id = object.id;
  4873. _face.v1.copy( v1 );
  4874. _face.v2.copy( v2 );
  4875. _face.v3.copy( v3 );
  4876. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4877. for ( var i = 0; i < 3; i ++ ) {
  4878. var offset = arguments[ i ] * 3;
  4879. var normal = _face.vertexNormalsModel[ i ];
  4880. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4881. normal.applyMatrix3( normalMatrix ).normalize();
  4882. var offset2 = arguments[ i ] * 2;
  4883. var uv = _face.uvs[ i ];
  4884. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4885. }
  4886. _face.vertexNormalsLength = 3;
  4887. _face.material = object.material;
  4888. _renderData.elements.push( _face );
  4889. }
  4890. };
  4891. return {
  4892. setObject: setObject,
  4893. projectVertex: projectVertex,
  4894. checkTriangleVisibility: checkTriangleVisibility,
  4895. checkBackfaceCulling: checkBackfaceCulling,
  4896. pushVertex: pushVertex,
  4897. pushNormal: pushNormal,
  4898. pushUv: pushUv,
  4899. pushLine: pushLine,
  4900. pushTriangle: pushTriangle
  4901. }
  4902. };
  4903. var renderList = new RenderList();
  4904. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4905. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4906. isFaceMaterial, objectMaterials;
  4907. _faceCount = 0;
  4908. _lineCount = 0;
  4909. _spriteCount = 0;
  4910. _renderData.elements.length = 0;
  4911. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4912. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4913. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4914. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4915. _frustum.setFromMatrix( _viewProjectionMatrix );
  4916. projectGraph( scene, sortObjects );
  4917. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4918. object = _renderData.objects[ o ].object;
  4919. geometry = object.geometry;
  4920. renderList.setObject( object );
  4921. _modelMatrix = object.matrixWorld;
  4922. _vertexCount = 0;
  4923. if ( object instanceof THREE.Mesh ) {
  4924. if ( geometry instanceof THREE.BufferGeometry ) {
  4925. var attributes = geometry.attributes;
  4926. var offsets = geometry.offsets;
  4927. if ( attributes.position === undefined ) continue;
  4928. var positions = attributes.position.array;
  4929. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4930. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4931. }
  4932. if ( attributes.normal !== undefined ) {
  4933. var normals = attributes.normal.array;
  4934. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4935. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4936. }
  4937. }
  4938. if ( attributes.uv !== undefined ) {
  4939. var uvs = attributes.uv.array;
  4940. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4941. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4942. }
  4943. }
  4944. if ( attributes.index !== undefined ) {
  4945. var indices = attributes.index.array;
  4946. if ( offsets.length > 0 ) {
  4947. for ( var o = 0; o < offsets.length; o ++ ) {
  4948. var offset = offsets[ o ];
  4949. var index = offset.index;
  4950. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4951. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4952. }
  4953. }
  4954. } else {
  4955. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4956. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4957. }
  4958. }
  4959. } else {
  4960. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4961. renderList.pushTriangle( i, i + 1, i + 2 );
  4962. }
  4963. }
  4964. } else if ( geometry instanceof THREE.Geometry ) {
  4965. vertices = geometry.vertices;
  4966. faces = geometry.faces;
  4967. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4968. _normalMatrix.getNormalMatrix( _modelMatrix );
  4969. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4970. objectMaterials = isFaceMaterial === true ? object.material : null;
  4971. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4972. var vertex = vertices[ v ];
  4973. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4974. }
  4975. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4976. face = faces[ f ];
  4977. var material = isFaceMaterial === true
  4978. ? objectMaterials.materials[ face.materialIndex ]
  4979. : object.material;
  4980. if ( material === undefined ) continue;
  4981. var side = material.side;
  4982. var v1 = _vertexPool[ face.a ];
  4983. var v2 = _vertexPool[ face.b ];
  4984. var v3 = _vertexPool[ face.c ];
  4985. if ( material.morphTargets === true ) {
  4986. var morphTargets = geometry.morphTargets;
  4987. var morphInfluences = object.morphTargetInfluences;
  4988. var v1p = v1.position;
  4989. var v2p = v2.position;
  4990. var v3p = v3.position;
  4991. _vA.set( 0, 0, 0 );
  4992. _vB.set( 0, 0, 0 );
  4993. _vC.set( 0, 0, 0 );
  4994. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4995. var influence = morphInfluences[ t ];
  4996. if ( influence === 0 ) continue;
  4997. var targets = morphTargets[ t ].vertices;
  4998. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4999. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  5000. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  5001. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  5002. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  5003. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  5004. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  5005. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  5006. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  5007. }
  5008. v1.position.add( _vA );
  5009. v2.position.add( _vB );
  5010. v3.position.add( _vC );
  5011. renderList.projectVertex( v1 );
  5012. renderList.projectVertex( v2 );
  5013. renderList.projectVertex( v3 );
  5014. }
  5015. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  5016. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  5017. if ( side !== THREE.DoubleSide ) {
  5018. if ( side === THREE.FrontSide && visible === false ) continue;
  5019. if ( side === THREE.BackSide && visible === true ) continue;
  5020. }
  5021. _face = getNextFaceInPool();
  5022. _face.id = object.id;
  5023. _face.v1.copy( v1 );
  5024. _face.v2.copy( v2 );
  5025. _face.v3.copy( v3 );
  5026. _face.normalModel.copy( face.normal );
  5027. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5028. _face.normalModel.negate();
  5029. }
  5030. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  5031. faceVertexNormals = face.vertexNormals;
  5032. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  5033. var normalModel = _face.vertexNormalsModel[ n ];
  5034. normalModel.copy( faceVertexNormals[ n ] );
  5035. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5036. normalModel.negate();
  5037. }
  5038. normalModel.applyMatrix3( _normalMatrix ).normalize();
  5039. }
  5040. _face.vertexNormalsLength = faceVertexNormals.length;
  5041. var vertexUvs = faceVertexUvs[ f ];
  5042. if ( vertexUvs !== undefined ) {
  5043. for ( var u = 0; u < 3; u ++ ) {
  5044. _face.uvs[ u ].copy( vertexUvs[ u ] );
  5045. }
  5046. }
  5047. _face.color = face.color;
  5048. _face.material = material;
  5049. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5050. _renderData.elements.push( _face );
  5051. }
  5052. }
  5053. } else if ( object instanceof THREE.Line ) {
  5054. if ( geometry instanceof THREE.BufferGeometry ) {
  5055. var attributes = geometry.attributes;
  5056. if ( attributes.position !== undefined ) {
  5057. var positions = attributes.position.array;
  5058. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5059. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5060. }
  5061. if ( attributes.index !== undefined ) {
  5062. var indices = attributes.index.array;
  5063. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5064. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5065. }
  5066. } else {
  5067. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5068. renderList.pushLine( i, i + 1 );
  5069. }
  5070. }
  5071. }
  5072. } else if ( geometry instanceof THREE.Geometry ) {
  5073. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5074. vertices = object.geometry.vertices;
  5075. if ( vertices.length === 0 ) continue;
  5076. v1 = getNextVertexInPool();
  5077. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5078. // Handle LineStrip and LinePieces
  5079. var step = object.type === THREE.LinePieces ? 2 : 1;
  5080. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5081. v1 = getNextVertexInPool();
  5082. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5083. if ( ( v + 1 ) % step > 0 ) continue;
  5084. v2 = _vertexPool[ _vertexCount - 2 ];
  5085. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5086. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5087. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5088. // Perform the perspective divide
  5089. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5090. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5091. _line = getNextLineInPool();
  5092. _line.id = object.id;
  5093. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5094. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5095. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5096. _line.material = object.material;
  5097. if ( object.material.vertexColors === THREE.VertexColors ) {
  5098. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5099. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5100. }
  5101. _renderData.elements.push( _line );
  5102. }
  5103. }
  5104. }
  5105. } else if ( object instanceof THREE.Sprite ) {
  5106. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5107. _vector4.applyMatrix4( _viewProjectionMatrix );
  5108. var invW = 1 / _vector4.w;
  5109. _vector4.z *= invW;
  5110. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5111. _sprite = getNextSpriteInPool();
  5112. _sprite.id = object.id;
  5113. _sprite.x = _vector4.x * invW;
  5114. _sprite.y = _vector4.y * invW;
  5115. _sprite.z = _vector4.z;
  5116. _sprite.object = object;
  5117. _sprite.rotation = object.rotation;
  5118. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5119. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5120. _sprite.material = object.material;
  5121. _renderData.elements.push( _sprite );
  5122. }
  5123. }
  5124. }
  5125. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5126. return _renderData;
  5127. };
  5128. // Pools
  5129. function getNextObjectInPool() {
  5130. if ( _objectCount === _objectPoolLength ) {
  5131. var object = new THREE.RenderableObject();
  5132. _objectPool.push( object );
  5133. _objectPoolLength ++;
  5134. _objectCount ++;
  5135. return object;
  5136. }
  5137. return _objectPool[ _objectCount ++ ];
  5138. }
  5139. function getNextVertexInPool() {
  5140. if ( _vertexCount === _vertexPoolLength ) {
  5141. var vertex = new THREE.RenderableVertex();
  5142. _vertexPool.push( vertex );
  5143. _vertexPoolLength ++;
  5144. _vertexCount ++;
  5145. return vertex;
  5146. }
  5147. return _vertexPool[ _vertexCount ++ ];
  5148. }
  5149. function getNextFaceInPool() {
  5150. if ( _faceCount === _facePoolLength ) {
  5151. var face = new THREE.RenderableFace();
  5152. _facePool.push( face );
  5153. _facePoolLength ++;
  5154. _faceCount ++;
  5155. return face;
  5156. }
  5157. return _facePool[ _faceCount ++ ];
  5158. }
  5159. function getNextLineInPool() {
  5160. if ( _lineCount === _linePoolLength ) {
  5161. var line = new THREE.RenderableLine();
  5162. _linePool.push( line );
  5163. _linePoolLength ++;
  5164. _lineCount ++
  5165. return line;
  5166. }
  5167. return _linePool[ _lineCount ++ ];
  5168. }
  5169. function getNextSpriteInPool() {
  5170. if ( _spriteCount === _spritePoolLength ) {
  5171. var sprite = new THREE.RenderableSprite();
  5172. _spritePool.push( sprite );
  5173. _spritePoolLength ++;
  5174. _spriteCount ++
  5175. return sprite;
  5176. }
  5177. return _spritePool[ _spriteCount ++ ];
  5178. }
  5179. //
  5180. function painterSort( a, b ) {
  5181. if ( a.z !== b.z ) {
  5182. return b.z - a.z;
  5183. } else if ( a.id !== b.id ) {
  5184. return a.id - b.id;
  5185. } else {
  5186. return 0;
  5187. }
  5188. }
  5189. function clipLine( s1, s2 ) {
  5190. var alpha1 = 0, alpha2 = 1,
  5191. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5192. // Z = -1 and Z = +1, respectively.
  5193. bc1near = s1.z + s1.w,
  5194. bc2near = s2.z + s2.w,
  5195. bc1far = - s1.z + s1.w,
  5196. bc2far = - s2.z + s2.w;
  5197. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5198. // Both vertices lie entirely within all clip planes.
  5199. return true;
  5200. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5201. // Both vertices lie entirely outside one of the clip planes.
  5202. return false;
  5203. } else {
  5204. // The line segment spans at least one clip plane.
  5205. if ( bc1near < 0 ) {
  5206. // v1 lies outside the near plane, v2 inside
  5207. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5208. } else if ( bc2near < 0 ) {
  5209. // v2 lies outside the near plane, v1 inside
  5210. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5211. }
  5212. if ( bc1far < 0 ) {
  5213. // v1 lies outside the far plane, v2 inside
  5214. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5215. } else if ( bc2far < 0 ) {
  5216. // v2 lies outside the far plane, v2 inside
  5217. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5218. }
  5219. if ( alpha2 < alpha1 ) {
  5220. // The line segment spans two boundaries, but is outside both of them.
  5221. // (This can't happen when we're only clipping against just near/far but good
  5222. // to leave the check here for future usage if other clip planes are added.)
  5223. return false;
  5224. } else {
  5225. // Update the s1 and s2 vertices to match the clipped line segment.
  5226. s1.lerp( s2, alpha1 );
  5227. s2.lerp( s1, 1 - alpha2 );
  5228. return true;
  5229. }
  5230. }
  5231. }
  5232. };
  5233. /**
  5234. * @author mrdoob / http://mrdoob.com/
  5235. * @author alteredq / http://alteredqualia.com/
  5236. */
  5237. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5238. this.a = a;
  5239. this.b = b;
  5240. this.c = c;
  5241. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5242. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5243. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5244. this.vertexColors = color instanceof Array ? color : [];
  5245. this.vertexTangents = [];
  5246. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5247. };
  5248. THREE.Face3.prototype = {
  5249. constructor: THREE.Face3,
  5250. clone: function () {
  5251. var face = new THREE.Face3( this.a, this.b, this.c );
  5252. face.normal.copy( this.normal );
  5253. face.color.copy( this.color );
  5254. face.materialIndex = this.materialIndex;
  5255. var i, il;
  5256. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5257. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5258. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5259. return face;
  5260. }
  5261. };
  5262. /**
  5263. * @author mrdoob / http://mrdoob.com/
  5264. */
  5265. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5266. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5267. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5268. };
  5269. /**
  5270. * @author mrdoob / http://mrdoob.com/
  5271. */
  5272. THREE.BufferAttribute = function () {};
  5273. THREE.BufferAttribute.prototype = {
  5274. constructor: THREE.BufferAttribute,
  5275. get length () {
  5276. return this.array.length;
  5277. },
  5278. set: function ( value ) {
  5279. this.array.set( value );
  5280. },
  5281. setX: function ( index, x ) {
  5282. this.array[ index * this.itemSize ] = x;
  5283. },
  5284. setY: function ( index, y ) {
  5285. this.array[ index * this.itemSize + 1 ] = y;
  5286. },
  5287. setZ: function ( index, z ) {
  5288. this.array[ index * this.itemSize + 2 ] = z;
  5289. },
  5290. setXY: function ( index, x, y ) {
  5291. index *= this.itemSize;
  5292. this.array[ index ] = x;
  5293. this.array[ index + 1 ] = y;
  5294. },
  5295. setXYZ: function ( index, x, y, z ) {
  5296. index *= this.itemSize;
  5297. this.array[ index ] = x;
  5298. this.array[ index + 1 ] = y;
  5299. this.array[ index + 2 ] = z;
  5300. },
  5301. setXYZW: function ( index, x, y, z, w ) {
  5302. index *= this.itemSize;
  5303. this.array[ index ] = x;
  5304. this.array[ index + 1 ] = y;
  5305. this.array[ index + 2 ] = z;
  5306. this.array[ index + 3 ] = w;
  5307. }
  5308. };
  5309. //
  5310. THREE.Int8Attribute = function ( size, itemSize ) {
  5311. this.array = new Int8Array( size * itemSize );
  5312. this.itemSize = itemSize;
  5313. };
  5314. THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5315. THREE.Uint8Attribute = function ( size, itemSize ) {
  5316. this.array = new Uint8Array( size * itemSize );
  5317. this.itemSize = itemSize;
  5318. };
  5319. THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5320. THREE.Uint8ClampedAttribute = function ( size, itemSize ) {
  5321. this.array = new Uint8ClampedArray( size * itemSize );
  5322. this.itemSize = itemSize;
  5323. };
  5324. THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5325. THREE.Int16Attribute = function ( size, itemSize ) {
  5326. this.array = new Int16Array( size * itemSize );
  5327. this.itemSize = itemSize;
  5328. };
  5329. THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5330. THREE.Uint16Attribute = function ( size, itemSize ) {
  5331. this.array = new Uint16Array( size * itemSize );
  5332. this.itemSize = itemSize;
  5333. };
  5334. THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5335. THREE.Int32Attribute = function ( size, itemSize ) {
  5336. this.array = new Int32Array( size * itemSize );
  5337. this.itemSize = itemSize;
  5338. };
  5339. THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5340. THREE.Uint32Attribute = function ( size, itemSize ) {
  5341. this.array = new Uint32Array( size * itemSize );
  5342. this.itemSize = itemSize;
  5343. };
  5344. THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5345. THREE.Float32Attribute = function ( size, itemSize ) {
  5346. this.array = new Float32Array( size * itemSize );
  5347. this.itemSize = itemSize;
  5348. };
  5349. THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5350. THREE.Float64Attribute = function ( size, itemSize ) {
  5351. this.array = new Float64Array( size * itemSize );
  5352. this.itemSize = itemSize;
  5353. };
  5354. THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5355. /**
  5356. * @author alteredq / http://alteredqualia.com/
  5357. */
  5358. THREE.BufferGeometry = function () {
  5359. this.id = THREE.GeometryIdCount ++;
  5360. this.uuid = THREE.Math.generateUUID();
  5361. this.name = '';
  5362. this.attributes = {};
  5363. this.drawcalls = [];
  5364. this.offsets = this.drawcalls; // backwards compatibility
  5365. this.boundingBox = null;
  5366. this.boundingSphere = null;
  5367. };
  5368. THREE.BufferGeometry.prototype = {
  5369. constructor: THREE.BufferGeometry,
  5370. addAttribute: function ( name, attribute ) {
  5371. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5372. console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' );
  5373. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5374. return;
  5375. }
  5376. this.attributes[ name ] = attribute;
  5377. },
  5378. getAttribute: function ( name ) {
  5379. return this.attributes[ name ];
  5380. },
  5381. addDrawCall: function ( start, count, indexOffset ) {
  5382. this.drawcalls.push( {
  5383. start: start,
  5384. count: count,
  5385. index: indexOffset !== undefined ? indexOffset : 0
  5386. } );
  5387. },
  5388. applyMatrix: function ( matrix ) {
  5389. var position = this.attributes.position;
  5390. if ( position !== undefined ) {
  5391. matrix.applyToVector3Array( position.array );
  5392. position.needsUpdate = true;
  5393. }
  5394. var normal = this.attributes.normal;
  5395. if ( normal !== undefined ) {
  5396. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5397. normalMatrix.applyToVector3Array( normal.array );
  5398. normal.needsUpdate = true;
  5399. }
  5400. },
  5401. computeBoundingBox: function () {
  5402. if ( this.boundingBox === null ) {
  5403. this.boundingBox = new THREE.Box3();
  5404. }
  5405. var positions = this.attributes[ "position" ].array;
  5406. if ( positions ) {
  5407. var bb = this.boundingBox;
  5408. if( positions.length >= 3 ) {
  5409. bb.min.x = bb.max.x = positions[ 0 ];
  5410. bb.min.y = bb.max.y = positions[ 1 ];
  5411. bb.min.z = bb.max.z = positions[ 2 ];
  5412. }
  5413. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5414. var x = positions[ i ];
  5415. var y = positions[ i + 1 ];
  5416. var z = positions[ i + 2 ];
  5417. // bounding box
  5418. if ( x < bb.min.x ) {
  5419. bb.min.x = x;
  5420. } else if ( x > bb.max.x ) {
  5421. bb.max.x = x;
  5422. }
  5423. if ( y < bb.min.y ) {
  5424. bb.min.y = y;
  5425. } else if ( y > bb.max.y ) {
  5426. bb.max.y = y;
  5427. }
  5428. if ( z < bb.min.z ) {
  5429. bb.min.z = z;
  5430. } else if ( z > bb.max.z ) {
  5431. bb.max.z = z;
  5432. }
  5433. }
  5434. }
  5435. if ( positions === undefined || positions.length === 0 ) {
  5436. this.boundingBox.min.set( 0, 0, 0 );
  5437. this.boundingBox.max.set( 0, 0, 0 );
  5438. }
  5439. },
  5440. computeBoundingSphere: function () {
  5441. var box = new THREE.Box3();
  5442. var vector = new THREE.Vector3();
  5443. return function () {
  5444. if ( this.boundingSphere === null ) {
  5445. this.boundingSphere = new THREE.Sphere();
  5446. }
  5447. var positions = this.attributes[ "position" ].array;
  5448. if ( positions ) {
  5449. box.makeEmpty();
  5450. var center = this.boundingSphere.center;
  5451. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5452. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5453. box.addPoint( vector );
  5454. }
  5455. box.center( center );
  5456. // hoping to find a boundingSphere with a radius smaller than the
  5457. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5458. var maxRadiusSq = 0;
  5459. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5460. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5461. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5462. }
  5463. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5464. }
  5465. }
  5466. }(),
  5467. computeFaceNormals: function () {
  5468. // backwards compatibility
  5469. },
  5470. computeVertexNormals: function () {
  5471. if ( this.attributes[ "position" ] ) {
  5472. var i, il;
  5473. var j, jl;
  5474. var nVertexElements = this.attributes[ "position" ].array.length;
  5475. if ( this.attributes[ "normal" ] === undefined ) {
  5476. this.attributes[ "normal" ] = {
  5477. itemSize: 3,
  5478. array: new Float32Array( nVertexElements )
  5479. };
  5480. } else {
  5481. // reset existing normals to zero
  5482. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5483. this.attributes[ "normal" ].array[ i ] = 0;
  5484. }
  5485. }
  5486. var positions = this.attributes[ "position" ].array;
  5487. var normals = this.attributes[ "normal" ].array;
  5488. var vA, vB, vC, x, y, z,
  5489. pA = new THREE.Vector3(),
  5490. pB = new THREE.Vector3(),
  5491. pC = new THREE.Vector3(),
  5492. cb = new THREE.Vector3(),
  5493. ab = new THREE.Vector3();
  5494. // indexed elements
  5495. if ( this.attributes[ "index" ] ) {
  5496. var indices = this.attributes[ "index" ].array;
  5497. var offsets = (this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ]);
  5498. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5499. var start = offsets[ j ].start;
  5500. var count = offsets[ j ].count;
  5501. var index = offsets[ j ].index;
  5502. for ( i = start, il = start + count; i < il; i += 3 ) {
  5503. vA = index + indices[ i ];
  5504. vB = index + indices[ i + 1 ];
  5505. vC = index + indices[ i + 2 ];
  5506. x = positions[ vA * 3 ];
  5507. y = positions[ vA * 3 + 1 ];
  5508. z = positions[ vA * 3 + 2 ];
  5509. pA.set( x, y, z );
  5510. x = positions[ vB * 3 ];
  5511. y = positions[ vB * 3 + 1 ];
  5512. z = positions[ vB * 3 + 2 ];
  5513. pB.set( x, y, z );
  5514. x = positions[ vC * 3 ];
  5515. y = positions[ vC * 3 + 1 ];
  5516. z = positions[ vC * 3 + 2 ];
  5517. pC.set( x, y, z );
  5518. cb.subVectors( pC, pB );
  5519. ab.subVectors( pA, pB );
  5520. cb.cross( ab );
  5521. normals[ vA * 3 ] += cb.x;
  5522. normals[ vA * 3 + 1 ] += cb.y;
  5523. normals[ vA * 3 + 2 ] += cb.z;
  5524. normals[ vB * 3 ] += cb.x;
  5525. normals[ vB * 3 + 1 ] += cb.y;
  5526. normals[ vB * 3 + 2 ] += cb.z;
  5527. normals[ vC * 3 ] += cb.x;
  5528. normals[ vC * 3 + 1 ] += cb.y;
  5529. normals[ vC * 3 + 2 ] += cb.z;
  5530. }
  5531. }
  5532. // non-indexed elements (unconnected triangle soup)
  5533. } else {
  5534. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5535. x = positions[ i ];
  5536. y = positions[ i + 1 ];
  5537. z = positions[ i + 2 ];
  5538. pA.set( x, y, z );
  5539. x = positions[ i + 3 ];
  5540. y = positions[ i + 4 ];
  5541. z = positions[ i + 5 ];
  5542. pB.set( x, y, z );
  5543. x = positions[ i + 6 ];
  5544. y = positions[ i + 7 ];
  5545. z = positions[ i + 8 ];
  5546. pC.set( x, y, z );
  5547. cb.subVectors( pC, pB );
  5548. ab.subVectors( pA, pB );
  5549. cb.cross( ab );
  5550. normals[ i ] = cb.x;
  5551. normals[ i + 1 ] = cb.y;
  5552. normals[ i + 2 ] = cb.z;
  5553. normals[ i + 3 ] = cb.x;
  5554. normals[ i + 4 ] = cb.y;
  5555. normals[ i + 5 ] = cb.z;
  5556. normals[ i + 6 ] = cb.x;
  5557. normals[ i + 7 ] = cb.y;
  5558. normals[ i + 8 ] = cb.z;
  5559. }
  5560. }
  5561. this.normalizeNormals();
  5562. this.normalsNeedUpdate = true;
  5563. }
  5564. },
  5565. normalizeNormals: function () {
  5566. var normals = this.attributes[ "normal" ].array;
  5567. var x, y, z, n;
  5568. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5569. x = normals[ i ];
  5570. y = normals[ i + 1 ];
  5571. z = normals[ i + 2 ];
  5572. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5573. normals[ i ] *= n;
  5574. normals[ i + 1 ] *= n;
  5575. normals[ i + 2 ] *= n;
  5576. }
  5577. },
  5578. computeTangents: function () {
  5579. // based on http://www.terathon.com/code/tangent.html
  5580. // (per vertex tangents)
  5581. if ( this.attributes[ "index" ] === undefined ||
  5582. this.attributes[ "position" ] === undefined ||
  5583. this.attributes[ "normal" ] === undefined ||
  5584. this.attributes[ "uv" ] === undefined ) {
  5585. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5586. return;
  5587. }
  5588. var indices = this.attributes[ "index" ].array;
  5589. var positions = this.attributes[ "position" ].array;
  5590. var normals = this.attributes[ "normal" ].array;
  5591. var uvs = this.attributes[ "uv" ].array;
  5592. var nVertices = positions.length / 3;
  5593. if ( this.attributes[ "tangent" ] === undefined ) {
  5594. var nTangentElements = 4 * nVertices;
  5595. this.attributes[ "tangent" ] = {
  5596. itemSize: 4,
  5597. array: new Float32Array( nTangentElements )
  5598. };
  5599. }
  5600. var tangents = this.attributes[ "tangent" ].array;
  5601. var tan1 = [], tan2 = [];
  5602. for ( var k = 0; k < nVertices; k ++ ) {
  5603. tan1[ k ] = new THREE.Vector3();
  5604. tan2[ k ] = new THREE.Vector3();
  5605. }
  5606. var xA, yA, zA,
  5607. xB, yB, zB,
  5608. xC, yC, zC,
  5609. uA, vA,
  5610. uB, vB,
  5611. uC, vC,
  5612. x1, x2, y1, y2, z1, z2,
  5613. s1, s2, t1, t2, r;
  5614. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5615. function handleTriangle( a, b, c ) {
  5616. xA = positions[ a * 3 ];
  5617. yA = positions[ a * 3 + 1 ];
  5618. zA = positions[ a * 3 + 2 ];
  5619. xB = positions[ b * 3 ];
  5620. yB = positions[ b * 3 + 1 ];
  5621. zB = positions[ b * 3 + 2 ];
  5622. xC = positions[ c * 3 ];
  5623. yC = positions[ c * 3 + 1 ];
  5624. zC = positions[ c * 3 + 2 ];
  5625. uA = uvs[ a * 2 ];
  5626. vA = uvs[ a * 2 + 1 ];
  5627. uB = uvs[ b * 2 ];
  5628. vB = uvs[ b * 2 + 1 ];
  5629. uC = uvs[ c * 2 ];
  5630. vC = uvs[ c * 2 + 1 ];
  5631. x1 = xB - xA;
  5632. x2 = xC - xA;
  5633. y1 = yB - yA;
  5634. y2 = yC - yA;
  5635. z1 = zB - zA;
  5636. z2 = zC - zA;
  5637. s1 = uB - uA;
  5638. s2 = uC - uA;
  5639. t1 = vB - vA;
  5640. t2 = vC - vA;
  5641. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5642. sdir.set(
  5643. ( t2 * x1 - t1 * x2 ) * r,
  5644. ( t2 * y1 - t1 * y2 ) * r,
  5645. ( t2 * z1 - t1 * z2 ) * r
  5646. );
  5647. tdir.set(
  5648. ( s1 * x2 - s2 * x1 ) * r,
  5649. ( s1 * y2 - s2 * y1 ) * r,
  5650. ( s1 * z2 - s2 * z1 ) * r
  5651. );
  5652. tan1[ a ].add( sdir );
  5653. tan1[ b ].add( sdir );
  5654. tan1[ c ].add( sdir );
  5655. tan2[ a ].add( tdir );
  5656. tan2[ b ].add( tdir );
  5657. tan2[ c ].add( tdir );
  5658. }
  5659. var i, il;
  5660. var j, jl;
  5661. var iA, iB, iC;
  5662. var offsets = this.offsets;
  5663. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5664. var start = offsets[ j ].start;
  5665. var count = offsets[ j ].count;
  5666. var index = offsets[ j ].index;
  5667. for ( i = start, il = start + count; i < il; i += 3 ) {
  5668. iA = index + indices[ i ];
  5669. iB = index + indices[ i + 1 ];
  5670. iC = index + indices[ i + 2 ];
  5671. handleTriangle( iA, iB, iC );
  5672. }
  5673. }
  5674. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5675. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5676. var w, t, test;
  5677. function handleVertex( v ) {
  5678. n.x = normals[ v * 3 ];
  5679. n.y = normals[ v * 3 + 1 ];
  5680. n.z = normals[ v * 3 + 2 ];
  5681. n2.copy( n );
  5682. t = tan1[ v ];
  5683. // Gram-Schmidt orthogonalize
  5684. tmp.copy( t );
  5685. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5686. // Calculate handedness
  5687. tmp2.crossVectors( n2, t );
  5688. test = tmp2.dot( tan2[ v ] );
  5689. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5690. tangents[ v * 4 ] = tmp.x;
  5691. tangents[ v * 4 + 1 ] = tmp.y;
  5692. tangents[ v * 4 + 2 ] = tmp.z;
  5693. tangents[ v * 4 + 3 ] = w;
  5694. }
  5695. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5696. var start = offsets[ j ].start;
  5697. var count = offsets[ j ].count;
  5698. var index = offsets[ j ].index;
  5699. for ( i = start, il = start + count; i < il; i += 3 ) {
  5700. iA = index + indices[ i ];
  5701. iB = index + indices[ i + 1 ];
  5702. iC = index + indices[ i + 2 ];
  5703. handleVertex( iA );
  5704. handleVertex( iB );
  5705. handleVertex( iC );
  5706. }
  5707. }
  5708. },
  5709. /*
  5710. computeOffsets
  5711. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5712. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5713. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5714. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5715. */
  5716. computeOffsets: function(indexBufferSize) {
  5717. var size = indexBufferSize;
  5718. if(indexBufferSize === undefined)
  5719. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5720. var s = Date.now();
  5721. var indices = this.attributes['index'].array;
  5722. var vertices = this.attributes['position'].array;
  5723. var verticesCount = (vertices.length/3);
  5724. var facesCount = (indices.length/3);
  5725. /*
  5726. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5727. console.log("Faces to process: "+(indices.length/3));
  5728. console.log("Reordering "+verticesCount+" vertices.");
  5729. */
  5730. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5731. var indexPtr = 0;
  5732. var vertexPtr = 0;
  5733. var offsets = [ { start:0, count:0, index:0 } ];
  5734. var offset = offsets[0];
  5735. var duplicatedVertices = 0;
  5736. var newVerticeMaps = 0;
  5737. var faceVertices = new Int32Array(6);
  5738. var vertexMap = new Int32Array( vertices.length );
  5739. var revVertexMap = new Int32Array( vertices.length );
  5740. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5741. /*
  5742. Traverse every face and reorder vertices in the proper offsets of 65k.
  5743. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5744. */
  5745. for(var findex = 0; findex < facesCount; findex++) {
  5746. newVerticeMaps = 0;
  5747. for(var vo = 0; vo < 3; vo++) {
  5748. var vid = indices[ findex*3 + vo ];
  5749. if(vertexMap[vid] == -1) {
  5750. //Unmapped vertice
  5751. faceVertices[vo*2] = vid;
  5752. faceVertices[vo*2+1] = -1;
  5753. newVerticeMaps++;
  5754. } else if(vertexMap[vid] < offset.index) {
  5755. //Reused vertices from previous block (duplicate)
  5756. faceVertices[vo*2] = vid;
  5757. faceVertices[vo*2+1] = -1;
  5758. duplicatedVertices++;
  5759. } else {
  5760. //Reused vertice in the current block
  5761. faceVertices[vo*2] = vid;
  5762. faceVertices[vo*2+1] = vertexMap[vid];
  5763. }
  5764. }
  5765. var faceMax = vertexPtr + newVerticeMaps;
  5766. if(faceMax > (offset.index + size)) {
  5767. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5768. offsets.push(new_offset);
  5769. offset = new_offset;
  5770. //Re-evaluate reused vertices in light of new offset.
  5771. for(var v = 0; v < 6; v+=2) {
  5772. var new_vid = faceVertices[v+1];
  5773. if(new_vid > -1 && new_vid < offset.index)
  5774. faceVertices[v+1] = -1;
  5775. }
  5776. }
  5777. //Reindex the face.
  5778. for(var v = 0; v < 6; v+=2) {
  5779. var vid = faceVertices[v];
  5780. var new_vid = faceVertices[v+1];
  5781. if(new_vid === -1)
  5782. new_vid = vertexPtr++;
  5783. vertexMap[vid] = new_vid;
  5784. revVertexMap[new_vid] = vid;
  5785. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5786. offset.count++;
  5787. }
  5788. }
  5789. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5790. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5791. this.offsets = offsets;
  5792. /*
  5793. var orderTime = Date.now();
  5794. console.log("Reorder time: "+(orderTime-s)+"ms");
  5795. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5796. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5797. console.log("Draw offsets: "+offsets.length);
  5798. */
  5799. return offsets;
  5800. },
  5801. /*
  5802. reoderBuffers:
  5803. Reorder attributes based on a new indexBuffer and indexMap.
  5804. indexBuffer - Uint16Array of the new ordered indices.
  5805. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5806. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5807. */
  5808. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5809. /* Create a copy of all attributes for reordering. */
  5810. var sortedAttributes = {};
  5811. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5812. for( var attr in this.attributes ) {
  5813. if(attr == 'index')
  5814. continue;
  5815. var sourceArray = this.attributes[attr].array;
  5816. for ( var i = 0, il = types.length; i < il; i++ ) {
  5817. var type = types[i];
  5818. if (sourceArray instanceof type) {
  5819. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5820. break;
  5821. }
  5822. }
  5823. }
  5824. /* Move attribute positions based on the new index map */
  5825. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5826. var vid = indexMap[new_vid];
  5827. for ( var attr in this.attributes ) {
  5828. if(attr == 'index')
  5829. continue;
  5830. var attrArray = this.attributes[attr].array;
  5831. var attrSize = this.attributes[attr].itemSize;
  5832. var sortedAttr = sortedAttributes[attr];
  5833. for(var k = 0; k < attrSize; k++)
  5834. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5835. }
  5836. }
  5837. /* Carry the new sorted buffers locally */
  5838. this.attributes['index'].array = indexBuffer;
  5839. for ( var attr in this.attributes ) {
  5840. if(attr == 'index')
  5841. continue;
  5842. this.attributes[attr].array = sortedAttributes[attr];
  5843. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5844. }
  5845. },
  5846. clone: function () {
  5847. var geometry = new THREE.BufferGeometry();
  5848. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5849. for ( var attr in this.attributes ) {
  5850. var sourceAttr = this.attributes[ attr ];
  5851. var sourceArray = sourceAttr.array;
  5852. var attribute = {
  5853. itemSize: sourceAttr.itemSize,
  5854. array: null
  5855. };
  5856. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5857. var type = types[ i ];
  5858. if ( sourceArray instanceof type ) {
  5859. attribute.array = new type( sourceArray );
  5860. break;
  5861. }
  5862. }
  5863. geometry.attributes[ attr ] = attribute;
  5864. }
  5865. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5866. var offset = this.offsets[ i ];
  5867. geometry.offsets.push( {
  5868. start: offset.start,
  5869. index: offset.index,
  5870. count: offset.count
  5871. } );
  5872. }
  5873. return geometry;
  5874. },
  5875. dispose: function () {
  5876. this.dispatchEvent( { type: 'dispose' } );
  5877. }
  5878. };
  5879. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5880. /**
  5881. * @author mrdoob / http://mrdoob.com/
  5882. */
  5883. THREE.Geometry2 = function ( vertices, normals, uvs ) {
  5884. THREE.BufferGeometry.call( this );
  5885. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  5886. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  5887. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  5888. };
  5889. THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  5890. /**
  5891. * @author mrdoob / http://mrdoob.com/
  5892. */
  5893. THREE.IndexedGeometry2 = function ( indices, vertices, normals, uvs ) {
  5894. THREE.BufferGeometry.call( this );
  5895. this.attributes[ 'index' ] = { array: indices, itemSize: 1 };
  5896. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  5897. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  5898. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  5899. };
  5900. THREE.IndexedGeometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  5901. /**
  5902. * @author mrdoob / http://mrdoob.com/
  5903. * @author kile / http://kile.stravaganza.org/
  5904. * @author alteredq / http://alteredqualia.com/
  5905. * @author mikael emtinger / http://gomo.se/
  5906. * @author zz85 / http://www.lab4games.net/zz85/blog
  5907. * @author bhouston / http://exocortex.com
  5908. */
  5909. THREE.Geometry = function () {
  5910. this.id = THREE.GeometryIdCount ++;
  5911. this.uuid = THREE.Math.generateUUID();
  5912. this.name = '';
  5913. this.vertices = [];
  5914. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5915. this.faces = [];
  5916. this.faceVertexUvs = [[]];
  5917. this.morphTargets = [];
  5918. this.morphColors = [];
  5919. this.morphNormals = [];
  5920. this.skinWeights = [];
  5921. this.skinIndices = [];
  5922. this.lineDistances = [];
  5923. this.boundingBox = null;
  5924. this.boundingSphere = null;
  5925. this.hasTangents = false;
  5926. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5927. // update flags
  5928. this.verticesNeedUpdate = false;
  5929. this.elementsNeedUpdate = false;
  5930. this.uvsNeedUpdate = false;
  5931. this.normalsNeedUpdate = false;
  5932. this.tangentsNeedUpdate = false;
  5933. this.colorsNeedUpdate = false;
  5934. this.lineDistancesNeedUpdate = false;
  5935. this.buffersNeedUpdate = false;
  5936. };
  5937. THREE.Geometry.prototype = {
  5938. constructor: THREE.Geometry,
  5939. applyMatrix: function ( matrix ) {
  5940. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5941. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5942. var vertex = this.vertices[ i ];
  5943. vertex.applyMatrix4( matrix );
  5944. }
  5945. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5946. var face = this.faces[ i ];
  5947. face.normal.applyMatrix3( normalMatrix ).normalize();
  5948. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5949. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5950. }
  5951. }
  5952. if ( this.boundingBox instanceof THREE.Box3 ) {
  5953. this.computeBoundingBox();
  5954. }
  5955. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5956. this.computeBoundingSphere();
  5957. }
  5958. },
  5959. computeFaceNormals: function () {
  5960. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5961. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5962. var face = this.faces[ f ];
  5963. var vA = this.vertices[ face.a ];
  5964. var vB = this.vertices[ face.b ];
  5965. var vC = this.vertices[ face.c ];
  5966. cb.subVectors( vC, vB );
  5967. ab.subVectors( vA, vB );
  5968. cb.cross( ab );
  5969. cb.normalize();
  5970. face.normal.copy( cb );
  5971. }
  5972. },
  5973. computeVertexNormals: function ( areaWeighted ) {
  5974. var v, vl, f, fl, face, vertices;
  5975. vertices = new Array( this.vertices.length );
  5976. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5977. vertices[ v ] = new THREE.Vector3();
  5978. }
  5979. if ( areaWeighted ) {
  5980. // vertex normals weighted by triangle areas
  5981. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5982. var vA, vB, vC, vD;
  5983. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5984. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5985. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5986. face = this.faces[ f ];
  5987. vA = this.vertices[ face.a ];
  5988. vB = this.vertices[ face.b ];
  5989. vC = this.vertices[ face.c ];
  5990. cb.subVectors( vC, vB );
  5991. ab.subVectors( vA, vB );
  5992. cb.cross( ab );
  5993. vertices[ face.a ].add( cb );
  5994. vertices[ face.b ].add( cb );
  5995. vertices[ face.c ].add( cb );
  5996. }
  5997. } else {
  5998. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5999. face = this.faces[ f ];
  6000. vertices[ face.a ].add( face.normal );
  6001. vertices[ face.b ].add( face.normal );
  6002. vertices[ face.c ].add( face.normal );
  6003. }
  6004. }
  6005. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6006. vertices[ v ].normalize();
  6007. }
  6008. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6009. face = this.faces[ f ];
  6010. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6011. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6012. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6013. }
  6014. },
  6015. computeMorphNormals: function () {
  6016. var i, il, f, fl, face;
  6017. // save original normals
  6018. // - create temp variables on first access
  6019. // otherwise just copy (for faster repeated calls)
  6020. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6021. face = this.faces[ f ];
  6022. if ( ! face.__originalFaceNormal ) {
  6023. face.__originalFaceNormal = face.normal.clone();
  6024. } else {
  6025. face.__originalFaceNormal.copy( face.normal );
  6026. }
  6027. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6028. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6029. if ( ! face.__originalVertexNormals[ i ] ) {
  6030. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6031. } else {
  6032. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6033. }
  6034. }
  6035. }
  6036. // use temp geometry to compute face and vertex normals for each morph
  6037. var tmpGeo = new THREE.Geometry();
  6038. tmpGeo.faces = this.faces;
  6039. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6040. // create on first access
  6041. if ( ! this.morphNormals[ i ] ) {
  6042. this.morphNormals[ i ] = {};
  6043. this.morphNormals[ i ].faceNormals = [];
  6044. this.morphNormals[ i ].vertexNormals = [];
  6045. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6046. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6047. var faceNormal, vertexNormals;
  6048. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6049. face = this.faces[ f ];
  6050. faceNormal = new THREE.Vector3();
  6051. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6052. dstNormalsFace.push( faceNormal );
  6053. dstNormalsVertex.push( vertexNormals );
  6054. }
  6055. }
  6056. var morphNormals = this.morphNormals[ i ];
  6057. // set vertices to morph target
  6058. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6059. // compute morph normals
  6060. tmpGeo.computeFaceNormals();
  6061. tmpGeo.computeVertexNormals();
  6062. // store morph normals
  6063. var faceNormal, vertexNormals;
  6064. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6065. face = this.faces[ f ];
  6066. faceNormal = morphNormals.faceNormals[ f ];
  6067. vertexNormals = morphNormals.vertexNormals[ f ];
  6068. faceNormal.copy( face.normal );
  6069. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6070. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6071. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6072. }
  6073. }
  6074. // restore original normals
  6075. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6076. face = this.faces[ f ];
  6077. face.normal = face.__originalFaceNormal;
  6078. face.vertexNormals = face.__originalVertexNormals;
  6079. }
  6080. },
  6081. computeTangents: function () {
  6082. // based on http://www.terathon.com/code/tangent.html
  6083. // tangents go to vertices
  6084. var f, fl, v, vl, i, il, vertexIndex,
  6085. face, uv, vA, vB, vC, uvA, uvB, uvC,
  6086. x1, x2, y1, y2, z1, z2,
  6087. s1, s2, t1, t2, r, t, test,
  6088. tan1 = [], tan2 = [],
  6089. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  6090. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  6091. n = new THREE.Vector3(), w;
  6092. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6093. tan1[ v ] = new THREE.Vector3();
  6094. tan2[ v ] = new THREE.Vector3();
  6095. }
  6096. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  6097. vA = context.vertices[ a ];
  6098. vB = context.vertices[ b ];
  6099. vC = context.vertices[ c ];
  6100. uvA = uv[ ua ];
  6101. uvB = uv[ ub ];
  6102. uvC = uv[ uc ];
  6103. x1 = vB.x - vA.x;
  6104. x2 = vC.x - vA.x;
  6105. y1 = vB.y - vA.y;
  6106. y2 = vC.y - vA.y;
  6107. z1 = vB.z - vA.z;
  6108. z2 = vC.z - vA.z;
  6109. s1 = uvB.x - uvA.x;
  6110. s2 = uvC.x - uvA.x;
  6111. t1 = uvB.y - uvA.y;
  6112. t2 = uvC.y - uvA.y;
  6113. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6114. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  6115. ( t2 * y1 - t1 * y2 ) * r,
  6116. ( t2 * z1 - t1 * z2 ) * r );
  6117. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  6118. ( s1 * y2 - s2 * y1 ) * r,
  6119. ( s1 * z2 - s2 * z1 ) * r );
  6120. tan1[ a ].add( sdir );
  6121. tan1[ b ].add( sdir );
  6122. tan1[ c ].add( sdir );
  6123. tan2[ a ].add( tdir );
  6124. tan2[ b ].add( tdir );
  6125. tan2[ c ].add( tdir );
  6126. }
  6127. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6128. face = this.faces[ f ];
  6129. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6130. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6131. }
  6132. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6133. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6134. face = this.faces[ f ];
  6135. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  6136. n.copy( face.vertexNormals[ i ] );
  6137. vertexIndex = face[ faceIndex[ i ] ];
  6138. t = tan1[ vertexIndex ];
  6139. // Gram-Schmidt orthogonalize
  6140. tmp.copy( t );
  6141. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6142. // Calculate handedness
  6143. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6144. test = tmp2.dot( tan2[ vertexIndex ] );
  6145. w = (test < 0.0) ? -1.0 : 1.0;
  6146. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6147. }
  6148. }
  6149. this.hasTangents = true;
  6150. },
  6151. computeLineDistances: function ( ) {
  6152. var d = 0;
  6153. var vertices = this.vertices;
  6154. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6155. if ( i > 0 ) {
  6156. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6157. }
  6158. this.lineDistances[ i ] = d;
  6159. }
  6160. },
  6161. computeBoundingBox: function () {
  6162. if ( this.boundingBox === null ) {
  6163. this.boundingBox = new THREE.Box3();
  6164. }
  6165. this.boundingBox.setFromPoints( this.vertices );
  6166. },
  6167. computeBoundingSphere: function () {
  6168. if ( this.boundingSphere === null ) {
  6169. this.boundingSphere = new THREE.Sphere();
  6170. }
  6171. this.boundingSphere.setFromPoints( this.vertices );
  6172. },
  6173. merge: function ( geometry, matrix, materialIndexOffset ) {
  6174. var normalMatrix,
  6175. vertexOffset = this.vertices.length,
  6176. uvPosition = this.faceVertexUvs[ 0 ].length,
  6177. vertices1 = this.vertices,
  6178. vertices2 = geometry.vertices,
  6179. faces1 = this.faces,
  6180. faces2 = geometry.faces,
  6181. uvs1 = this.faceVertexUvs[ 0 ],
  6182. uvs2 = geometry.faceVertexUvs[ 0 ];
  6183. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6184. if ( matrix !== undefined ) {
  6185. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6186. }
  6187. // vertices
  6188. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6189. var vertex = vertices2[ i ];
  6190. var vertexCopy = vertex.clone();
  6191. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6192. vertices1.push( vertexCopy );
  6193. }
  6194. // faces
  6195. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6196. var face = faces2[ i ], faceCopy, normal, color,
  6197. faceVertexNormals = face.vertexNormals,
  6198. faceVertexColors = face.vertexColors;
  6199. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6200. faceCopy.normal.copy( face.normal );
  6201. if ( normalMatrix !== undefined ) {
  6202. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6203. }
  6204. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6205. normal = faceVertexNormals[ j ].clone();
  6206. if ( normalMatrix !== undefined ) {
  6207. normal.applyMatrix3( normalMatrix ).normalize();
  6208. }
  6209. faceCopy.vertexNormals.push( normal );
  6210. }
  6211. faceCopy.color.copy( face.color );
  6212. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6213. color = faceVertexColors[ j ];
  6214. faceCopy.vertexColors.push( color.clone() );
  6215. }
  6216. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6217. faces1.push( faceCopy );
  6218. }
  6219. // uvs
  6220. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6221. var uv = uvs2[ i ], uvCopy = [];
  6222. if ( uv === undefined ) {
  6223. continue;
  6224. }
  6225. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6226. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6227. }
  6228. uvs1.push( uvCopy );
  6229. }
  6230. },
  6231. /*
  6232. * Checks for duplicate vertices with hashmap.
  6233. * Duplicated vertices are removed
  6234. * and faces' vertices are updated.
  6235. */
  6236. mergeVertices: function () {
  6237. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6238. var unique = [], changes = [];
  6239. var v, key;
  6240. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6241. var precision = Math.pow( 10, precisionPoints );
  6242. var i,il, face;
  6243. var indices, k, j, jl, u;
  6244. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6245. v = this.vertices[ i ];
  6246. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6247. if ( verticesMap[ key ] === undefined ) {
  6248. verticesMap[ key ] = i;
  6249. unique.push( this.vertices[ i ] );
  6250. changes[ i ] = unique.length - 1;
  6251. } else {
  6252. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6253. changes[ i ] = changes[ verticesMap[ key ] ];
  6254. }
  6255. };
  6256. // if faces are completely degenerate after merging vertices, we
  6257. // have to remove them from the geometry.
  6258. var faceIndicesToRemove = [];
  6259. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6260. face = this.faces[ i ];
  6261. face.a = changes[ face.a ];
  6262. face.b = changes[ face.b ];
  6263. face.c = changes[ face.c ];
  6264. indices = [ face.a, face.b, face.c ];
  6265. var dupIndex = -1;
  6266. // if any duplicate vertices are found in a Face3
  6267. // we have to remove the face as nothing can be saved
  6268. for ( var n = 0; n < 3; n ++ ) {
  6269. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6270. dupIndex = n;
  6271. faceIndicesToRemove.push( i );
  6272. break;
  6273. }
  6274. }
  6275. }
  6276. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6277. var idx = faceIndicesToRemove[ i ];
  6278. this.faces.splice( idx, 1 );
  6279. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6280. this.faceVertexUvs[ j ].splice( idx, 1 );
  6281. }
  6282. }
  6283. // Use unique set of vertices
  6284. var diff = this.vertices.length - unique.length;
  6285. this.vertices = unique;
  6286. return diff;
  6287. },
  6288. // Geometry splitting
  6289. makeGroups: ( function () {
  6290. var geometryGroupCounter = 0;
  6291. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6292. var f, fl, face, materialIndex,
  6293. groupHash, hash_map = {};
  6294. var numMorphTargets = this.morphTargets.length;
  6295. var numMorphNormals = this.morphNormals.length;
  6296. this.geometryGroups = {};
  6297. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6298. face = this.faces[ f ];
  6299. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6300. if ( ! ( materialIndex in hash_map ) ) {
  6301. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6302. }
  6303. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6304. if ( ! ( groupHash in this.geometryGroups ) ) {
  6305. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6306. }
  6307. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6308. hash_map[ materialIndex ].counter += 1;
  6309. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6310. if ( ! ( groupHash in this.geometryGroups ) ) {
  6311. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6312. }
  6313. }
  6314. this.geometryGroups[ groupHash ].faces3.push( f );
  6315. this.geometryGroups[ groupHash ].vertices += 3;
  6316. }
  6317. this.geometryGroupsList = [];
  6318. for ( var g in this.geometryGroups ) {
  6319. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6320. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6321. }
  6322. };
  6323. } )(),
  6324. clone: function () {
  6325. var geometry = new THREE.Geometry();
  6326. var vertices = this.vertices;
  6327. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6328. geometry.vertices.push( vertices[ i ].clone() );
  6329. }
  6330. var faces = this.faces;
  6331. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6332. geometry.faces.push( faces[ i ].clone() );
  6333. }
  6334. var uvs = this.faceVertexUvs[ 0 ];
  6335. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6336. var uv = uvs[ i ], uvCopy = [];
  6337. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6338. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6339. }
  6340. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6341. }
  6342. return geometry;
  6343. },
  6344. dispose: function () {
  6345. this.dispatchEvent( { type: 'dispose' } );
  6346. }
  6347. };
  6348. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6349. THREE.GeometryIdCount = 0;
  6350. /**
  6351. * @author mrdoob / http://mrdoob.com/
  6352. */
  6353. THREE.GeometryEditor = function ( geometry ) {
  6354. this.geometry = geometry;
  6355. };
  6356. Object.defineProperties( THREE.GeometryEditor.prototype, {
  6357. vertices: {
  6358. enumerable: true,
  6359. get: function() { return this.createVertexProxies(); }
  6360. },
  6361. normals: {
  6362. enumerable: true,
  6363. get: function() { return this.createNormalProxies(); }
  6364. },
  6365. uvs: {
  6366. enumerable: true,
  6367. get: function() { return this.createUVProxies(); }
  6368. }
  6369. } );
  6370. THREE.GeometryEditor.prototype.createVertexProxies = function () {
  6371. Object.defineProperty( this, 'vertices', { value: [], writable: true } );
  6372. var attributes = this.geometry.attributes;
  6373. var length = attributes.position.array.length / 3;
  6374. for ( var i = 0; i < length; i ++ ) {
  6375. this.vertices.push( new THREE.ProxyVector3( attributes.position.array, i * 3 ) );
  6376. }
  6377. return this.vertices;
  6378. };
  6379. THREE.GeometryEditor.prototype.createNormalProxies = function () {
  6380. Object.defineProperty( this, 'normals', { value: [], writable: true } );
  6381. var attributes = this.geometry.attributes;
  6382. var length = attributes.position.array.length / 3;
  6383. for ( var i = 0; i < length; i ++ ) {
  6384. this.normals.push( new THREE.ProxyVector3( attributes.normal.array, i * 3 ) );
  6385. }
  6386. return this.normals;
  6387. };
  6388. THREE.GeometryEditor.prototype.createUVProxies = function () {
  6389. Object.defineProperty( this, 'uvs', { value: [], writable: true } );
  6390. var attributes = this.geometry.attributes;
  6391. var length = attributes.position.array.length / 3;
  6392. for ( var i = 0; i < length; i ++ ) {
  6393. this.uvs.push( new THREE.ProxyVector2( attributes.uv.array, i * 2 ) );
  6394. }
  6395. return this.uvs;
  6396. };
  6397. /**
  6398. * @author mrdoob / http://mrdoob.com/
  6399. * @author kile / http://kile.stravaganza.org/
  6400. * @author alteredq / http://alteredqualia.com/
  6401. * @author mikael emtinger / http://gomo.se/
  6402. * @author zz85 / http://www.lab4games.net/zz85/blog
  6403. * @author bhouston / http://exocortex.com
  6404. * @author jbaicoianu / http://baicoianu.com
  6405. */
  6406. THREE.ProxyGeometry = function ( ) {
  6407. THREE.BufferGeometry.call( this );
  6408. this.addEventListener( 'allocate', this.onGeometryAllocate);
  6409. // TODO - implement as BufferGeometry attributes
  6410. this.morphTargets = [];
  6411. this.morphColors = [];
  6412. };
  6413. THREE.ProxyGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  6414. Object.defineProperties(THREE.ProxyGeometry.prototype, {
  6415. vertices: {
  6416. enumerable: true,
  6417. configurable: true,
  6418. get: function() { return this.createVertexProxies(); }
  6419. },
  6420. faces: {
  6421. enumerable: true,
  6422. get: function() { return this.createFaceProxies() }
  6423. },
  6424. faceVertexUvs: {
  6425. enumerable: true,
  6426. get: function() { return this.createUvProxies() }
  6427. },
  6428. colors: {
  6429. enumerable: true,
  6430. get: function() { return this.createColorProxies() }
  6431. },
  6432. skinIndices: {
  6433. enumerable: true,
  6434. get: function() { return this.createSkinIndexProxies() }
  6435. },
  6436. skinWeights: {
  6437. enumerable: true,
  6438. get: function() { return this.createSkinWeightProxies() }
  6439. },
  6440. // TODO - fill in additional proxies:
  6441. // - morphColors
  6442. // - morphNormals
  6443. // - morphTargets
  6444. verticesNeedUpdate: {
  6445. enumerable: true,
  6446. get: function() { if (this.attributes[ 'position' ]) return this.attributes[ 'position' ].needsUpdate; } ,
  6447. set: function(v) { if (this.attributes[ 'position' ]) this.attributes[ 'position' ].needsUpdate = v; }
  6448. },
  6449. colorsNeedUpdate: {
  6450. enumerable: true,
  6451. get: function() { if (this.attributes[ 'color' ]) return this.attributes[ 'color' ].needsUpdate; } ,
  6452. set: function(v) { if (this.attributes[ 'color' ]) this.attributes[ 'color' ].needsUpdate = v; }
  6453. },
  6454. normalsNeedUpdate: {
  6455. enumerable: true,
  6456. get: function() { if (this.attributes[ 'normal' ]) return this.attributes[ 'normal' ].needsUpdate; } ,
  6457. set: function(v) { if (this.attributes[ 'normal' ]) this.attributes[ 'normal' ].needsUpdate = v; }
  6458. },
  6459. });
  6460. THREE.ProxyGeometry.prototype.createVertexProxies = function(values) {
  6461. if (!this.hasOwnProperty('vertices')) {
  6462. // Replace the prototype getter with a local array property
  6463. Object.defineProperty( this, "vertices", { value: [], writable: true } );
  6464. } else {
  6465. // Start with a new, empty array
  6466. this.vertices = [];
  6467. }
  6468. // If the attribute buffer has already been populated, set up proxy objects
  6469. this.populateProxyFromBuffer(this.vertices, "position", THREE.ProxyVector3, 3);
  6470. // If values were passed in, store them in the buffer via the proxy objects
  6471. if (values) {
  6472. for (var i = 0; i < values.length; i++) {
  6473. this.vertices[i].copy(values[i]);
  6474. }
  6475. }
  6476. // Return a reference to the newly-created array
  6477. return this.vertices;
  6478. }
  6479. THREE.ProxyGeometry.prototype.createFaceProxies = function(values) {
  6480. if (!this.hasOwnProperty("faces")) {
  6481. // Replace the prototype getter with a local array property
  6482. Object.defineProperty( this, "faces", { value: [], writable: true } );
  6483. } else {
  6484. // Start with a new, empty array
  6485. this.faces = [];
  6486. }
  6487. // If the attribute buffer has already been populated, set up proxy objects
  6488. var faces = this.faces,
  6489. indexarray = false,
  6490. positionarray = false,
  6491. normalarray = false,
  6492. colorarray = false,
  6493. tangentarray = false;
  6494. if ( this.attributes[ 'index' ] ) {
  6495. indexarray = this.attributes[ 'index' ].array;
  6496. }
  6497. if ( this.attributes[ 'position' ] ) {
  6498. positionarray = this.attributes[ 'position' ].array;
  6499. }
  6500. if (this.attributes[ 'normal' ]) {
  6501. normalarray = this.attributes[ 'normal' ].array;
  6502. }
  6503. if (this.attributes[ 'color' ]) {
  6504. colorarray = this.attributes[ 'color' ].array;
  6505. }
  6506. if (this.attributes[ 'tangent' ]) {
  6507. tangentarray = this.attributes[ 'tangent' ].array;
  6508. }
  6509. // TODO - this should be accomplished using "virtual" functions on various classes (IndexedGeometry, SmoothGeometry, etc)
  6510. if (indexarray) {
  6511. for ( var i = 0, l = indexarray.length / 3; i < l; i ++ ) {
  6512. var o = i * 3;
  6513. var face = new THREE.ProxyFace3( indexarray, i * 3 );
  6514. faces.push(face);
  6515. }
  6516. } else if (positionarray) {
  6517. for ( var i = 0, l = positionarray.length / 3; i < l; i += 3 ) {
  6518. var o = i * 3;
  6519. var v1 = i, v2 = i+1, v3 = i+2;
  6520. var face = new THREE.ProxyFace3( v1, v2, v3 );
  6521. faces.push(face);
  6522. }
  6523. }
  6524. // If values were passed in, store them in the buffer via the proxy objects
  6525. if (values) {
  6526. for (var i = 0, l = values.length; i < l; i++) {
  6527. var f = faces[i],
  6528. v = values[i];
  6529. f.a = v.a;
  6530. f.b = v.b;
  6531. f.c = v.c;
  6532. }
  6533. }
  6534. if (normalarray) {
  6535. this.createFaceVertexNormalProxies(values);
  6536. }
  6537. if (colorarray) {
  6538. this.createFaceVertexColorProxies(values);
  6539. }
  6540. if (tangentarray) {
  6541. this.createFaceVertexTangentProxies(values);
  6542. }
  6543. // Return a reference to the newly-created array
  6544. return this.faces;
  6545. }
  6546. THREE.ProxyGeometry.prototype.createFaceVertexNormalProxies = function(values) {
  6547. if ( this.attributes[ 'normal' ] && this.attributes[ 'normal' ].array ) {
  6548. var normalarray = this.attributes[ 'normal' ].array;
  6549. for (var i = 0, l = this.faces.length; i < l; i++) {
  6550. var f = this.faces[i];
  6551. f.vertexNormals = [
  6552. new THREE.ProxyVector3(normalarray, f.a * 3),
  6553. new THREE.ProxyVector3(normalarray, f.b * 3),
  6554. new THREE.ProxyVector3(normalarray, f.c * 3),
  6555. ];
  6556. f.normal = new THREE.MultiVector3(f.vertexNormals);
  6557. }
  6558. }
  6559. // If values were passed in, store them in the buffer via the proxy objects
  6560. if (values) {
  6561. for (var i = 0, l = values.length; i < l; i++) {
  6562. var f = this.faces[i],
  6563. v = values[i];
  6564. if (v.vertexNormals.length > 0) {
  6565. for (var j = 0, l2 = f.vertexNormals.length; j < l2; j++) {
  6566. f.vertexNormals[j].copy(v.vertexNormals[j]);
  6567. }
  6568. } else if (v.normal) {
  6569. f.normal.copy(v.normal);
  6570. }
  6571. }
  6572. }
  6573. }
  6574. THREE.ProxyGeometry.prototype.createFaceVertexColorProxies = function(values) {
  6575. if ( this.attributes[ 'color' ] && this.attributes[ 'color' ].array ) {
  6576. var colorarray = this.attributes[ 'color' ].array;
  6577. for (var i = 0, l = this.faces.length; i < l; i++) {
  6578. var f = this.faces[i];
  6579. if ( this.attributes[ 'index' ] ) {
  6580. f.vertexColors = [
  6581. new THREE.ProxyColor(colorarray, f.a * 3),
  6582. new THREE.ProxyColor(colorarray, f.b * 3),
  6583. new THREE.ProxyColor(colorarray, f.c * 3),
  6584. ];
  6585. } else {
  6586. var o = i * 9;
  6587. f.vertexColors = [
  6588. new THREE.ProxyColor(colorarray, o),
  6589. new THREE.ProxyColor(colorarray, o + 3),
  6590. new THREE.ProxyColor(colorarray, o + 6),
  6591. ];
  6592. }
  6593. f.color = new THREE.MultiColor(f.vertexColors);
  6594. }
  6595. }
  6596. // If values were passed in, store them in the buffer via the proxy objects
  6597. if (values) {
  6598. for (var i = 0, l = values.length; i < l; i++) {
  6599. var f = this.faces[i],
  6600. v = values[i];
  6601. for (var j = 0, l2 = f.vertexColors.length; j < l2; j++) {
  6602. if (v.vertexColors.length > 0) {
  6603. f.vertexColors[j].copy(v.vertexColors[j]);
  6604. } else if (v.color) {
  6605. f.color.copy(v.color);
  6606. }
  6607. }
  6608. }
  6609. }
  6610. }
  6611. THREE.ProxyGeometry.prototype.createFaceVertexTangentProxies = function(values) {
  6612. if ( this.attributes[ 'tangent' ] && this.attributes[ 'tangent' ].array ) {
  6613. var tangentarray = this.attributes[ 'tangent' ].array;
  6614. for (var i = 0, l = this.faces.length; i < l; i++) {
  6615. var f = this.faces[i];
  6616. f.vertexTangents = [
  6617. new THREE.ProxyVector3(tangentarray, f.a * 3),
  6618. new THREE.ProxyVector3(tangentarray, f.b * 3),
  6619. new THREE.ProxyVector3(tangentarray, f.c * 3),
  6620. ];
  6621. }
  6622. }
  6623. // If values were passed in, store them in the buffer via the proxy objects
  6624. if (values) {
  6625. for (var i = 0, l = values.length; i < l; i++) {
  6626. var f = this.faces[i],
  6627. v = values[i];
  6628. if (v.vertexTangents.length > 0) {
  6629. for (var j = 0, l2 = f.vertexTangents.length; j < l2; j++) {
  6630. f.vertexTangents[j].copy(v.vertexTangents[j]);
  6631. }
  6632. }
  6633. }
  6634. }
  6635. }
  6636. THREE.ProxyGeometry.prototype.createUvProxies = function(values) {
  6637. // Replace the prototype getter with a local array property
  6638. if (!this.hasOwnProperty("faceVertexUvs")) {
  6639. Object.defineProperty( this, "faceVertexUvs", { value: [[]], writable: true } );
  6640. } else {
  6641. this.faceVertexUvs = [[]];
  6642. }
  6643. // If the attribute buffer has already been populated, set up proxy objects
  6644. if ( this.attributes[ 'uv' ] && this.attributes[ 'uv' ].array ) {
  6645. var faces = this.faces;
  6646. var uvarray = this.attributes[ 'uv' ].array;
  6647. for (var i = 0, l = faces.length; i < l; i++) {
  6648. var f = faces[i];
  6649. this.faceVertexUvs[0][i] = [];
  6650. if ( this.attributes[ 'index' ] ) {
  6651. this.faceVertexUvs[0][i][0] = new THREE.ProxyVector2(uvarray, f.a * 2);
  6652. this.faceVertexUvs[0][i][1] = new THREE.ProxyVector2(uvarray, f.b * 2);
  6653. this.faceVertexUvs[0][i][2] = new THREE.ProxyVector2(uvarray, f.c * 2);
  6654. } else {
  6655. var o = i * 6;
  6656. this.faceVertexUvs[0][i][0] = new THREE.ProxyVector2(uvarray, o);
  6657. this.faceVertexUvs[0][i][1] = new THREE.ProxyVector2(uvarray, o + 2);
  6658. this.faceVertexUvs[0][i][2] = new THREE.ProxyVector2(uvarray, o + 4);
  6659. }
  6660. }
  6661. }
  6662. // If values were passed in, store them in the buffer via the proxy objects
  6663. if (values) {
  6664. for (var i = 0, l = values.length; i < l; i++) {
  6665. for (var j = 0, l2 = values[i].length; j < l2; j++) {
  6666. var uv = values[i][j];
  6667. this.faceVertexUvs[0][i][j].copy(uv);
  6668. }
  6669. }
  6670. }
  6671. // Return a reference to the newly-created array
  6672. return this.faceVertexUvs;
  6673. }
  6674. THREE.ProxyGeometry.prototype.createSkinIndexProxies = function(values) {
  6675. // Replace the prototype getter with a local array property
  6676. if (!this.hasOwnProperty('skinIndices')) {
  6677. Object.defineProperty( this, "skinIndices", { value: [], writable: true } );
  6678. } else {
  6679. this.skinIndices = [];
  6680. }
  6681. // If the attribute buffer has already been populated, set up proxy objects
  6682. this.populateProxyFromBuffer(this.skinIndices, "skinIndex", THREE.ProxyVector4, 4);
  6683. // If values were passed in, store them in the buffer via the proxy objects
  6684. if (values) {
  6685. for (var i = 0; i < values.length; i++) {
  6686. this.skinIndices[i].copy(values[i]);
  6687. }
  6688. }
  6689. // Return a reference to the newly-created array
  6690. return this.skinIndices;
  6691. }
  6692. THREE.ProxyGeometry.prototype.createSkinWeightProxies = function(values) {
  6693. // Replace the prototype getter with a local array property
  6694. if (!this.hasOwnProperty('skinWeights')) {
  6695. Object.defineProperty( this, "skinWeights", { value: [], writable: true } );
  6696. } else {
  6697. this.skinWeights = [];
  6698. }
  6699. // If the attribute buffer has already been populated, set up proxy objects
  6700. this.populateProxyFromBuffer(this.skinWeights, "skinWeight", THREE.ProxyVector4, 4);
  6701. // If values were passed in, store them in the buffer via the proxy objects
  6702. if (values) {
  6703. for (var i = 0; i < values.length; i++) {
  6704. this.skinWeights[i].copy(values[i]);
  6705. }
  6706. }
  6707. // Return a reference to the newly-created array
  6708. return this.skinWeights;
  6709. }
  6710. THREE.ProxyGeometry.prototype.createColorProxies = function(values) {
  6711. // Replace the prototype getter with a local array property
  6712. if (!this.hasOwnProperty('colors')) {
  6713. Object.defineProperty( this, "colors", { value: [], writable: true } );
  6714. } else {
  6715. this.colors = [];
  6716. }
  6717. // If the attribute buffer has already been populated, set up proxy objects
  6718. this.populateProxyFromBuffer(this.colors, "color", THREE.ProxyColor, 3);
  6719. // If values were passed in, store them in the buffer via the proxy objects
  6720. if (values) {
  6721. for (var i = 0; i < values.length; i++) {
  6722. this.colors[i].copy(values[i]);
  6723. }
  6724. }
  6725. // Return a reference to the newly-created array
  6726. return this.colors;
  6727. }
  6728. THREE.ProxyGeometry.prototype.populateProxyFromBuffer = function(attr, buffername, proxytype, itemsize, offset, count) {
  6729. if ( this.attributes[ buffername ] && this.attributes[ buffername ].array ) {
  6730. var array = this.attributes[ buffername ].array;
  6731. var size = itemsize || this.attributes[ buffername ].itemSize;
  6732. var start = offset || 0;
  6733. count = count || (array.length / size - start);
  6734. for ( var i = start, l = start + count; i < l; i ++ ) {
  6735. attr.push( new proxytype( array, i * size ) );
  6736. }
  6737. }
  6738. }
  6739. /*
  6740. * Checks for duplicate vertices with hashmap.
  6741. * Duplicated vertices are removed
  6742. * and faces' vertices are updated.
  6743. */
  6744. THREE.ProxyGeometry.prototype.mergeVertices = function () {
  6745. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6746. var unique = [], changes = [];
  6747. var v, key;
  6748. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6749. var precision = Math.pow( 10, precisionPoints );
  6750. var i,il, face;
  6751. var indices, k, j, jl, u;
  6752. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6753. v = this.vertices[ i ];
  6754. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6755. if ( verticesMap[ key ] === undefined ) {
  6756. verticesMap[ key ] = i;
  6757. unique.push( this.vertices[ i ] );
  6758. changes[ i ] = unique.length - 1;
  6759. } else {
  6760. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6761. changes[ i ] = changes[ verticesMap[ key ] ];
  6762. }
  6763. };
  6764. // if faces are completely degenerate after merging vertices, we
  6765. // have to remove them from the geometry.
  6766. var faceIndicesToRemove = [];
  6767. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6768. face = this.faces[ i ];
  6769. face.a = changes[ face.a ];
  6770. face.b = changes[ face.b ];
  6771. face.c = changes[ face.c ];
  6772. indices = [ face.a, face.b, face.c ];
  6773. var dupIndex = -1;
  6774. // if any duplicate vertices are found in a Face3
  6775. // we have to remove the face as nothing can be saved
  6776. for ( var n = 0; n < 3; n ++ ) {
  6777. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6778. dupIndex = n;
  6779. faceIndicesToRemove.push( i );
  6780. break;
  6781. }
  6782. }
  6783. }
  6784. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6785. var idx = faceIndicesToRemove[ i ];
  6786. this.faces.splice( idx, 1 );
  6787. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6788. this.faceVertexUvs[ j ].splice( idx, 1 );
  6789. }
  6790. }
  6791. // Use unique set of vertices
  6792. var diff = this.vertices.length - unique.length;
  6793. this.vertices = unique;
  6794. return diff;
  6795. }
  6796. THREE.ProxyGeometry.prototype.onGeometryAllocate = function (ev) {
  6797. // Prevent allocate event listener from firing multiple times
  6798. this.removeEventListener( 'allocate', this.onGeometryAllocate);
  6799. if (this.hasOwnProperty('vertices')) {
  6800. var attr = new THREE.Float32Attribute(this.vertices.length, 3);
  6801. this.addAttribute('position', attr);
  6802. this.createVertexProxies(this.vertices);
  6803. }
  6804. if (this.hasOwnProperty('faces')) {
  6805. var idxattr = new THREE.Uint16Attribute(this.faces.length, 3);
  6806. this.addAttribute('index', idxattr);
  6807. if (this.faces.length > 0) {
  6808. var hasnormals = (this.hasOwnProperty('normals') || this.faces[0].normal || this.faces[0].vertexNormals.length > 0);
  6809. var hascolors = (this.hasOwnProperty('colors') || this.faces[0].color || this.faces[0].vertexColors.length > 0);
  6810. var hastangents = (this.faces[0].vertexTangents.length > 0);
  6811. if (hasnormals) {
  6812. var normalattr = new THREE.Float32Attribute(this.vertices.length, 3);
  6813. this.addAttribute('normal', normalattr);
  6814. }
  6815. if (hascolors) {
  6816. var colorattr = new THREE.Float32Attribute(this.faces.length * 3, 3);
  6817. this.addAttribute('color', colorattr);
  6818. }
  6819. if (hastangents) {
  6820. var tangentattr = new THREE.Float32Attribute(this.faces.length * 3, 3);
  6821. this.addAttribute('tangent', tangentattr);
  6822. }
  6823. }
  6824. this.createFaceProxies(this.faces);
  6825. }
  6826. if (this.hasOwnProperty('faceVertexUvs')) {
  6827. var uvattr = new THREE.Float32Attribute(this.faces.length * 3, 2);
  6828. this.addAttribute('uv', uvattr);
  6829. this.createUvProxies(this.faceVertexUvs[0]);
  6830. }
  6831. if (this.hasOwnProperty('skinIndices')) {
  6832. var skinidxattr = new THREE.Float32Attribute(this.skinIndices.length, 4);
  6833. this.addAttribute('skinIndex', skinidxattr);
  6834. this.createSkinIndexProxies(this.skinIndices);
  6835. }
  6836. if (this.hasOwnProperty('skinWeights')) {
  6837. var skinweightattr = new THREE.Float32Attribute(this.skinWeights.length, 4);
  6838. this.addAttribute('skinWeight', skinweightattr);
  6839. this.createSkinWeightProxies(this.skinWeights);
  6840. }
  6841. }
  6842. THREE.ProxyGeometry.prototype.computeFaceNormals = function() {
  6843. this.dispatchEvent( { type: 'allocate' } );
  6844. return THREE.BufferGeometry.prototype.computeFaceNormals.call(this);
  6845. }
  6846. THREE.ProxyGeometry.prototype.computeVertexNormals = function() {
  6847. this.dispatchEvent( { type: 'allocate' } );
  6848. return THREE.BufferGeometry.prototype.computeVertexNormals.call(this);
  6849. }
  6850. THREE.ProxyGeometry.prototype.computeTangents = function() {
  6851. this.dispatchEvent( { type: 'allocate' } );
  6852. var ret = THREE.BufferGeometry.prototype.computeTangents.call(this);
  6853. // FIXME - this doesn't work yet
  6854. //this.createFaceVertexTangentProxies();
  6855. return ret;
  6856. }
  6857. THREE.ProxyGeometry.prototype.computeBoundingSphere = function() {
  6858. this.dispatchEvent( { type: 'allocate' } );
  6859. return THREE.BufferGeometry.prototype.computeBoundingSphere.call(this);
  6860. }
  6861. THREE.ProxyGeometry.prototype.computeBoundingBox = function () {
  6862. this.dispatchEvent( { type: 'allocate' } );
  6863. return THREE.BufferGeometry.prototype.computeBoundingBox.call(this);
  6864. }
  6865. THREE.ProxyGeometry.prototype.clone = function () {
  6866. var buff = THREE.BufferGeometry.prototype.clone.call(this);
  6867. var geo = new THREE.ProxyGeometry();
  6868. geo.attributes = buff.attributes;
  6869. geo.offsets = buff.offsets;
  6870. return geo;
  6871. }
  6872. THREE.EventDispatcher.prototype.apply( THREE.ProxyGeometry.prototype );
  6873. THREE.ProxyGeometryIdCount = 0;
  6874. // Allows updating of multiple THREE.Color objects with the same value
  6875. // Used for face.color -> face.vertexColor[] compatibility layer for non-indexed geometry
  6876. THREE.MultiColor = function(links) {
  6877. this.links = links;
  6878. }
  6879. THREE.MultiColor.prototype = Object.create( THREE.Color.prototype );
  6880. THREE.MultiColor.prototype.setAll = function(axis, value) {
  6881. for (var i = 0, l = this.links.length; i < l; i++) {
  6882. this.links[i][axis] = value;
  6883. }
  6884. }
  6885. // Getters return value from the first linked color
  6886. // Setters set the same value for all linked colors
  6887. Object.defineProperties( THREE.MultiColor.prototype, {
  6888. 'r': {
  6889. get: function () { return (this.links[0] ? this.links[0].r : 0); },
  6890. set: function ( v ) { this.setAll('r', v); }
  6891. },
  6892. 'g': {
  6893. get: function () { return (this.links[0] ? this.links[0].g : 0); },
  6894. set: function ( v ) { this.setAll('g', v); }
  6895. },
  6896. 'b': {
  6897. get: function () { return (this.links[0] ? this.links[0].b : 0); },
  6898. set: function ( v ) { this.setAll('b', v); }
  6899. }
  6900. } );
  6901. // Allows updating of multiple THREE.Vector3 objects with the same value
  6902. // Used for face.normal -> face.vertexNormal[] compatibility layer for FlatShading
  6903. THREE.MultiVector3 = function(links) {
  6904. this.links = links;
  6905. }
  6906. THREE.MultiVector3.prototype = Object.create( THREE.Vector3.prototype );
  6907. THREE.MultiVector3.prototype.setAll = function(axis, value) {
  6908. for (var i = 0, l = this.links.length; i < l; i++) {
  6909. this.links[i][axis] = value;
  6910. }
  6911. }
  6912. // Getters return value from the first linked vector
  6913. // Setters set the same value for all linked vectors
  6914. Object.defineProperties( THREE.MultiVector3.prototype, {
  6915. 'x': {
  6916. get: function () { return (this.links[0] ? this.links[0].x : 0); },
  6917. set: function ( v ) { this.setAll('x', v); }
  6918. },
  6919. 'y': {
  6920. get: function () { return (this.links[0] ? this.links[0].y : 0); },
  6921. set: function ( v ) { this.setAll('y', v); }
  6922. },
  6923. 'z': {
  6924. get: function () { return (this.links[0] ? this.links[0].z : 0); },
  6925. set: function ( v ) { this.setAll('z', v); }
  6926. }
  6927. } );
  6928. /**
  6929. * @author mrdoob / http://mrdoob.com/
  6930. * @author jbaicoianu / http://baicoianu.com/
  6931. */
  6932. THREE.ProxyColor = function ( array, offset ) {
  6933. this.array = array;
  6934. this.offset = offset;
  6935. }
  6936. THREE.ProxyColor.prototype = Object.create( THREE.Color.prototype );
  6937. Object.defineProperties( THREE.ProxyColor.prototype, {
  6938. 'r': {
  6939. enumerable: true,
  6940. get: function () { return this.array[ this.offset ]; },
  6941. set: function ( v ) { this.array[ this.offset ] = v; }
  6942. },
  6943. 'g': {
  6944. enumerable: true,
  6945. get: function () { return this.array[ this.offset + 1 ]; },
  6946. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6947. },
  6948. 'b': {
  6949. enumerable: true,
  6950. get: function () { return this.array[ this.offset + 2 ]; },
  6951. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6952. }
  6953. } );
  6954. /**
  6955. * @author mrdoob / http://mrdoob.com/
  6956. * @author jbaicoianu / http://baicoianu.com/
  6957. */
  6958. THREE.ProxyVector2 = function ( array, offset ) {
  6959. this.array = array;
  6960. this.offset = offset;
  6961. };
  6962. THREE.ProxyVector2.prototype = Object.create( THREE.Vector2.prototype );
  6963. Object.defineProperties( THREE.ProxyVector2.prototype, {
  6964. 'x': {
  6965. get: function () { return this.array[ this.offset ]; },
  6966. set: function ( v ) { this.array[ this.offset ] = v; }
  6967. },
  6968. 'y': {
  6969. get: function () { return this.array[ this.offset + 1 ]; },
  6970. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6971. }
  6972. } );
  6973. /**
  6974. * @author mrdoob / http://mrdoob.com/
  6975. * @author jbaicoianu / http://baicoianu.com/
  6976. */
  6977. THREE.ProxyVector3 = function ( array, offset ) {
  6978. this.array = array;
  6979. this.offset = offset;
  6980. };
  6981. THREE.ProxyVector3.prototype = Object.create( THREE.Vector3.prototype );
  6982. Object.defineProperties( THREE.ProxyVector3.prototype, {
  6983. 'x': {
  6984. get: function () { return this.array[ this.offset ]; },
  6985. set: function ( v ) { this.array[ this.offset ] = v; }
  6986. },
  6987. 'y': {
  6988. get: function () { return this.array[ this.offset + 1 ]; },
  6989. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6990. },
  6991. 'z': {
  6992. get: function () { return this.array[ this.offset + 2 ]; },
  6993. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6994. }
  6995. } );
  6996. /**
  6997. * @author mrdoob / http://mrdoob.com/
  6998. * @author jbaicoianu / http://baicoianu.com/
  6999. */
  7000. THREE.ProxyVector4 = function ( array, offset ) {
  7001. this.array = array;
  7002. this.offset = offset;
  7003. };
  7004. THREE.ProxyVector4.prototype = Object.create( THREE.Vector4.prototype );
  7005. Object.defineProperties( THREE.ProxyVector4.prototype, {
  7006. 'x': {
  7007. get: function () { return this.array[ this.offset ]; },
  7008. set: function ( v ) { this.array[ this.offset ] = v; }
  7009. },
  7010. 'y': {
  7011. get: function () { return this.array[ this.offset + 1 ]; },
  7012. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  7013. },
  7014. 'z': {
  7015. get: function () { return this.array[ this.offset + 2 ]; },
  7016. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  7017. },
  7018. 'w': {
  7019. get: function () { return this.array[ this.offset + 3 ]; },
  7020. set: function ( v ) { this.array[ this.offset + 3 ] = v; }
  7021. }
  7022. } );
  7023. /**
  7024. * @author jbaicoianu / http://baicoianu.com/
  7025. */
  7026. THREE.ProxyFace3 = function ( array, offset, vertexNormals, vertexColors, vertexTangents ) {
  7027. this.array = array;
  7028. this.offset = offset;
  7029. this.vertexNormals = vertexNormals || [];
  7030. this.vertexColors = vertexColors || [];
  7031. this.vertexTangents = vertexTangents || [];
  7032. this.normal = new THREE.MultiVector3( this.vertexNormals );
  7033. this.color = new THREE.MultiColor( this.vertexColors );
  7034. //THREE.Face3.call( this, array[offset], array[offset+1], array[offset+2] /*, normal, color, materialIndex */);
  7035. }
  7036. THREE.ProxyFace3.prototype = Object.create( THREE.Face3.prototype );
  7037. Object.defineProperties( THREE.ProxyFace3.prototype, {
  7038. 'a': {
  7039. enumerable: true,
  7040. get: function () { return this.array[ this.offset ]; },
  7041. set: function ( v ) { this.array[ this.offset ] = v; }
  7042. },
  7043. 'b': {
  7044. enumerable: true,
  7045. get: function () { return this.array[ this.offset + 1 ]; },
  7046. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  7047. },
  7048. 'c': {
  7049. enumerable: true,
  7050. get: function () { return this.array[ this.offset + 2 ]; },
  7051. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  7052. },
  7053. } );
  7054. /**
  7055. * @author mrdoob / http://mrdoob.com/
  7056. * @author mikael emtinger / http://gomo.se/
  7057. * @author WestLangley / http://github.com/WestLangley
  7058. */
  7059. THREE.Camera = function () {
  7060. THREE.Object3D.call( this );
  7061. this.matrixWorldInverse = new THREE.Matrix4();
  7062. this.projectionMatrix = new THREE.Matrix4();
  7063. };
  7064. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  7065. THREE.Camera.prototype.lookAt = function () {
  7066. // This routine does not support cameras with rotated and/or translated parent(s)
  7067. var m1 = new THREE.Matrix4();
  7068. return function ( vector ) {
  7069. m1.lookAt( this.position, vector, this.up );
  7070. this.quaternion.setFromRotationMatrix( m1 );
  7071. };
  7072. }();
  7073. THREE.Camera.prototype.clone = function (camera) {
  7074. if ( camera === undefined ) camera = new THREE.Camera();
  7075. THREE.Object3D.prototype.clone.call( this, camera );
  7076. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  7077. camera.projectionMatrix.copy( this.projectionMatrix );
  7078. return camera;
  7079. };
  7080. /**
  7081. * @author alteredq / http://alteredqualia.com/
  7082. */
  7083. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  7084. THREE.Camera.call( this );
  7085. this.left = left;
  7086. this.right = right;
  7087. this.top = top;
  7088. this.bottom = bottom;
  7089. this.near = ( near !== undefined ) ? near : 0.1;
  7090. this.far = ( far !== undefined ) ? far : 2000;
  7091. this.updateProjectionMatrix();
  7092. };
  7093. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  7094. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  7095. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  7096. };
  7097. THREE.OrthographicCamera.prototype.clone = function () {
  7098. var camera = new THREE.OrthographicCamera();
  7099. THREE.Camera.prototype.clone.call( this, camera );
  7100. camera.left = this.left;
  7101. camera.right = this.right;
  7102. camera.top = this.top;
  7103. camera.bottom = this.bottom;
  7104. camera.near = this.near;
  7105. camera.far = this.far;
  7106. return camera;
  7107. };
  7108. /**
  7109. * @author mrdoob / http://mrdoob.com/
  7110. * @author greggman / http://games.greggman.com/
  7111. * @author zz85 / http://www.lab4games.net/zz85/blog
  7112. */
  7113. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  7114. THREE.Camera.call( this );
  7115. this.fov = fov !== undefined ? fov : 50;
  7116. this.aspect = aspect !== undefined ? aspect : 1;
  7117. this.near = near !== undefined ? near : 0.1;
  7118. this.far = far !== undefined ? far : 2000;
  7119. this.updateProjectionMatrix();
  7120. };
  7121. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  7122. /**
  7123. * Uses Focal Length (in mm) to estimate and set FOV
  7124. * 35mm (fullframe) camera is used if frame size is not specified;
  7125. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  7126. */
  7127. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  7128. if ( frameHeight === undefined ) frameHeight = 24;
  7129. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  7130. this.updateProjectionMatrix();
  7131. }
  7132. /**
  7133. * Sets an offset in a larger frustum. This is useful for multi-window or
  7134. * multi-monitor/multi-machine setups.
  7135. *
  7136. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7137. * the monitors are in grid like this
  7138. *
  7139. * +---+---+---+
  7140. * | A | B | C |
  7141. * +---+---+---+
  7142. * | D | E | F |
  7143. * +---+---+---+
  7144. *
  7145. * then for each monitor you would call it like this
  7146. *
  7147. * var w = 1920;
  7148. * var h = 1080;
  7149. * var fullWidth = w * 3;
  7150. * var fullHeight = h * 2;
  7151. *
  7152. * --A--
  7153. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7154. * --B--
  7155. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7156. * --C--
  7157. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7158. * --D--
  7159. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7160. * --E--
  7161. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7162. * --F--
  7163. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7164. *
  7165. * Note there is no reason monitors have to be the same size or in a grid.
  7166. */
  7167. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  7168. this.fullWidth = fullWidth;
  7169. this.fullHeight = fullHeight;
  7170. this.x = x;
  7171. this.y = y;
  7172. this.width = width;
  7173. this.height = height;
  7174. this.updateProjectionMatrix();
  7175. };
  7176. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  7177. if ( this.fullWidth ) {
  7178. var aspect = this.fullWidth / this.fullHeight;
  7179. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  7180. var bottom = -top;
  7181. var left = aspect * bottom;
  7182. var right = aspect * top;
  7183. var width = Math.abs( right - left );
  7184. var height = Math.abs( top - bottom );
  7185. this.projectionMatrix.makeFrustum(
  7186. left + this.x * width / this.fullWidth,
  7187. left + ( this.x + this.width ) * width / this.fullWidth,
  7188. top - ( this.y + this.height ) * height / this.fullHeight,
  7189. top - this.y * height / this.fullHeight,
  7190. this.near,
  7191. this.far
  7192. );
  7193. } else {
  7194. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  7195. }
  7196. };
  7197. THREE.PerspectiveCamera.prototype.clone = function () {
  7198. var camera = new THREE.PerspectiveCamera();
  7199. THREE.Camera.prototype.clone.call( this, camera );
  7200. camera.fov = this.fov;
  7201. camera.aspect = this.aspect;
  7202. camera.near = this.near;
  7203. camera.far = this.far;
  7204. return camera;
  7205. };
  7206. /**
  7207. * @author mrdoob / http://mrdoob.com/
  7208. * @author alteredq / http://alteredqualia.com/
  7209. */
  7210. THREE.Light = function ( color ) {
  7211. THREE.Object3D.call( this );
  7212. this.color = new THREE.Color( color );
  7213. };
  7214. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  7215. THREE.Light.prototype.clone = function ( light ) {
  7216. if ( light === undefined ) light = new THREE.Light();
  7217. THREE.Object3D.prototype.clone.call( this, light );
  7218. light.color.copy( this.color );
  7219. return light;
  7220. };
  7221. /**
  7222. * @author mrdoob / http://mrdoob.com/
  7223. */
  7224. THREE.AmbientLight = function ( color ) {
  7225. THREE.Light.call( this, color );
  7226. };
  7227. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  7228. THREE.AmbientLight.prototype.clone = function () {
  7229. var light = new THREE.AmbientLight();
  7230. THREE.Light.prototype.clone.call( this, light );
  7231. return light;
  7232. };
  7233. /**
  7234. * @author MPanknin / http://www.redplant.de/
  7235. * @author alteredq / http://alteredqualia.com/
  7236. */
  7237. THREE.AreaLight = function ( color, intensity ) {
  7238. THREE.Light.call( this, color );
  7239. this.normal = new THREE.Vector3( 0, -1, 0 );
  7240. this.right = new THREE.Vector3( 1, 0, 0 );
  7241. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7242. this.width = 1.0;
  7243. this.height = 1.0;
  7244. this.constantAttenuation = 1.5;
  7245. this.linearAttenuation = 0.5;
  7246. this.quadraticAttenuation = 0.1;
  7247. };
  7248. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  7249. /**
  7250. * @author mrdoob / http://mrdoob.com/
  7251. * @author alteredq / http://alteredqualia.com/
  7252. */
  7253. THREE.DirectionalLight = function ( color, intensity ) {
  7254. THREE.Light.call( this, color );
  7255. this.position.set( 0, 1, 0 );
  7256. this.target = new THREE.Object3D();
  7257. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7258. this.castShadow = false;
  7259. this.onlyShadow = false;
  7260. //
  7261. this.shadowCameraNear = 50;
  7262. this.shadowCameraFar = 5000;
  7263. this.shadowCameraLeft = -500;
  7264. this.shadowCameraRight = 500;
  7265. this.shadowCameraTop = 500;
  7266. this.shadowCameraBottom = -500;
  7267. this.shadowCameraVisible = false;
  7268. this.shadowBias = 0;
  7269. this.shadowDarkness = 0.5;
  7270. this.shadowMapWidth = 512;
  7271. this.shadowMapHeight = 512;
  7272. //
  7273. this.shadowCascade = false;
  7274. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  7275. this.shadowCascadeCount = 2;
  7276. this.shadowCascadeBias = [ 0, 0, 0 ];
  7277. this.shadowCascadeWidth = [ 512, 512, 512 ];
  7278. this.shadowCascadeHeight = [ 512, 512, 512 ];
  7279. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  7280. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  7281. this.shadowCascadeArray = [];
  7282. //
  7283. this.shadowMap = null;
  7284. this.shadowMapSize = null;
  7285. this.shadowCamera = null;
  7286. this.shadowMatrix = null;
  7287. };
  7288. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  7289. THREE.DirectionalLight.prototype.clone = function () {
  7290. var light = new THREE.DirectionalLight();
  7291. THREE.Light.prototype.clone.call( this, light );
  7292. light.target = this.target.clone();
  7293. light.intensity = this.intensity;
  7294. light.castShadow = this.castShadow;
  7295. light.onlyShadow = this.onlyShadow;
  7296. //
  7297. light.shadowCameraNear = this.shadowCameraNear;
  7298. light.shadowCameraFar = this.shadowCameraFar;
  7299. light.shadowCameraLeft = this.shadowCameraLeft;
  7300. light.shadowCameraRight = this.shadowCameraRight;
  7301. light.shadowCameraTop = this.shadowCameraTop;
  7302. light.shadowCameraBottom = this.shadowCameraBottom;
  7303. light.shadowCameraVisible = this.shadowCameraVisible;
  7304. light.shadowBias = this.shadowBias;
  7305. light.shadowDarkness = this.shadowDarkness;
  7306. light.shadowMapWidth = this.shadowMapWidth;
  7307. light.shadowMapHeight = this.shadowMapHeight;
  7308. //
  7309. light.shadowCascade = this.shadowCascade;
  7310. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  7311. light.shadowCascadeCount = this.shadowCascadeCount;
  7312. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  7313. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  7314. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  7315. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  7316. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  7317. return light;
  7318. };
  7319. /**
  7320. * @author alteredq / http://alteredqualia.com/
  7321. */
  7322. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  7323. THREE.Light.call( this, skyColor );
  7324. this.position.set( 0, 100, 0 );
  7325. this.groundColor = new THREE.Color( groundColor );
  7326. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7327. };
  7328. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  7329. THREE.HemisphereLight.prototype.clone = function () {
  7330. var light = new THREE.HemisphereLight();
  7331. THREE.Light.prototype.clone.call( this, light );
  7332. light.groundColor.copy( this.groundColor );
  7333. light.intensity = this.intensity;
  7334. return light;
  7335. };
  7336. /**
  7337. * @author mrdoob / http://mrdoob.com/
  7338. */
  7339. THREE.PointLight = function ( color, intensity, distance ) {
  7340. THREE.Light.call( this, color );
  7341. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7342. this.distance = ( distance !== undefined ) ? distance : 0;
  7343. };
  7344. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  7345. THREE.PointLight.prototype.clone = function () {
  7346. var light = new THREE.PointLight();
  7347. THREE.Light.prototype.clone.call( this, light );
  7348. light.intensity = this.intensity;
  7349. light.distance = this.distance;
  7350. return light;
  7351. };
  7352. /**
  7353. * @author alteredq / http://alteredqualia.com/
  7354. */
  7355. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  7356. THREE.Light.call( this, color );
  7357. this.position.set( 0, 1, 0 );
  7358. this.target = new THREE.Object3D();
  7359. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7360. this.distance = ( distance !== undefined ) ? distance : 0;
  7361. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  7362. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  7363. this.castShadow = false;
  7364. this.onlyShadow = false;
  7365. //
  7366. this.shadowCameraNear = 50;
  7367. this.shadowCameraFar = 5000;
  7368. this.shadowCameraFov = 50;
  7369. this.shadowCameraVisible = false;
  7370. this.shadowBias = 0;
  7371. this.shadowDarkness = 0.5;
  7372. this.shadowMapWidth = 512;
  7373. this.shadowMapHeight = 512;
  7374. //
  7375. this.shadowMap = null;
  7376. this.shadowMapSize = null;
  7377. this.shadowCamera = null;
  7378. this.shadowMatrix = null;
  7379. };
  7380. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  7381. THREE.SpotLight.prototype.clone = function () {
  7382. var light = new THREE.SpotLight();
  7383. THREE.Light.prototype.clone.call( this, light );
  7384. light.target = this.target.clone();
  7385. light.intensity = this.intensity;
  7386. light.distance = this.distance;
  7387. light.angle = this.angle;
  7388. light.exponent = this.exponent;
  7389. light.castShadow = this.castShadow;
  7390. light.onlyShadow = this.onlyShadow;
  7391. //
  7392. light.shadowCameraNear = this.shadowCameraNear;
  7393. light.shadowCameraFar = this.shadowCameraFar;
  7394. light.shadowCameraFov = this.shadowCameraFov;
  7395. light.shadowCameraVisible = this.shadowCameraVisible;
  7396. light.shadowBias = this.shadowBias;
  7397. light.shadowDarkness = this.shadowDarkness;
  7398. light.shadowMapWidth = this.shadowMapWidth;
  7399. light.shadowMapHeight = this.shadowMapHeight;
  7400. return light;
  7401. };
  7402. /**
  7403. * @author mrdoob / http://mrdoob.com/
  7404. */
  7405. THREE.Cache = function () {
  7406. this.files = {};
  7407. };
  7408. THREE.Cache.prototype = {
  7409. constructor: THREE.Cache,
  7410. add: function ( key, file ) {
  7411. // console.log( 'THREE.Cache', 'Adding key:', key );
  7412. this.files[ key ] = file;
  7413. },
  7414. get: function ( key ) {
  7415. // console.log( 'THREE.Cache', 'Checking key:', key );
  7416. return this.files[ key ];
  7417. },
  7418. remove: function ( key ) {
  7419. delete this.files[ key ];
  7420. },
  7421. clear: function () {
  7422. this.files = {}
  7423. }
  7424. };
  7425. /**
  7426. * @author alteredq / http://alteredqualia.com/
  7427. */
  7428. THREE.Loader = function ( showStatus ) {
  7429. this.showStatus = showStatus;
  7430. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  7431. this.imageLoader = new THREE.ImageLoader();
  7432. this.onLoadStart = function () {};
  7433. this.onLoadProgress = function () {};
  7434. this.onLoadComplete = function () {};
  7435. };
  7436. THREE.Loader.prototype = {
  7437. constructor: THREE.Loader,
  7438. crossOrigin: undefined,
  7439. addStatusElement: function () {
  7440. var e = document.createElement( "div" );
  7441. e.style.position = "absolute";
  7442. e.style.right = "0px";
  7443. e.style.top = "0px";
  7444. e.style.fontSize = "0.8em";
  7445. e.style.textAlign = "left";
  7446. e.style.background = "rgba(0,0,0,0.25)";
  7447. e.style.color = "#fff";
  7448. e.style.width = "120px";
  7449. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  7450. e.style.zIndex = 1000;
  7451. e.innerHTML = "Loading ...";
  7452. return e;
  7453. },
  7454. updateProgress: function ( progress ) {
  7455. var message = "Loaded ";
  7456. if ( progress.total ) {
  7457. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  7458. } else {
  7459. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  7460. }
  7461. this.statusDomElement.innerHTML = message;
  7462. },
  7463. extractUrlBase: function ( url ) {
  7464. var parts = url.split( '/' );
  7465. if ( parts.length === 1 ) return './';
  7466. parts.pop();
  7467. return parts.join( '/' ) + '/';
  7468. },
  7469. initMaterials: function ( materials, texturePath ) {
  7470. var array = [];
  7471. for ( var i = 0; i < materials.length; ++ i ) {
  7472. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  7473. }
  7474. return array;
  7475. },
  7476. needsTangents: function ( materials ) {
  7477. for( var i = 0, il = materials.length; i < il; i ++ ) {
  7478. var m = materials[ i ];
  7479. if ( m instanceof THREE.ShaderMaterial ) return true;
  7480. }
  7481. return false;
  7482. },
  7483. createMaterial: function ( m, texturePath ) {
  7484. var scope = this;
  7485. function nearest_pow2( n ) {
  7486. var l = Math.log( n ) / Math.LN2;
  7487. return Math.pow( 2, Math.round( l ) );
  7488. }
  7489. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  7490. var isCompressed = /\.dds$/i.test( sourceFile );
  7491. var fullPath = texturePath + sourceFile;
  7492. if ( isCompressed ) {
  7493. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  7494. where[ name ] = texture;
  7495. } else {
  7496. var texture = document.createElement( 'canvas' );
  7497. where[ name ] = new THREE.Texture( texture );
  7498. }
  7499. where[ name ].sourceFile = sourceFile;
  7500. if( repeat ) {
  7501. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  7502. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  7503. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  7504. }
  7505. if ( offset ) {
  7506. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  7507. }
  7508. if ( wrap ) {
  7509. var wrapMap = {
  7510. "repeat": THREE.RepeatWrapping,
  7511. "mirror": THREE.MirroredRepeatWrapping
  7512. }
  7513. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  7514. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  7515. }
  7516. if ( anisotropy ) {
  7517. where[ name ].anisotropy = anisotropy;
  7518. }
  7519. if ( ! isCompressed ) {
  7520. var texture = where[ name ];
  7521. scope.imageLoader.crossOrigin = scope.crossOrigin;
  7522. scope.imageLoader.load( fullPath, function ( image ) {
  7523. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  7524. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  7525. var width = nearest_pow2( image.width );
  7526. var height = nearest_pow2( image.height );
  7527. texture.image.width = width;
  7528. texture.image.height = height;
  7529. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  7530. } else {
  7531. texture.image = image;
  7532. }
  7533. texture.needsUpdate = true;
  7534. } );
  7535. }
  7536. }
  7537. function rgb2hex( rgb ) {
  7538. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  7539. }
  7540. // defaults
  7541. var mtype = "MeshLambertMaterial";
  7542. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  7543. // parameters from model file
  7544. if ( m.shading ) {
  7545. var shading = m.shading.toLowerCase();
  7546. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  7547. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  7548. }
  7549. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  7550. mpars.blending = THREE[ m.blending ];
  7551. }
  7552. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  7553. mpars.transparent = m.transparent;
  7554. }
  7555. if ( m.depthTest !== undefined ) {
  7556. mpars.depthTest = m.depthTest;
  7557. }
  7558. if ( m.depthWrite !== undefined ) {
  7559. mpars.depthWrite = m.depthWrite;
  7560. }
  7561. if ( m.visible !== undefined ) {
  7562. mpars.visible = m.visible;
  7563. }
  7564. if ( m.flipSided !== undefined ) {
  7565. mpars.side = THREE.BackSide;
  7566. }
  7567. if ( m.doubleSided !== undefined ) {
  7568. mpars.side = THREE.DoubleSide;
  7569. }
  7570. if ( m.wireframe !== undefined ) {
  7571. mpars.wireframe = m.wireframe;
  7572. }
  7573. if ( m.vertexColors !== undefined ) {
  7574. if ( m.vertexColors === "face" ) {
  7575. mpars.vertexColors = THREE.FaceColors;
  7576. } else if ( m.vertexColors ) {
  7577. mpars.vertexColors = THREE.VertexColors;
  7578. }
  7579. }
  7580. // colors
  7581. if ( m.colorDiffuse ) {
  7582. mpars.color = rgb2hex( m.colorDiffuse );
  7583. } else if ( m.DbgColor ) {
  7584. mpars.color = m.DbgColor;
  7585. }
  7586. if ( m.colorSpecular ) {
  7587. mpars.specular = rgb2hex( m.colorSpecular );
  7588. }
  7589. if ( m.colorAmbient ) {
  7590. mpars.ambient = rgb2hex( m.colorAmbient );
  7591. }
  7592. // modifiers
  7593. if ( m.transparency ) {
  7594. mpars.opacity = m.transparency;
  7595. }
  7596. if ( m.specularCoef ) {
  7597. mpars.shininess = m.specularCoef;
  7598. }
  7599. // textures
  7600. if ( m.mapDiffuse && texturePath ) {
  7601. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  7602. }
  7603. if ( m.mapLight && texturePath ) {
  7604. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  7605. }
  7606. if ( m.mapBump && texturePath ) {
  7607. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  7608. }
  7609. if ( m.mapNormal && texturePath ) {
  7610. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  7611. }
  7612. if ( m.mapSpecular && texturePath ) {
  7613. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  7614. }
  7615. //
  7616. if ( m.mapBumpScale ) {
  7617. mpars.bumpScale = m.mapBumpScale;
  7618. }
  7619. // special case for normal mapped material
  7620. if ( m.mapNormal ) {
  7621. var shader = THREE.ShaderLib[ "normalmap" ];
  7622. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7623. uniforms[ "tNormal" ].value = mpars.normalMap;
  7624. if ( m.mapNormalFactor ) {
  7625. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  7626. }
  7627. if ( mpars.map ) {
  7628. uniforms[ "tDiffuse" ].value = mpars.map;
  7629. uniforms[ "enableDiffuse" ].value = true;
  7630. }
  7631. if ( mpars.specularMap ) {
  7632. uniforms[ "tSpecular" ].value = mpars.specularMap;
  7633. uniforms[ "enableSpecular" ].value = true;
  7634. }
  7635. if ( mpars.lightMap ) {
  7636. uniforms[ "tAO" ].value = mpars.lightMap;
  7637. uniforms[ "enableAO" ].value = true;
  7638. }
  7639. // for the moment don't handle displacement texture
  7640. uniforms[ "diffuse" ].value.setHex( mpars.color );
  7641. uniforms[ "specular" ].value.setHex( mpars.specular );
  7642. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  7643. uniforms[ "shininess" ].value = mpars.shininess;
  7644. if ( mpars.opacity !== undefined ) {
  7645. uniforms[ "opacity" ].value = mpars.opacity;
  7646. }
  7647. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7648. var material = new THREE.ShaderMaterial( parameters );
  7649. if ( mpars.transparent ) {
  7650. material.transparent = true;
  7651. }
  7652. } else {
  7653. var material = new THREE[ mtype ]( mpars );
  7654. }
  7655. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  7656. return material;
  7657. }
  7658. };
  7659. /**
  7660. * @author mrdoob / http://mrdoob.com/
  7661. */
  7662. THREE.XHRLoader = function ( manager ) {
  7663. this.cache = new THREE.Cache();
  7664. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7665. };
  7666. THREE.XHRLoader.prototype = {
  7667. constructor: THREE.XHRLoader,
  7668. load: function ( url, onLoad, onProgress, onError ) {
  7669. var scope = this;
  7670. var cached = scope.cache.get( url );
  7671. if ( cached !== undefined ) {
  7672. onLoad( cached );
  7673. return;
  7674. }
  7675. var request = new XMLHttpRequest();
  7676. if ( onLoad !== undefined ) {
  7677. request.addEventListener( 'load', function ( event ) {
  7678. scope.cache.add( url, event.target.responseText );
  7679. onLoad( event.target.responseText );
  7680. scope.manager.itemEnd( url );
  7681. }, false );
  7682. }
  7683. if ( onProgress !== undefined ) {
  7684. request.addEventListener( 'progress', function ( event ) {
  7685. onProgress( event );
  7686. }, false );
  7687. }
  7688. if ( onError !== undefined ) {
  7689. request.addEventListener( 'error', function ( event ) {
  7690. onError( event );
  7691. }, false );
  7692. }
  7693. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  7694. request.open( 'GET', url, true );
  7695. request.send( null );
  7696. scope.manager.itemStart( url );
  7697. },
  7698. setCrossOrigin: function ( value ) {
  7699. this.crossOrigin = value;
  7700. }
  7701. };
  7702. /**
  7703. * @author mrdoob / http://mrdoob.com/
  7704. */
  7705. THREE.ImageLoader = function ( manager ) {
  7706. this.cache = new THREE.Cache();
  7707. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7708. };
  7709. THREE.ImageLoader.prototype = {
  7710. constructor: THREE.ImageLoader,
  7711. load: function ( url, onLoad, onProgress, onError ) {
  7712. var scope = this;
  7713. var cached = scope.cache.get( url );
  7714. if ( cached !== undefined ) {
  7715. onLoad( cached );
  7716. return;
  7717. }
  7718. var image = document.createElement( 'img' );
  7719. if ( onLoad !== undefined ) {
  7720. image.addEventListener( 'load', function ( event ) {
  7721. scope.cache.add( url, this );
  7722. onLoad( this );
  7723. scope.manager.itemEnd( url );
  7724. }, false );
  7725. }
  7726. if ( onProgress !== undefined ) {
  7727. image.addEventListener( 'progress', function ( event ) {
  7728. onProgress( event );
  7729. }, false );
  7730. }
  7731. if ( onError !== undefined ) {
  7732. image.addEventListener( 'error', function ( event ) {
  7733. onError( event );
  7734. }, false );
  7735. }
  7736. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7737. image.src = url;
  7738. scope.manager.itemStart( url );
  7739. return image;
  7740. },
  7741. setCrossOrigin: function ( value ) {
  7742. this.crossOrigin = value;
  7743. }
  7744. }
  7745. /**
  7746. * @author mrdoob / http://mrdoob.com/
  7747. * @author alteredq / http://alteredqualia.com/
  7748. */
  7749. THREE.JSONLoader = function ( showStatus ) {
  7750. THREE.Loader.call( this, showStatus );
  7751. this.withCredentials = false;
  7752. };
  7753. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7754. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7755. var scope = this;
  7756. // todo: unify load API to for easier SceneLoader use
  7757. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  7758. this.onLoadStart();
  7759. this.loadAjaxJSON( this, url, callback, texturePath );
  7760. };
  7761. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7762. var xhr = new XMLHttpRequest();
  7763. var length = 0;
  7764. xhr.onreadystatechange = function () {
  7765. if ( xhr.readyState === xhr.DONE ) {
  7766. if ( xhr.status === 200 || xhr.status === 0 ) {
  7767. if ( xhr.responseText ) {
  7768. var json = JSON.parse( xhr.responseText );
  7769. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7770. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7771. return;
  7772. }
  7773. var result = context.parse( json, texturePath );
  7774. callback( result.geometry, result.materials );
  7775. } else {
  7776. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7777. }
  7778. // in context of more complex asset initialization
  7779. // do not block on single failed file
  7780. // maybe should go even one more level up
  7781. context.onLoadComplete();
  7782. } else {
  7783. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7784. }
  7785. } else if ( xhr.readyState === xhr.LOADING ) {
  7786. if ( callbackProgress ) {
  7787. if ( length === 0 ) {
  7788. length = xhr.getResponseHeader( 'Content-Length' );
  7789. }
  7790. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7791. }
  7792. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7793. if ( callbackProgress !== undefined ) {
  7794. length = xhr.getResponseHeader( "Content-Length" );
  7795. }
  7796. }
  7797. };
  7798. xhr.open( "GET", url, true );
  7799. xhr.withCredentials = this.withCredentials;
  7800. xhr.send( null );
  7801. };
  7802. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7803. var scope = this,
  7804. geometry = new THREE.Geometry(),
  7805. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7806. parseModel( scale );
  7807. parseSkin();
  7808. parseMorphing( scale );
  7809. geometry.computeFaceNormals();
  7810. geometry.computeBoundingSphere();
  7811. function parseModel( scale ) {
  7812. function isBitSet( value, position ) {
  7813. return value & ( 1 << position );
  7814. }
  7815. var i, j, fi,
  7816. offset, zLength,
  7817. colorIndex, normalIndex, uvIndex, materialIndex,
  7818. type,
  7819. isQuad,
  7820. hasMaterial,
  7821. hasFaceVertexUv,
  7822. hasFaceNormal, hasFaceVertexNormal,
  7823. hasFaceColor, hasFaceVertexColor,
  7824. vertex, face, faceA, faceB, color, hex, normal,
  7825. uvLayer, uv, u, v,
  7826. faces = json.faces,
  7827. vertices = json.vertices,
  7828. normals = json.normals,
  7829. colors = json.colors,
  7830. nUvLayers = 0;
  7831. if ( json.uvs !== undefined ) {
  7832. // disregard empty arrays
  7833. for ( i = 0; i < json.uvs.length; i++ ) {
  7834. if ( json.uvs[ i ].length ) nUvLayers ++;
  7835. }
  7836. for ( i = 0; i < nUvLayers; i++ ) {
  7837. geometry.faceVertexUvs[ i ] = [];
  7838. }
  7839. }
  7840. offset = 0;
  7841. zLength = vertices.length;
  7842. while ( offset < zLength ) {
  7843. vertex = new THREE.Vector3();
  7844. vertex.x = vertices[ offset ++ ] * scale;
  7845. vertex.y = vertices[ offset ++ ] * scale;
  7846. vertex.z = vertices[ offset ++ ] * scale;
  7847. geometry.vertices.push( vertex );
  7848. }
  7849. offset = 0;
  7850. zLength = faces.length;
  7851. while ( offset < zLength ) {
  7852. type = faces[ offset ++ ];
  7853. isQuad = isBitSet( type, 0 );
  7854. hasMaterial = isBitSet( type, 1 );
  7855. hasFaceVertexUv = isBitSet( type, 3 );
  7856. hasFaceNormal = isBitSet( type, 4 );
  7857. hasFaceVertexNormal = isBitSet( type, 5 );
  7858. hasFaceColor = isBitSet( type, 6 );
  7859. hasFaceVertexColor = isBitSet( type, 7 );
  7860. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7861. if ( isQuad ) {
  7862. faceA = new THREE.Face3();
  7863. faceA.a = faces[ offset ];
  7864. faceA.b = faces[ offset + 1 ];
  7865. faceA.c = faces[ offset + 3 ];
  7866. faceB = new THREE.Face3();
  7867. faceB.a = faces[ offset + 1 ];
  7868. faceB.b = faces[ offset + 2 ];
  7869. faceB.c = faces[ offset + 3 ];
  7870. offset += 4;
  7871. if ( hasMaterial ) {
  7872. materialIndex = faces[ offset ++ ];
  7873. faceA.materialIndex = materialIndex;
  7874. faceB.materialIndex = materialIndex;
  7875. }
  7876. // to get face <=> uv index correspondence
  7877. fi = geometry.faces.length;
  7878. if ( hasFaceVertexUv ) {
  7879. for ( i = 0; i < nUvLayers; i++ ) {
  7880. uvLayer = json.uvs[ i ];
  7881. geometry.faceVertexUvs[ i ][ fi ] = [];
  7882. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7883. for ( j = 0; j < 4; j ++ ) {
  7884. uvIndex = faces[ offset ++ ];
  7885. u = uvLayer[ uvIndex * 2 ];
  7886. v = uvLayer[ uvIndex * 2 + 1 ];
  7887. uv = new THREE.Vector2( u, v );
  7888. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7889. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7890. }
  7891. }
  7892. }
  7893. if ( hasFaceNormal ) {
  7894. normalIndex = faces[ offset ++ ] * 3;
  7895. faceA.normal.set(
  7896. normals[ normalIndex ++ ],
  7897. normals[ normalIndex ++ ],
  7898. normals[ normalIndex ]
  7899. );
  7900. faceB.normal.copy( faceA.normal );
  7901. }
  7902. if ( hasFaceVertexNormal ) {
  7903. for ( i = 0; i < 4; i++ ) {
  7904. normalIndex = faces[ offset ++ ] * 3;
  7905. normal = new THREE.Vector3(
  7906. normals[ normalIndex ++ ],
  7907. normals[ normalIndex ++ ],
  7908. normals[ normalIndex ]
  7909. );
  7910. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7911. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7912. }
  7913. }
  7914. if ( hasFaceColor ) {
  7915. colorIndex = faces[ offset ++ ];
  7916. hex = colors[ colorIndex ];
  7917. faceA.color.setHex( hex );
  7918. faceB.color.setHex( hex );
  7919. }
  7920. if ( hasFaceVertexColor ) {
  7921. for ( i = 0; i < 4; i++ ) {
  7922. colorIndex = faces[ offset ++ ];
  7923. hex = colors[ colorIndex ];
  7924. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7925. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7926. }
  7927. }
  7928. geometry.faces.push( faceA );
  7929. geometry.faces.push( faceB );
  7930. } else {
  7931. face = new THREE.Face3();
  7932. face.a = faces[ offset ++ ];
  7933. face.b = faces[ offset ++ ];
  7934. face.c = faces[ offset ++ ];
  7935. if ( hasMaterial ) {
  7936. materialIndex = faces[ offset ++ ];
  7937. face.materialIndex = materialIndex;
  7938. }
  7939. // to get face <=> uv index correspondence
  7940. fi = geometry.faces.length;
  7941. if ( hasFaceVertexUv ) {
  7942. for ( i = 0; i < nUvLayers; i++ ) {
  7943. uvLayer = json.uvs[ i ];
  7944. geometry.faceVertexUvs[ i ][ fi ] = [];
  7945. for ( j = 0; j < 3; j ++ ) {
  7946. uvIndex = faces[ offset ++ ];
  7947. u = uvLayer[ uvIndex * 2 ];
  7948. v = uvLayer[ uvIndex * 2 + 1 ];
  7949. uv = new THREE.Vector2( u, v );
  7950. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7951. }
  7952. }
  7953. }
  7954. if ( hasFaceNormal ) {
  7955. normalIndex = faces[ offset ++ ] * 3;
  7956. face.normal.set(
  7957. normals[ normalIndex ++ ],
  7958. normals[ normalIndex ++ ],
  7959. normals[ normalIndex ]
  7960. );
  7961. }
  7962. if ( hasFaceVertexNormal ) {
  7963. for ( i = 0; i < 3; i++ ) {
  7964. normalIndex = faces[ offset ++ ] * 3;
  7965. normal = new THREE.Vector3(
  7966. normals[ normalIndex ++ ],
  7967. normals[ normalIndex ++ ],
  7968. normals[ normalIndex ]
  7969. );
  7970. face.vertexNormals.push( normal );
  7971. }
  7972. }
  7973. if ( hasFaceColor ) {
  7974. colorIndex = faces[ offset ++ ];
  7975. face.color.setHex( colors[ colorIndex ] );
  7976. }
  7977. if ( hasFaceVertexColor ) {
  7978. for ( i = 0; i < 3; i++ ) {
  7979. colorIndex = faces[ offset ++ ];
  7980. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7981. }
  7982. }
  7983. geometry.faces.push( face );
  7984. }
  7985. }
  7986. };
  7987. function parseSkin() {
  7988. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7989. if ( json.skinWeights ) {
  7990. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7991. var x = json.skinWeights[ i ];
  7992. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7993. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7994. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7995. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7996. }
  7997. }
  7998. if ( json.skinIndices ) {
  7999. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  8000. var a = json.skinIndices[ i ];
  8001. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  8002. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  8003. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  8004. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  8005. }
  8006. }
  8007. geometry.bones = json.bones;
  8008. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  8009. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  8010. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  8011. }
  8012. // could change this to json.animations[0] or remove completely
  8013. geometry.animation = json.animation;
  8014. geometry.animations = json.animations;
  8015. };
  8016. function parseMorphing( scale ) {
  8017. if ( json.morphTargets !== undefined ) {
  8018. var i, l, v, vl, dstVertices, srcVertices;
  8019. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  8020. geometry.morphTargets[ i ] = {};
  8021. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  8022. geometry.morphTargets[ i ].vertices = [];
  8023. dstVertices = geometry.morphTargets[ i ].vertices;
  8024. srcVertices = json.morphTargets [ i ].vertices;
  8025. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  8026. var vertex = new THREE.Vector3();
  8027. vertex.x = srcVertices[ v ] * scale;
  8028. vertex.y = srcVertices[ v + 1 ] * scale;
  8029. vertex.z = srcVertices[ v + 2 ] * scale;
  8030. dstVertices.push( vertex );
  8031. }
  8032. }
  8033. }
  8034. if ( json.morphColors !== undefined ) {
  8035. var i, l, c, cl, dstColors, srcColors, color;
  8036. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  8037. geometry.morphColors[ i ] = {};
  8038. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  8039. geometry.morphColors[ i ].colors = [];
  8040. dstColors = geometry.morphColors[ i ].colors;
  8041. srcColors = json.morphColors [ i ].colors;
  8042. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  8043. color = new THREE.Color( 0xffaa00 );
  8044. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  8045. dstColors.push( color );
  8046. }
  8047. }
  8048. }
  8049. };
  8050. if ( json.materials === undefined || json.materials.length === 0 ) {
  8051. return { geometry: geometry };
  8052. } else {
  8053. var materials = this.initMaterials( json.materials, texturePath );
  8054. if ( this.needsTangents( materials ) ) {
  8055. geometry.computeTangents();
  8056. }
  8057. return { geometry: geometry, materials: materials };
  8058. }
  8059. };
  8060. /**
  8061. * @author mrdoob / http://mrdoob.com/
  8062. */
  8063. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  8064. var scope = this;
  8065. var loaded = 0, total = 0;
  8066. this.onLoad = onLoad;
  8067. this.onProgress = onProgress;
  8068. this.onError = onError;
  8069. this.itemStart = function ( url ) {
  8070. total ++;
  8071. };
  8072. this.itemEnd = function ( url ) {
  8073. loaded ++;
  8074. if ( scope.onProgress !== undefined ) {
  8075. scope.onProgress( url, loaded, total );
  8076. }
  8077. if ( loaded === total && scope.onLoad !== undefined ) {
  8078. scope.onLoad();
  8079. }
  8080. };
  8081. };
  8082. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  8083. /**
  8084. * @author mrdoob / http://mrdoob.com/
  8085. */
  8086. THREE.BufferGeometryLoader = function ( manager ) {
  8087. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8088. };
  8089. THREE.BufferGeometryLoader.prototype = {
  8090. constructor: THREE.BufferGeometryLoader,
  8091. load: function ( url, onLoad, onProgress, onError ) {
  8092. var scope = this;
  8093. var loader = new THREE.XHRLoader();
  8094. loader.setCrossOrigin( this.crossOrigin );
  8095. loader.load( url, function ( text ) {
  8096. onLoad( scope.parse( JSON.parse( text ) ) );
  8097. } );
  8098. },
  8099. setCrossOrigin: function ( value ) {
  8100. this.crossOrigin = value;
  8101. },
  8102. parse: function ( json ) {
  8103. var geometry = new THREE.BufferGeometry();
  8104. var attributes = json.attributes;
  8105. var offsets = json.offsets;
  8106. var boundingSphere = json.boundingSphere;
  8107. for ( var key in attributes ) {
  8108. var attribute = attributes[ key ];
  8109. geometry.attributes[ key ] = {
  8110. itemSize: attribute.itemSize,
  8111. array: new self[ attribute.type ]( attribute.array )
  8112. }
  8113. }
  8114. if ( offsets !== undefined ) {
  8115. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  8116. }
  8117. if ( boundingSphere !== undefined ) {
  8118. geometry.boundingSphere = new THREE.Sphere(
  8119. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  8120. boundingSphere.radius
  8121. );
  8122. }
  8123. return geometry;
  8124. }
  8125. };
  8126. /**
  8127. * @author mrdoob / http://mrdoob.com/
  8128. */
  8129. THREE.MaterialLoader = function ( manager ) {
  8130. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8131. };
  8132. THREE.MaterialLoader.prototype = {
  8133. constructor: THREE.MaterialLoader,
  8134. load: function ( url, onLoad, onProgress, onError ) {
  8135. var scope = this;
  8136. var loader = new THREE.XHRLoader();
  8137. loader.setCrossOrigin( this.crossOrigin );
  8138. loader.load( url, function ( text ) {
  8139. onLoad( scope.parse( JSON.parse( text ) ) );
  8140. } );
  8141. },
  8142. setCrossOrigin: function ( value ) {
  8143. this.crossOrigin = value;
  8144. },
  8145. parse: function ( json ) {
  8146. var material = new THREE[ json.type ];
  8147. if ( json.color !== undefined ) material.color.setHex( json.color );
  8148. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  8149. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  8150. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  8151. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  8152. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  8153. if ( json.blending !== undefined ) material.blending = json.blending;
  8154. if ( json.side !== undefined ) material.side = json.side;
  8155. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  8156. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  8157. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  8158. if ( json.materials !== undefined ) {
  8159. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  8160. material.materials.push( this.parse( json.materials[ i ] ) );
  8161. }
  8162. }
  8163. return material;
  8164. }
  8165. };
  8166. /**
  8167. * @author mrdoob / http://mrdoob.com/
  8168. */
  8169. THREE.ObjectLoader = function ( manager ) {
  8170. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8171. };
  8172. THREE.ObjectLoader.prototype = {
  8173. constructor: THREE.ObjectLoader,
  8174. load: function ( url, onLoad, onProgress, onError ) {
  8175. var scope = this;
  8176. var loader = new THREE.XHRLoader( scope.manager );
  8177. loader.setCrossOrigin( this.crossOrigin );
  8178. loader.load( url, function ( text ) {
  8179. onLoad( scope.parse( JSON.parse( text ) ) );
  8180. } );
  8181. },
  8182. setCrossOrigin: function ( value ) {
  8183. this.crossOrigin = value;
  8184. },
  8185. parse: function ( json ) {
  8186. var geometries = this.parseGeometries( json.geometries );
  8187. var materials = this.parseMaterials( json.materials );
  8188. var object = this.parseObject( json.object, geometries, materials );
  8189. return object;
  8190. },
  8191. parseGeometries: function ( json ) {
  8192. var geometries = {};
  8193. if ( json !== undefined ) {
  8194. var geometryLoader = new THREE.JSONLoader();
  8195. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  8196. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8197. var geometry;
  8198. var data = json[ i ];
  8199. switch ( data.type ) {
  8200. case 'PlaneGeometry':
  8201. geometry = new THREE.PlaneGeometry(
  8202. data.width,
  8203. data.height,
  8204. data.widthSegments,
  8205. data.heightSegments
  8206. );
  8207. break;
  8208. case 'BoxGeometry':
  8209. case 'CubeGeometry': // DEPRECATED
  8210. geometry = new THREE.BoxGeometry(
  8211. data.width,
  8212. data.height,
  8213. data.depth,
  8214. data.widthSegments,
  8215. data.heightSegments,
  8216. data.depthSegments
  8217. );
  8218. break;
  8219. case 'CircleGeometry':
  8220. geometry = new THREE.CircleGeometry(
  8221. data.radius,
  8222. data.segments
  8223. );
  8224. break;
  8225. case 'CylinderGeometry':
  8226. geometry = new THREE.CylinderGeometry(
  8227. data.radiusTop,
  8228. data.radiusBottom,
  8229. data.height,
  8230. data.radialSegments,
  8231. data.heightSegments,
  8232. data.openEnded
  8233. );
  8234. break;
  8235. case 'SphereGeometry':
  8236. geometry = new THREE.SphereGeometry(
  8237. data.radius,
  8238. data.widthSegments,
  8239. data.heightSegments,
  8240. data.phiStart,
  8241. data.phiLength,
  8242. data.thetaStart,
  8243. data.thetaLength
  8244. );
  8245. break;
  8246. case 'IcosahedronGeometry':
  8247. geometry = new THREE.IcosahedronGeometry(
  8248. data.radius,
  8249. data.detail
  8250. );
  8251. break;
  8252. case 'TorusGeometry':
  8253. geometry = new THREE.TorusGeometry(
  8254. data.radius,
  8255. data.tube,
  8256. data.radialSegments,
  8257. data.tubularSegments,
  8258. data.arc
  8259. );
  8260. break;
  8261. case 'TorusKnotGeometry':
  8262. geometry = new THREE.TorusKnotGeometry(
  8263. data.radius,
  8264. data.tube,
  8265. data.radialSegments,
  8266. data.tubularSegments,
  8267. data.p,
  8268. data.q,
  8269. data.heightScale
  8270. );
  8271. break;
  8272. case 'BufferGeometry':
  8273. geometry = bufferGeometryLoader.parse( data.data );
  8274. break;
  8275. case 'Geometry':
  8276. geometry = geometryLoader.parse( data.data ).geometry;
  8277. break;
  8278. }
  8279. geometry.uuid = data.uuid;
  8280. if ( data.name !== undefined ) geometry.name = data.name;
  8281. geometries[ data.uuid ] = geometry;
  8282. }
  8283. }
  8284. return geometries;
  8285. },
  8286. parseMaterials: function ( json ) {
  8287. var materials = {};
  8288. if ( json !== undefined ) {
  8289. var loader = new THREE.MaterialLoader();
  8290. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8291. var data = json[ i ];
  8292. var material = loader.parse( data );
  8293. material.uuid = data.uuid;
  8294. if ( data.name !== undefined ) material.name = data.name;
  8295. materials[ data.uuid ] = material;
  8296. }
  8297. }
  8298. return materials;
  8299. },
  8300. parseObject: function () {
  8301. var matrix = new THREE.Matrix4();
  8302. return function ( data, geometries, materials ) {
  8303. var object;
  8304. switch ( data.type ) {
  8305. case 'Scene':
  8306. object = new THREE.Scene();
  8307. break;
  8308. case 'PerspectiveCamera':
  8309. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  8310. break;
  8311. case 'OrthographicCamera':
  8312. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  8313. break;
  8314. case 'AmbientLight':
  8315. object = new THREE.AmbientLight( data.color );
  8316. break;
  8317. case 'DirectionalLight':
  8318. object = new THREE.DirectionalLight( data.color, data.intensity );
  8319. break;
  8320. case 'PointLight':
  8321. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  8322. break;
  8323. case 'SpotLight':
  8324. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  8325. break;
  8326. case 'HemisphereLight':
  8327. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  8328. break;
  8329. case 'Mesh':
  8330. var geometry = geometries[ data.geometry ];
  8331. var material = materials[ data.material ];
  8332. if ( geometry === undefined ) {
  8333. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  8334. }
  8335. if ( material === undefined ) {
  8336. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  8337. }
  8338. object = new THREE.Mesh( geometry, material );
  8339. break;
  8340. case 'Sprite':
  8341. var material = materials[ data.material ];
  8342. if ( material === undefined ) {
  8343. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  8344. }
  8345. object = new THREE.Sprite( material );
  8346. break;
  8347. default:
  8348. object = new THREE.Object3D();
  8349. }
  8350. object.uuid = data.uuid;
  8351. if ( data.name !== undefined ) object.name = data.name;
  8352. if ( data.matrix !== undefined ) {
  8353. matrix.fromArray( data.matrix );
  8354. matrix.decompose( object.position, object.quaternion, object.scale );
  8355. } else {
  8356. if ( data.position !== undefined ) object.position.fromArray( data.position );
  8357. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  8358. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  8359. }
  8360. if ( data.visible !== undefined ) object.visible = data.visible;
  8361. if ( data.userData !== undefined ) object.userData = data.userData;
  8362. if ( data.children !== undefined ) {
  8363. for ( var child in data.children ) {
  8364. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  8365. }
  8366. }
  8367. return object;
  8368. }
  8369. }()
  8370. };
  8371. /**
  8372. * @author alteredq / http://alteredqualia.com/
  8373. */
  8374. THREE.SceneLoader = function () {
  8375. this.onLoadStart = function () {};
  8376. this.onLoadProgress = function() {};
  8377. this.onLoadComplete = function () {};
  8378. this.callbackSync = function () {};
  8379. this.callbackProgress = function () {};
  8380. this.geometryHandlers = {};
  8381. this.hierarchyHandlers = {};
  8382. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  8383. };
  8384. THREE.SceneLoader.prototype = {
  8385. constructor: THREE.SceneLoader,
  8386. load: function ( url, onLoad, onProgress, onError ) {
  8387. var scope = this;
  8388. var loader = new THREE.XHRLoader( scope.manager );
  8389. loader.setCrossOrigin( this.crossOrigin );
  8390. loader.load( url, function ( text ) {
  8391. scope.parse( JSON.parse( text ), onLoad, url );
  8392. } );
  8393. },
  8394. setCrossOrigin: function ( value ) {
  8395. this.crossOrigin = value;
  8396. },
  8397. addGeometryHandler: function ( typeID, loaderClass ) {
  8398. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  8399. },
  8400. addHierarchyHandler: function ( typeID, loaderClass ) {
  8401. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  8402. },
  8403. parse: function ( json, callbackFinished, url ) {
  8404. var scope = this;
  8405. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  8406. var geometry, material, camera, fog,
  8407. texture, images, color,
  8408. light, hex, intensity,
  8409. counter_models, counter_textures,
  8410. total_models, total_textures,
  8411. result;
  8412. var target_array = [];
  8413. var data = json;
  8414. // async geometry loaders
  8415. for ( var typeID in this.geometryHandlers ) {
  8416. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  8417. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  8418. }
  8419. // async hierachy loaders
  8420. for ( var typeID in this.hierarchyHandlers ) {
  8421. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  8422. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  8423. }
  8424. counter_models = 0;
  8425. counter_textures = 0;
  8426. result = {
  8427. scene: new THREE.Scene(),
  8428. geometries: {},
  8429. face_materials: {},
  8430. materials: {},
  8431. textures: {},
  8432. objects: {},
  8433. cameras: {},
  8434. lights: {},
  8435. fogs: {},
  8436. empties: {},
  8437. groups: {}
  8438. };
  8439. if ( data.transform ) {
  8440. var position = data.transform.position,
  8441. rotation = data.transform.rotation,
  8442. scale = data.transform.scale;
  8443. if ( position ) {
  8444. result.scene.position.fromArray( position );
  8445. }
  8446. if ( rotation ) {
  8447. result.scene.rotation.fromArray( rotation );
  8448. }
  8449. if ( scale ) {
  8450. result.scene.scale.fromArray( scale );
  8451. }
  8452. if ( position || rotation || scale ) {
  8453. result.scene.updateMatrix();
  8454. result.scene.updateMatrixWorld();
  8455. }
  8456. }
  8457. function get_url( source_url, url_type ) {
  8458. if ( url_type == "relativeToHTML" ) {
  8459. return source_url;
  8460. } else {
  8461. return urlBase + source_url;
  8462. }
  8463. };
  8464. // toplevel loader function, delegates to handle_children
  8465. function handle_objects() {
  8466. handle_children( result.scene, data.objects );
  8467. }
  8468. // handle all the children from the loaded json and attach them to given parent
  8469. function handle_children( parent, children ) {
  8470. var mat, dst, pos, rot, scl, quat;
  8471. for ( var objID in children ) {
  8472. // check by id if child has already been handled,
  8473. // if not, create new object
  8474. var object = result.objects[ objID ];
  8475. var objJSON = children[ objID ];
  8476. if ( object === undefined ) {
  8477. // meshes
  8478. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  8479. if ( objJSON.loading === undefined ) {
  8480. var reservedTypes = {
  8481. "type": 1, "url": 1, "material": 1,
  8482. "position": 1, "rotation": 1, "scale" : 1,
  8483. "visible": 1, "children": 1, "userData": 1,
  8484. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  8485. };
  8486. var loaderParameters = {};
  8487. for ( var parType in objJSON ) {
  8488. if ( ! ( parType in reservedTypes ) ) {
  8489. loaderParameters[ parType ] = objJSON[ parType ];
  8490. }
  8491. }
  8492. material = result.materials[ objJSON.material ];
  8493. objJSON.loading = true;
  8494. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  8495. // ColladaLoader
  8496. if ( loader.options ) {
  8497. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  8498. // UTF8Loader
  8499. // OBJLoader
  8500. } else {
  8501. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  8502. }
  8503. }
  8504. } else if ( objJSON.geometry !== undefined ) {
  8505. geometry = result.geometries[ objJSON.geometry ];
  8506. // geometry already loaded
  8507. if ( geometry ) {
  8508. var needsTangents = false;
  8509. material = result.materials[ objJSON.material ];
  8510. needsTangents = material instanceof THREE.ShaderMaterial;
  8511. pos = objJSON.position;
  8512. rot = objJSON.rotation;
  8513. scl = objJSON.scale;
  8514. mat = objJSON.matrix;
  8515. quat = objJSON.quaternion;
  8516. // use materials from the model file
  8517. // if there is no material specified in the object
  8518. if ( ! objJSON.material ) {
  8519. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  8520. }
  8521. // use materials from the model file
  8522. // if there is just empty face material
  8523. // (must create new material as each model has its own face material)
  8524. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  8525. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  8526. }
  8527. if ( material instanceof THREE.MeshFaceMaterial ) {
  8528. for ( var i = 0; i < material.materials.length; i ++ ) {
  8529. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  8530. }
  8531. }
  8532. if ( needsTangents ) {
  8533. geometry.computeTangents();
  8534. }
  8535. if ( objJSON.skin ) {
  8536. object = new THREE.SkinnedMesh( geometry, material );
  8537. } else if ( objJSON.morph ) {
  8538. object = new THREE.MorphAnimMesh( geometry, material );
  8539. if ( objJSON.duration !== undefined ) {
  8540. object.duration = objJSON.duration;
  8541. }
  8542. if ( objJSON.time !== undefined ) {
  8543. object.time = objJSON.time;
  8544. }
  8545. if ( objJSON.mirroredLoop !== undefined ) {
  8546. object.mirroredLoop = objJSON.mirroredLoop;
  8547. }
  8548. if ( material.morphNormals ) {
  8549. geometry.computeMorphNormals();
  8550. }
  8551. } else {
  8552. object = new THREE.Mesh( geometry, material );
  8553. }
  8554. object.name = objID;
  8555. if ( mat ) {
  8556. object.matrixAutoUpdate = false;
  8557. object.matrix.set(
  8558. mat[0], mat[1], mat[2], mat[3],
  8559. mat[4], mat[5], mat[6], mat[7],
  8560. mat[8], mat[9], mat[10], mat[11],
  8561. mat[12], mat[13], mat[14], mat[15]
  8562. );
  8563. } else {
  8564. object.position.fromArray( pos );
  8565. if ( quat ) {
  8566. object.quaternion.fromArray( quat );
  8567. } else {
  8568. object.rotation.fromArray( rot );
  8569. }
  8570. object.scale.fromArray( scl );
  8571. }
  8572. object.visible = objJSON.visible;
  8573. object.castShadow = objJSON.castShadow;
  8574. object.receiveShadow = objJSON.receiveShadow;
  8575. parent.add( object );
  8576. result.objects[ objID ] = object;
  8577. }
  8578. // lights
  8579. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  8580. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  8581. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  8582. var color = objJSON.color;
  8583. var intensity = objJSON.intensity;
  8584. var distance = objJSON.distance;
  8585. var position = objJSON.position;
  8586. var rotation = objJSON.rotation;
  8587. switch ( objJSON.type ) {
  8588. case 'AmbientLight':
  8589. light = new THREE.AmbientLight( color );
  8590. break;
  8591. case 'PointLight':
  8592. light = new THREE.PointLight( color, intensity, distance );
  8593. light.position.fromArray( position );
  8594. break;
  8595. case 'DirectionalLight':
  8596. light = new THREE.DirectionalLight( color, intensity );
  8597. light.position.fromArray( objJSON.direction );
  8598. break;
  8599. case 'SpotLight':
  8600. light = new THREE.SpotLight( color, intensity, distance, 1 );
  8601. light.angle = objJSON.angle;
  8602. light.position.fromArray( position );
  8603. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8604. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8605. break;
  8606. case 'HemisphereLight':
  8607. light = new THREE.DirectionalLight( color, intensity, distance );
  8608. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8609. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8610. break;
  8611. case 'AreaLight':
  8612. light = new THREE.AreaLight(color, intensity);
  8613. light.position.fromArray( position );
  8614. light.width = objJSON.size;
  8615. light.height = objJSON.size_y;
  8616. break;
  8617. }
  8618. parent.add( light );
  8619. light.name = objID;
  8620. result.lights[ objID ] = light;
  8621. result.objects[ objID ] = light;
  8622. // cameras
  8623. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  8624. pos = objJSON.position;
  8625. rot = objJSON.rotation;
  8626. quat = objJSON.quaternion;
  8627. if ( objJSON.type === "PerspectiveCamera" ) {
  8628. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  8629. } else if ( objJSON.type === "OrthographicCamera" ) {
  8630. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  8631. }
  8632. camera.name = objID;
  8633. camera.position.fromArray( pos );
  8634. if ( quat !== undefined ) {
  8635. camera.quaternion.fromArray( quat );
  8636. } else if ( rot !== undefined ) {
  8637. camera.rotation.fromArray( rot );
  8638. }
  8639. parent.add( camera );
  8640. result.cameras[ objID ] = camera;
  8641. result.objects[ objID ] = camera;
  8642. // pure Object3D
  8643. } else {
  8644. pos = objJSON.position;
  8645. rot = objJSON.rotation;
  8646. scl = objJSON.scale;
  8647. quat = objJSON.quaternion;
  8648. object = new THREE.Object3D();
  8649. object.name = objID;
  8650. object.position.fromArray( pos );
  8651. if ( quat ) {
  8652. object.quaternion.fromArray( quat );
  8653. } else {
  8654. object.rotation.fromArray( rot );
  8655. }
  8656. object.scale.fromArray( scl );
  8657. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  8658. parent.add( object );
  8659. result.objects[ objID ] = object;
  8660. result.empties[ objID ] = object;
  8661. }
  8662. if ( object ) {
  8663. if ( objJSON.userData !== undefined ) {
  8664. for ( var key in objJSON.userData ) {
  8665. var value = objJSON.userData[ key ];
  8666. object.userData[ key ] = value;
  8667. }
  8668. }
  8669. if ( objJSON.groups !== undefined ) {
  8670. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  8671. var groupID = objJSON.groups[ i ];
  8672. if ( result.groups[ groupID ] === undefined ) {
  8673. result.groups[ groupID ] = [];
  8674. }
  8675. result.groups[ groupID ].push( objID );
  8676. }
  8677. }
  8678. }
  8679. }
  8680. if ( object !== undefined && objJSON.children !== undefined ) {
  8681. handle_children( object, objJSON.children );
  8682. }
  8683. }
  8684. };
  8685. function handle_mesh( geo, mat, id ) {
  8686. result.geometries[ id ] = geo;
  8687. result.face_materials[ id ] = mat;
  8688. handle_objects();
  8689. };
  8690. function handle_hierarchy( node, id, parent, material, obj ) {
  8691. var p = obj.position;
  8692. var r = obj.rotation;
  8693. var q = obj.quaternion;
  8694. var s = obj.scale;
  8695. node.position.fromArray( p );
  8696. if ( q ) {
  8697. node.quaternion.fromArray( q );
  8698. } else {
  8699. node.rotation.fromArray( r );
  8700. }
  8701. node.scale.fromArray( s );
  8702. // override children materials
  8703. // if object material was specified in JSON explicitly
  8704. if ( material ) {
  8705. node.traverse( function ( child ) {
  8706. child.material = material;
  8707. } );
  8708. }
  8709. // override children visibility
  8710. // with root node visibility as specified in JSON
  8711. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  8712. node.traverse( function ( child ) {
  8713. child.visible = visible;
  8714. } );
  8715. parent.add( node );
  8716. node.name = id;
  8717. result.objects[ id ] = node;
  8718. handle_objects();
  8719. };
  8720. function create_callback_geometry( id ) {
  8721. return function ( geo, mat ) {
  8722. geo.name = id;
  8723. handle_mesh( geo, mat, id );
  8724. counter_models -= 1;
  8725. scope.onLoadComplete();
  8726. async_callback_gate();
  8727. }
  8728. };
  8729. function create_callback_hierachy( id, parent, material, obj ) {
  8730. return function ( event ) {
  8731. var result;
  8732. // loaders which use EventDispatcher
  8733. if ( event.content ) {
  8734. result = event.content;
  8735. // ColladaLoader
  8736. } else if ( event.dae ) {
  8737. result = event.scene;
  8738. // UTF8Loader
  8739. } else {
  8740. result = event;
  8741. }
  8742. handle_hierarchy( result, id, parent, material, obj );
  8743. counter_models -= 1;
  8744. scope.onLoadComplete();
  8745. async_callback_gate();
  8746. }
  8747. };
  8748. function create_callback_embed( id ) {
  8749. return function ( geo, mat ) {
  8750. geo.name = id;
  8751. result.geometries[ id ] = geo;
  8752. result.face_materials[ id ] = mat;
  8753. }
  8754. };
  8755. function async_callback_gate() {
  8756. var progress = {
  8757. totalModels : total_models,
  8758. totalTextures : total_textures,
  8759. loadedModels : total_models - counter_models,
  8760. loadedTextures : total_textures - counter_textures
  8761. };
  8762. scope.callbackProgress( progress, result );
  8763. scope.onLoadProgress();
  8764. if ( counter_models === 0 && counter_textures === 0 ) {
  8765. finalize();
  8766. callbackFinished( result );
  8767. }
  8768. };
  8769. function finalize() {
  8770. // take care of targets which could be asynchronously loaded objects
  8771. for ( var i = 0; i < target_array.length; i ++ ) {
  8772. var ta = target_array[ i ];
  8773. var target = result.objects[ ta.targetName ];
  8774. if ( target ) {
  8775. ta.object.target = target;
  8776. } else {
  8777. // if there was error and target of specified name doesn't exist in the scene file
  8778. // create instead dummy target
  8779. // (target must be added to scene explicitly as parent is already added)
  8780. ta.object.target = new THREE.Object3D();
  8781. result.scene.add( ta.object.target );
  8782. }
  8783. ta.object.target.userData.targetInverse = ta.object;
  8784. }
  8785. };
  8786. var callbackTexture = function ( count ) {
  8787. counter_textures -= count;
  8788. async_callback_gate();
  8789. scope.onLoadComplete();
  8790. };
  8791. // must use this instead of just directly calling callbackTexture
  8792. // because of closure in the calling context loop
  8793. var generateTextureCallback = function ( count ) {
  8794. return function () {
  8795. callbackTexture( count );
  8796. };
  8797. };
  8798. function traverse_json_hierarchy( objJSON, callback ) {
  8799. callback( objJSON );
  8800. if ( objJSON.children !== undefined ) {
  8801. for ( var objChildID in objJSON.children ) {
  8802. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  8803. }
  8804. }
  8805. };
  8806. // first go synchronous elements
  8807. // fogs
  8808. var fogID, fogJSON;
  8809. for ( fogID in data.fogs ) {
  8810. fogJSON = data.fogs[ fogID ];
  8811. if ( fogJSON.type === "linear" ) {
  8812. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  8813. } else if ( fogJSON.type === "exp2" ) {
  8814. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  8815. }
  8816. color = fogJSON.color;
  8817. fog.color.setRGB( color[0], color[1], color[2] );
  8818. result.fogs[ fogID ] = fog;
  8819. }
  8820. // now come potentially asynchronous elements
  8821. // geometries
  8822. // count how many geometries will be loaded asynchronously
  8823. var geoID, geoJSON;
  8824. for ( geoID in data.geometries ) {
  8825. geoJSON = data.geometries[ geoID ];
  8826. if ( geoJSON.type in this.geometryHandlers ) {
  8827. counter_models += 1;
  8828. scope.onLoadStart();
  8829. }
  8830. }
  8831. // count how many hierarchies will be loaded asynchronously
  8832. for ( var objID in data.objects ) {
  8833. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  8834. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  8835. counter_models += 1;
  8836. scope.onLoadStart();
  8837. }
  8838. });
  8839. }
  8840. total_models = counter_models;
  8841. for ( geoID in data.geometries ) {
  8842. geoJSON = data.geometries[ geoID ];
  8843. if ( geoJSON.type === "cube" ) {
  8844. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  8845. geometry.name = geoID;
  8846. result.geometries[ geoID ] = geometry;
  8847. } else if ( geoJSON.type === "plane" ) {
  8848. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  8849. geometry.name = geoID;
  8850. result.geometries[ geoID ] = geometry;
  8851. } else if ( geoJSON.type === "sphere" ) {
  8852. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  8853. geometry.name = geoID;
  8854. result.geometries[ geoID ] = geometry;
  8855. } else if ( geoJSON.type === "cylinder" ) {
  8856. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  8857. geometry.name = geoID;
  8858. result.geometries[ geoID ] = geometry;
  8859. } else if ( geoJSON.type === "torus" ) {
  8860. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  8861. geometry.name = geoID;
  8862. result.geometries[ geoID ] = geometry;
  8863. } else if ( geoJSON.type === "icosahedron" ) {
  8864. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  8865. geometry.name = geoID;
  8866. result.geometries[ geoID ] = geometry;
  8867. } else if ( geoJSON.type in this.geometryHandlers ) {
  8868. var loaderParameters = {};
  8869. for ( var parType in geoJSON ) {
  8870. if ( parType !== "type" && parType !== "url" ) {
  8871. loaderParameters[ parType ] = geoJSON[ parType ];
  8872. }
  8873. }
  8874. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  8875. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  8876. } else if ( geoJSON.type === "embedded" ) {
  8877. var modelJson = data.embeds[ geoJSON.id ],
  8878. texture_path = "";
  8879. // pass metadata along to jsonLoader so it knows the format version
  8880. modelJson.metadata = data.metadata;
  8881. if ( modelJson ) {
  8882. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  8883. var model = jsonLoader.parse( modelJson, texture_path );
  8884. create_callback_embed( geoID )( model.geometry, model.materials );
  8885. }
  8886. }
  8887. }
  8888. // textures
  8889. // count how many textures will be loaded asynchronously
  8890. var textureID, textureJSON;
  8891. for ( textureID in data.textures ) {
  8892. textureJSON = data.textures[ textureID ];
  8893. if ( textureJSON.url instanceof Array ) {
  8894. counter_textures += textureJSON.url.length;
  8895. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8896. scope.onLoadStart();
  8897. }
  8898. } else {
  8899. counter_textures += 1;
  8900. scope.onLoadStart();
  8901. }
  8902. }
  8903. total_textures = counter_textures;
  8904. for ( textureID in data.textures ) {
  8905. textureJSON = data.textures[ textureID ];
  8906. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8907. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8908. }
  8909. if ( textureJSON.url instanceof Array ) {
  8910. var count = textureJSON.url.length;
  8911. var url_array = [];
  8912. for( var i = 0; i < count; i ++ ) {
  8913. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8914. }
  8915. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8916. if ( isCompressed ) {
  8917. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8918. } else {
  8919. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8920. }
  8921. } else {
  8922. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8923. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8924. var textureCallback = generateTextureCallback( 1 );
  8925. if ( isCompressed ) {
  8926. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8927. } else {
  8928. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8929. }
  8930. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8931. texture.minFilter = THREE[ textureJSON.minFilter ];
  8932. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8933. texture.magFilter = THREE[ textureJSON.magFilter ];
  8934. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8935. if ( textureJSON.repeat ) {
  8936. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8937. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8938. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8939. }
  8940. if ( textureJSON.offset ) {
  8941. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8942. }
  8943. // handle wrap after repeat so that default repeat can be overriden
  8944. if ( textureJSON.wrap ) {
  8945. var wrapMap = {
  8946. "repeat": THREE.RepeatWrapping,
  8947. "mirror": THREE.MirroredRepeatWrapping
  8948. }
  8949. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8950. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8951. }
  8952. }
  8953. result.textures[ textureID ] = texture;
  8954. }
  8955. // materials
  8956. var matID, matJSON;
  8957. var parID;
  8958. for ( matID in data.materials ) {
  8959. matJSON = data.materials[ matID ];
  8960. for ( parID in matJSON.parameters ) {
  8961. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8962. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8963. } else if ( parID === "shading" ) {
  8964. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8965. } else if ( parID === "side" ) {
  8966. if ( matJSON.parameters[ parID ] == "double" ) {
  8967. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8968. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8969. matJSON.parameters[ parID ] = THREE.BackSide;
  8970. } else {
  8971. matJSON.parameters[ parID ] = THREE.FrontSide;
  8972. }
  8973. } else if ( parID === "blending" ) {
  8974. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8975. } else if ( parID === "combine" ) {
  8976. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8977. } else if ( parID === "vertexColors" ) {
  8978. if ( matJSON.parameters[ parID ] == "face" ) {
  8979. matJSON.parameters[ parID ] = THREE.FaceColors;
  8980. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8981. } else if ( matJSON.parameters[ parID ] ) {
  8982. matJSON.parameters[ parID ] = THREE.VertexColors;
  8983. }
  8984. } else if ( parID === "wrapRGB" ) {
  8985. var v3 = matJSON.parameters[ parID ];
  8986. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8987. }
  8988. }
  8989. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8990. matJSON.parameters.transparent = true;
  8991. }
  8992. if ( matJSON.parameters.normalMap ) {
  8993. var shader = THREE.ShaderLib[ "normalmap" ];
  8994. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8995. var diffuse = matJSON.parameters.color;
  8996. var specular = matJSON.parameters.specular;
  8997. var ambient = matJSON.parameters.ambient;
  8998. var shininess = matJSON.parameters.shininess;
  8999. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  9000. if ( matJSON.parameters.normalScale ) {
  9001. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  9002. }
  9003. if ( matJSON.parameters.map ) {
  9004. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  9005. uniforms[ "enableDiffuse" ].value = true;
  9006. }
  9007. if ( matJSON.parameters.envMap ) {
  9008. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  9009. uniforms[ "enableReflection" ].value = true;
  9010. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  9011. }
  9012. if ( matJSON.parameters.lightMap ) {
  9013. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  9014. uniforms[ "enableAO" ].value = true;
  9015. }
  9016. if ( matJSON.parameters.specularMap ) {
  9017. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  9018. uniforms[ "enableSpecular" ].value = true;
  9019. }
  9020. if ( matJSON.parameters.displacementMap ) {
  9021. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  9022. uniforms[ "enableDisplacement" ].value = true;
  9023. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  9024. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  9025. }
  9026. uniforms[ "diffuse" ].value.setHex( diffuse );
  9027. uniforms[ "specular" ].value.setHex( specular );
  9028. uniforms[ "ambient" ].value.setHex( ambient );
  9029. uniforms[ "shininess" ].value = shininess;
  9030. if ( matJSON.parameters.opacity ) {
  9031. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  9032. }
  9033. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  9034. material = new THREE.ShaderMaterial( parameters );
  9035. } else {
  9036. material = new THREE[ matJSON.type ]( matJSON.parameters );
  9037. }
  9038. material.name = matID;
  9039. result.materials[ matID ] = material;
  9040. }
  9041. // second pass through all materials to initialize MeshFaceMaterials
  9042. // that could be referring to other materials out of order
  9043. for ( matID in data.materials ) {
  9044. matJSON = data.materials[ matID ];
  9045. if ( matJSON.parameters.materials ) {
  9046. var materialArray = [];
  9047. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  9048. var label = matJSON.parameters.materials[ i ];
  9049. materialArray.push( result.materials[ label ] );
  9050. }
  9051. result.materials[ matID ].materials = materialArray;
  9052. }
  9053. }
  9054. // objects ( synchronous init of procedural primitives )
  9055. handle_objects();
  9056. // defaults
  9057. if ( result.cameras && data.defaults.camera ) {
  9058. result.currentCamera = result.cameras[ data.defaults.camera ];
  9059. }
  9060. if ( result.fogs && data.defaults.fog ) {
  9061. result.scene.fog = result.fogs[ data.defaults.fog ];
  9062. }
  9063. // synchronous callback
  9064. scope.callbackSync( result );
  9065. // just in case there are no async elements
  9066. async_callback_gate();
  9067. }
  9068. }
  9069. /**
  9070. * @author mrdoob / http://mrdoob.com/
  9071. */
  9072. THREE.TextureLoader = function ( manager ) {
  9073. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9074. };
  9075. THREE.TextureLoader.prototype = {
  9076. constructor: THREE.TextureLoader,
  9077. load: function ( url, onLoad, onProgress, onError ) {
  9078. var scope = this;
  9079. var loader = new THREE.ImageLoader( scope.manager );
  9080. loader.setCrossOrigin( this.crossOrigin );
  9081. loader.load( url, function ( image ) {
  9082. var texture = new THREE.Texture( image );
  9083. texture.needsUpdate = true;
  9084. if ( onLoad !== undefined ) {
  9085. onLoad( texture );
  9086. }
  9087. } );
  9088. },
  9089. setCrossOrigin: function ( value ) {
  9090. this.crossOrigin = value;
  9091. }
  9092. };
  9093. /**
  9094. * @author mrdoob / http://mrdoob.com/
  9095. * @author alteredq / http://alteredqualia.com/
  9096. */
  9097. THREE.Material = function () {
  9098. this.id = THREE.MaterialIdCount ++;
  9099. this.uuid = THREE.Math.generateUUID();
  9100. this.name = '';
  9101. this.side = THREE.FrontSide;
  9102. this.opacity = 1;
  9103. this.transparent = false;
  9104. this.blending = THREE.NormalBlending;
  9105. this.blendSrc = THREE.SrcAlphaFactor;
  9106. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  9107. this.blendEquation = THREE.AddEquation;
  9108. this.depthTest = true;
  9109. this.depthWrite = true;
  9110. this.polygonOffset = false;
  9111. this.polygonOffsetFactor = 0;
  9112. this.polygonOffsetUnits = 0;
  9113. this.alphaTest = 0;
  9114. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  9115. this.visible = true;
  9116. this.needsUpdate = true;
  9117. };
  9118. THREE.Material.prototype = {
  9119. constructor: THREE.Material,
  9120. setValues: function ( values ) {
  9121. if ( values === undefined ) return;
  9122. for ( var key in values ) {
  9123. var newValue = values[ key ];
  9124. if ( newValue === undefined ) {
  9125. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  9126. continue;
  9127. }
  9128. if ( key in this ) {
  9129. var currentValue = this[ key ];
  9130. if ( currentValue instanceof THREE.Color ) {
  9131. currentValue.set( newValue );
  9132. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  9133. currentValue.copy( newValue );
  9134. } else if ( key == 'overdraw') {
  9135. // ensure overdraw is backwards-compatable with legacy boolean type
  9136. this[ key ] = Number(newValue);
  9137. } else {
  9138. this[ key ] = newValue;
  9139. }
  9140. }
  9141. }
  9142. },
  9143. clone: function ( material ) {
  9144. if ( material === undefined ) material = new THREE.Material();
  9145. material.name = this.name;
  9146. material.side = this.side;
  9147. material.opacity = this.opacity;
  9148. material.transparent = this.transparent;
  9149. material.blending = this.blending;
  9150. material.blendSrc = this.blendSrc;
  9151. material.blendDst = this.blendDst;
  9152. material.blendEquation = this.blendEquation;
  9153. material.depthTest = this.depthTest;
  9154. material.depthWrite = this.depthWrite;
  9155. material.polygonOffset = this.polygonOffset;
  9156. material.polygonOffsetFactor = this.polygonOffsetFactor;
  9157. material.polygonOffsetUnits = this.polygonOffsetUnits;
  9158. material.alphaTest = this.alphaTest;
  9159. material.overdraw = this.overdraw;
  9160. material.visible = this.visible;
  9161. return material;
  9162. },
  9163. dispose: function () {
  9164. this.dispatchEvent( { type: 'dispose' } );
  9165. }
  9166. };
  9167. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  9168. THREE.MaterialIdCount = 0;
  9169. /**
  9170. * @author mrdoob / http://mrdoob.com/
  9171. * @author alteredq / http://alteredqualia.com/
  9172. *
  9173. * parameters = {
  9174. * color: <hex>,
  9175. * opacity: <float>,
  9176. *
  9177. * blending: THREE.NormalBlending,
  9178. * depthTest: <bool>,
  9179. * depthWrite: <bool>,
  9180. *
  9181. * linewidth: <float>,
  9182. * linecap: "round",
  9183. * linejoin: "round",
  9184. *
  9185. * vertexColors: <bool>
  9186. *
  9187. * fog: <bool>
  9188. * }
  9189. */
  9190. THREE.LineBasicMaterial = function ( parameters ) {
  9191. THREE.Material.call( this );
  9192. this.color = new THREE.Color( 0xffffff );
  9193. this.linewidth = 1;
  9194. this.linecap = 'round';
  9195. this.linejoin = 'round';
  9196. this.vertexColors = false;
  9197. this.fog = true;
  9198. this.setValues( parameters );
  9199. };
  9200. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  9201. THREE.LineBasicMaterial.prototype.clone = function () {
  9202. var material = new THREE.LineBasicMaterial();
  9203. THREE.Material.prototype.clone.call( this, material );
  9204. material.color.copy( this.color );
  9205. material.linewidth = this.linewidth;
  9206. material.linecap = this.linecap;
  9207. material.linejoin = this.linejoin;
  9208. material.vertexColors = this.vertexColors;
  9209. material.fog = this.fog;
  9210. return material;
  9211. };
  9212. /**
  9213. * @author alteredq / http://alteredqualia.com/
  9214. *
  9215. * parameters = {
  9216. * color: <hex>,
  9217. * opacity: <float>,
  9218. *
  9219. * blending: THREE.NormalBlending,
  9220. * depthTest: <bool>,
  9221. * depthWrite: <bool>,
  9222. *
  9223. * linewidth: <float>,
  9224. *
  9225. * scale: <float>,
  9226. * dashSize: <float>,
  9227. * gapSize: <float>,
  9228. *
  9229. * vertexColors: <bool>
  9230. *
  9231. * fog: <bool>
  9232. * }
  9233. */
  9234. THREE.LineDashedMaterial = function ( parameters ) {
  9235. THREE.Material.call( this );
  9236. this.color = new THREE.Color( 0xffffff );
  9237. this.linewidth = 1;
  9238. this.scale = 1;
  9239. this.dashSize = 3;
  9240. this.gapSize = 1;
  9241. this.vertexColors = false;
  9242. this.fog = true;
  9243. this.setValues( parameters );
  9244. };
  9245. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  9246. THREE.LineDashedMaterial.prototype.clone = function () {
  9247. var material = new THREE.LineDashedMaterial();
  9248. THREE.Material.prototype.clone.call( this, material );
  9249. material.color.copy( this.color );
  9250. material.linewidth = this.linewidth;
  9251. material.scale = this.scale;
  9252. material.dashSize = this.dashSize;
  9253. material.gapSize = this.gapSize;
  9254. material.vertexColors = this.vertexColors;
  9255. material.fog = this.fog;
  9256. return material;
  9257. };
  9258. /**
  9259. * @author mrdoob / http://mrdoob.com/
  9260. * @author alteredq / http://alteredqualia.com/
  9261. *
  9262. * parameters = {
  9263. * color: <hex>,
  9264. * opacity: <float>,
  9265. * map: new THREE.Texture( <Image> ),
  9266. *
  9267. * lightMap: new THREE.Texture( <Image> ),
  9268. *
  9269. * specularMap: new THREE.Texture( <Image> ),
  9270. *
  9271. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  9272. * combine: THREE.Multiply,
  9273. * reflectivity: <float>,
  9274. * refractionRatio: <float>,
  9275. *
  9276. * shading: THREE.SmoothShading,
  9277. * blending: THREE.NormalBlending,
  9278. * depthTest: <bool>,
  9279. * depthWrite: <bool>,
  9280. *
  9281. * wireframe: <boolean>,
  9282. * wireframeLinewidth: <float>,
  9283. *
  9284. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9285. *
  9286. * skinning: <bool>,
  9287. * morphTargets: <bool>,
  9288. *
  9289. * fog: <bool>
  9290. * }
  9291. */
  9292. THREE.MeshBasicMaterial = function ( parameters ) {
  9293. THREE.Material.call( this );
  9294. this.color = new THREE.Color( 0xffffff ); // emissive
  9295. this.map = null;
  9296. this.lightMap = null;
  9297. this.specularMap = null;
  9298. this.envMap = null;
  9299. this.combine = THREE.MultiplyOperation;
  9300. this.reflectivity = 1;
  9301. this.refractionRatio = 0.98;
  9302. this.fog = true;
  9303. this.shading = THREE.SmoothShading;
  9304. this.wireframe = false;
  9305. this.wireframeLinewidth = 1;
  9306. this.wireframeLinecap = 'round';
  9307. this.wireframeLinejoin = 'round';
  9308. this.vertexColors = THREE.NoColors;
  9309. this.skinning = false;
  9310. this.morphTargets = false;
  9311. this.setValues( parameters );
  9312. };
  9313. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  9314. THREE.MeshBasicMaterial.prototype.clone = function () {
  9315. var material = new THREE.MeshBasicMaterial();
  9316. THREE.Material.prototype.clone.call( this, material );
  9317. material.color.copy( this.color );
  9318. material.map = this.map;
  9319. material.lightMap = this.lightMap;
  9320. material.specularMap = this.specularMap;
  9321. material.envMap = this.envMap;
  9322. material.combine = this.combine;
  9323. material.reflectivity = this.reflectivity;
  9324. material.refractionRatio = this.refractionRatio;
  9325. material.fog = this.fog;
  9326. material.shading = this.shading;
  9327. material.wireframe = this.wireframe;
  9328. material.wireframeLinewidth = this.wireframeLinewidth;
  9329. material.wireframeLinecap = this.wireframeLinecap;
  9330. material.wireframeLinejoin = this.wireframeLinejoin;
  9331. material.vertexColors = this.vertexColors;
  9332. material.skinning = this.skinning;
  9333. material.morphTargets = this.morphTargets;
  9334. return material;
  9335. };
  9336. /**
  9337. * @author mrdoob / http://mrdoob.com/
  9338. * @author alteredq / http://alteredqualia.com/
  9339. *
  9340. * parameters = {
  9341. * color: <hex>,
  9342. * ambient: <hex>,
  9343. * emissive: <hex>,
  9344. * opacity: <float>,
  9345. *
  9346. * map: new THREE.Texture( <Image> ),
  9347. *
  9348. * lightMap: new THREE.Texture( <Image> ),
  9349. *
  9350. * specularMap: new THREE.Texture( <Image> ),
  9351. *
  9352. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  9353. * combine: THREE.Multiply,
  9354. * reflectivity: <float>,
  9355. * refractionRatio: <float>,
  9356. *
  9357. * shading: THREE.SmoothShading,
  9358. * blending: THREE.NormalBlending,
  9359. * depthTest: <bool>,
  9360. * depthWrite: <bool>,
  9361. *
  9362. * wireframe: <boolean>,
  9363. * wireframeLinewidth: <float>,
  9364. *
  9365. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9366. *
  9367. * skinning: <bool>,
  9368. * morphTargets: <bool>,
  9369. * morphNormals: <bool>,
  9370. *
  9371. * fog: <bool>
  9372. * }
  9373. */
  9374. THREE.MeshLambertMaterial = function ( parameters ) {
  9375. THREE.Material.call( this );
  9376. this.color = new THREE.Color( 0xffffff ); // diffuse
  9377. this.ambient = new THREE.Color( 0xffffff );
  9378. this.emissive = new THREE.Color( 0x000000 );
  9379. this.wrapAround = false;
  9380. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  9381. this.map = null;
  9382. this.lightMap = null;
  9383. this.specularMap = null;
  9384. this.envMap = null;
  9385. this.combine = THREE.MultiplyOperation;
  9386. this.reflectivity = 1;
  9387. this.refractionRatio = 0.98;
  9388. this.fog = true;
  9389. this.shading = THREE.SmoothShading;
  9390. this.wireframe = false;
  9391. this.wireframeLinewidth = 1;
  9392. this.wireframeLinecap = 'round';
  9393. this.wireframeLinejoin = 'round';
  9394. this.vertexColors = THREE.NoColors;
  9395. this.skinning = false;
  9396. this.morphTargets = false;
  9397. this.morphNormals = false;
  9398. this.setValues( parameters );
  9399. };
  9400. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  9401. THREE.MeshLambertMaterial.prototype.clone = function () {
  9402. var material = new THREE.MeshLambertMaterial();
  9403. THREE.Material.prototype.clone.call( this, material );
  9404. material.color.copy( this.color );
  9405. material.ambient.copy( this.ambient );
  9406. material.emissive.copy( this.emissive );
  9407. material.wrapAround = this.wrapAround;
  9408. material.wrapRGB.copy( this.wrapRGB );
  9409. material.map = this.map;
  9410. material.lightMap = this.lightMap;
  9411. material.specularMap = this.specularMap;
  9412. material.envMap = this.envMap;
  9413. material.combine = this.combine;
  9414. material.reflectivity = this.reflectivity;
  9415. material.refractionRatio = this.refractionRatio;
  9416. material.fog = this.fog;
  9417. material.shading = this.shading;
  9418. material.wireframe = this.wireframe;
  9419. material.wireframeLinewidth = this.wireframeLinewidth;
  9420. material.wireframeLinecap = this.wireframeLinecap;
  9421. material.wireframeLinejoin = this.wireframeLinejoin;
  9422. material.vertexColors = this.vertexColors;
  9423. material.skinning = this.skinning;
  9424. material.morphTargets = this.morphTargets;
  9425. material.morphNormals = this.morphNormals;
  9426. return material;
  9427. };
  9428. /**
  9429. * @author mrdoob / http://mrdoob.com/
  9430. * @author alteredq / http://alteredqualia.com/
  9431. *
  9432. * parameters = {
  9433. * color: <hex>,
  9434. * ambient: <hex>,
  9435. * emissive: <hex>,
  9436. * specular: <hex>,
  9437. * shininess: <float>,
  9438. * opacity: <float>,
  9439. *
  9440. * map: new THREE.Texture( <Image> ),
  9441. *
  9442. * lightMap: new THREE.Texture( <Image> ),
  9443. *
  9444. * bumpMap: new THREE.Texture( <Image> ),
  9445. * bumpScale: <float>,
  9446. *
  9447. * normalMap: new THREE.Texture( <Image> ),
  9448. * normalScale: <Vector2>,
  9449. *
  9450. * specularMap: new THREE.Texture( <Image> ),
  9451. *
  9452. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  9453. * combine: THREE.Multiply,
  9454. * reflectivity: <float>,
  9455. * refractionRatio: <float>,
  9456. *
  9457. * shading: THREE.SmoothShading,
  9458. * blending: THREE.NormalBlending,
  9459. * depthTest: <bool>,
  9460. * depthWrite: <bool>,
  9461. *
  9462. * wireframe: <boolean>,
  9463. * wireframeLinewidth: <float>,
  9464. *
  9465. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9466. *
  9467. * skinning: <bool>,
  9468. * morphTargets: <bool>,
  9469. * morphNormals: <bool>,
  9470. *
  9471. * fog: <bool>
  9472. * }
  9473. */
  9474. THREE.MeshPhongMaterial = function ( parameters ) {
  9475. THREE.Material.call( this );
  9476. this.color = new THREE.Color( 0xffffff ); // diffuse
  9477. this.ambient = new THREE.Color( 0xffffff );
  9478. this.emissive = new THREE.Color( 0x000000 );
  9479. this.specular = new THREE.Color( 0x111111 );
  9480. this.shininess = 30;
  9481. this.metal = false;
  9482. this.wrapAround = false;
  9483. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  9484. this.map = null;
  9485. this.lightMap = null;
  9486. this.bumpMap = null;
  9487. this.bumpScale = 1;
  9488. this.normalMap = null;
  9489. this.normalScale = new THREE.Vector2( 1, 1 );
  9490. this.specularMap = null;
  9491. this.envMap = null;
  9492. this.combine = THREE.MultiplyOperation;
  9493. this.reflectivity = 1;
  9494. this.refractionRatio = 0.98;
  9495. this.fog = true;
  9496. this.shading = THREE.SmoothShading;
  9497. this.wireframe = false;
  9498. this.wireframeLinewidth = 1;
  9499. this.wireframeLinecap = 'round';
  9500. this.wireframeLinejoin = 'round';
  9501. this.vertexColors = THREE.NoColors;
  9502. this.skinning = false;
  9503. this.morphTargets = false;
  9504. this.morphNormals = false;
  9505. this.setValues( parameters );
  9506. };
  9507. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  9508. THREE.MeshPhongMaterial.prototype.clone = function () {
  9509. var material = new THREE.MeshPhongMaterial();
  9510. THREE.Material.prototype.clone.call( this, material );
  9511. material.color.copy( this.color );
  9512. material.ambient.copy( this.ambient );
  9513. material.emissive.copy( this.emissive );
  9514. material.specular.copy( this.specular );
  9515. material.shininess = this.shininess;
  9516. material.metal = this.metal;
  9517. material.wrapAround = this.wrapAround;
  9518. material.wrapRGB.copy( this.wrapRGB );
  9519. material.map = this.map;
  9520. material.lightMap = this.lightMap;
  9521. material.bumpMap = this.bumpMap;
  9522. material.bumpScale = this.bumpScale;
  9523. material.normalMap = this.normalMap;
  9524. material.normalScale.copy( this.normalScale );
  9525. material.specularMap = this.specularMap;
  9526. material.envMap = this.envMap;
  9527. material.combine = this.combine;
  9528. material.reflectivity = this.reflectivity;
  9529. material.refractionRatio = this.refractionRatio;
  9530. material.fog = this.fog;
  9531. material.shading = this.shading;
  9532. material.wireframe = this.wireframe;
  9533. material.wireframeLinewidth = this.wireframeLinewidth;
  9534. material.wireframeLinecap = this.wireframeLinecap;
  9535. material.wireframeLinejoin = this.wireframeLinejoin;
  9536. material.vertexColors = this.vertexColors;
  9537. material.skinning = this.skinning;
  9538. material.morphTargets = this.morphTargets;
  9539. material.morphNormals = this.morphNormals;
  9540. return material;
  9541. };
  9542. /**
  9543. * @author mrdoob / http://mrdoob.com/
  9544. * @author alteredq / http://alteredqualia.com/
  9545. *
  9546. * parameters = {
  9547. * opacity: <float>,
  9548. *
  9549. * blending: THREE.NormalBlending,
  9550. * depthTest: <bool>,
  9551. * depthWrite: <bool>,
  9552. *
  9553. * wireframe: <boolean>,
  9554. * wireframeLinewidth: <float>
  9555. * }
  9556. */
  9557. THREE.MeshDepthMaterial = function ( parameters ) {
  9558. THREE.Material.call( this );
  9559. this.wireframe = false;
  9560. this.wireframeLinewidth = 1;
  9561. this.setValues( parameters );
  9562. };
  9563. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  9564. THREE.MeshDepthMaterial.prototype.clone = function () {
  9565. var material = new THREE.MeshDepthMaterial();
  9566. THREE.Material.prototype.clone.call( this, material );
  9567. material.wireframe = this.wireframe;
  9568. material.wireframeLinewidth = this.wireframeLinewidth;
  9569. return material;
  9570. };
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. *
  9574. * parameters = {
  9575. * opacity: <float>,
  9576. *
  9577. * shading: THREE.FlatShading,
  9578. * blending: THREE.NormalBlending,
  9579. * depthTest: <bool>,
  9580. * depthWrite: <bool>,
  9581. *
  9582. * wireframe: <boolean>,
  9583. * wireframeLinewidth: <float>
  9584. * }
  9585. */
  9586. THREE.MeshNormalMaterial = function ( parameters ) {
  9587. THREE.Material.call( this, parameters );
  9588. this.shading = THREE.FlatShading;
  9589. this.wireframe = false;
  9590. this.wireframeLinewidth = 1;
  9591. this.morphTargets = false;
  9592. this.setValues( parameters );
  9593. };
  9594. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  9595. THREE.MeshNormalMaterial.prototype.clone = function () {
  9596. var material = new THREE.MeshNormalMaterial();
  9597. THREE.Material.prototype.clone.call( this, material );
  9598. material.shading = this.shading;
  9599. material.wireframe = this.wireframe;
  9600. material.wireframeLinewidth = this.wireframeLinewidth;
  9601. return material;
  9602. };
  9603. /**
  9604. * @author mrdoob / http://mrdoob.com/
  9605. */
  9606. THREE.MeshFaceMaterial = function ( materials ) {
  9607. this.materials = materials instanceof Array ? materials : [];
  9608. };
  9609. THREE.MeshFaceMaterial.prototype.clone = function () {
  9610. var material = new THREE.MeshFaceMaterial();
  9611. for ( var i = 0; i < this.materials.length; i ++ ) {
  9612. material.materials.push( this.materials[ i ].clone() );
  9613. }
  9614. return material;
  9615. };
  9616. /**
  9617. * @author mrdoob / http://mrdoob.com/
  9618. * @author alteredq / http://alteredqualia.com/
  9619. *
  9620. * parameters = {
  9621. * color: <hex>,
  9622. * opacity: <float>,
  9623. * map: new THREE.Texture( <Image> ),
  9624. *
  9625. * size: <float>,
  9626. *
  9627. * blending: THREE.NormalBlending,
  9628. * depthTest: <bool>,
  9629. * depthWrite: <bool>,
  9630. *
  9631. * vertexColors: <bool>,
  9632. *
  9633. * fog: <bool>
  9634. * }
  9635. */
  9636. THREE.ParticleSystemMaterial = function ( parameters ) {
  9637. THREE.Material.call( this );
  9638. this.color = new THREE.Color( 0xffffff );
  9639. this.map = null;
  9640. this.size = 1;
  9641. this.sizeAttenuation = true;
  9642. this.vertexColors = false;
  9643. this.fog = true;
  9644. this.setValues( parameters );
  9645. };
  9646. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  9647. THREE.ParticleSystemMaterial.prototype.clone = function () {
  9648. var material = new THREE.ParticleSystemMaterial();
  9649. THREE.Material.prototype.clone.call( this, material );
  9650. material.color.copy( this.color );
  9651. material.map = this.map;
  9652. material.size = this.size;
  9653. material.sizeAttenuation = this.sizeAttenuation;
  9654. material.vertexColors = this.vertexColors;
  9655. material.fog = this.fog;
  9656. return material;
  9657. };
  9658. // backwards compatibility
  9659. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  9660. /**
  9661. * @author alteredq / http://alteredqualia.com/
  9662. *
  9663. * parameters = {
  9664. * fragmentShader: <string>,
  9665. * vertexShader: <string>,
  9666. *
  9667. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  9668. *
  9669. * defines: { "label" : "value" },
  9670. *
  9671. * shading: THREE.SmoothShading,
  9672. * blending: THREE.NormalBlending,
  9673. * depthTest: <bool>,
  9674. * depthWrite: <bool>,
  9675. *
  9676. * wireframe: <boolean>,
  9677. * wireframeLinewidth: <float>,
  9678. *
  9679. * lights: <bool>,
  9680. *
  9681. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9682. *
  9683. * skinning: <bool>,
  9684. * morphTargets: <bool>,
  9685. * morphNormals: <bool>,
  9686. *
  9687. * fog: <bool>
  9688. * }
  9689. */
  9690. THREE.ShaderMaterial = function ( parameters ) {
  9691. THREE.Material.call( this );
  9692. this.fragmentShader = "void main() {}";
  9693. this.vertexShader = "void main() {}";
  9694. this.uniforms = {};
  9695. this.defines = {};
  9696. this.attributes = null;
  9697. this.shading = THREE.SmoothShading;
  9698. this.linewidth = 1;
  9699. this.wireframe = false;
  9700. this.wireframeLinewidth = 1;
  9701. this.fog = false; // set to use scene fog
  9702. this.lights = false; // set to use scene lights
  9703. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  9704. this.skinning = false; // set to use skinning attribute streams
  9705. this.morphTargets = false; // set to use morph targets
  9706. this.morphNormals = false; // set to use morph normals
  9707. // When rendered geometry doesn't include these attributes but the material does,
  9708. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9709. this.defaultAttributeValues = {
  9710. "color" : [ 1, 1, 1 ],
  9711. "uv" : [ 0, 0 ],
  9712. "uv2" : [ 0, 0 ]
  9713. };
  9714. this.index0AttributeName = undefined;
  9715. this.setValues( parameters );
  9716. };
  9717. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  9718. THREE.ShaderMaterial.prototype.clone = function () {
  9719. var material = new THREE.ShaderMaterial();
  9720. THREE.Material.prototype.clone.call( this, material );
  9721. material.fragmentShader = this.fragmentShader;
  9722. material.vertexShader = this.vertexShader;
  9723. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  9724. material.attributes = this.attributes;
  9725. material.defines = this.defines;
  9726. material.shading = this.shading;
  9727. material.wireframe = this.wireframe;
  9728. material.wireframeLinewidth = this.wireframeLinewidth;
  9729. material.fog = this.fog;
  9730. material.lights = this.lights;
  9731. material.vertexColors = this.vertexColors;
  9732. material.skinning = this.skinning;
  9733. material.morphTargets = this.morphTargets;
  9734. material.morphNormals = this.morphNormals;
  9735. return material;
  9736. };
  9737. /**
  9738. * @author mrdoob / http://mrdoob.com/
  9739. */
  9740. THREE.RawShaderMaterial = function ( parameters ) {
  9741. THREE.ShaderMaterial.call( this, parameters );
  9742. };
  9743. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9744. THREE.RawShaderMaterial.prototype.clone = function () {
  9745. var material = new THREE.RawShaderMaterial();
  9746. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9747. return material;
  9748. };
  9749. /**
  9750. * @author alteredq / http://alteredqualia.com/
  9751. *
  9752. * parameters = {
  9753. * color: <hex>,
  9754. * opacity: <float>,
  9755. * map: new THREE.Texture( <Image> ),
  9756. *
  9757. * blending: THREE.NormalBlending,
  9758. * depthTest: <bool>,
  9759. * depthWrite: <bool>,
  9760. *
  9761. * uvOffset: new THREE.Vector2(),
  9762. * uvScale: new THREE.Vector2(),
  9763. *
  9764. * fog: <bool>
  9765. * }
  9766. */
  9767. THREE.SpriteMaterial = function ( parameters ) {
  9768. THREE.Material.call( this );
  9769. // defaults
  9770. this.color = new THREE.Color( 0xffffff );
  9771. this.map = null;
  9772. this.rotation = 0;
  9773. this.fog = false;
  9774. // set parameters
  9775. this.setValues( parameters );
  9776. };
  9777. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9778. THREE.SpriteMaterial.prototype.clone = function () {
  9779. var material = new THREE.SpriteMaterial();
  9780. THREE.Material.prototype.clone.call( this, material );
  9781. material.color.copy( this.color );
  9782. material.map = this.map;
  9783. material.rotation = this.rotation;
  9784. material.fog = this.fog;
  9785. return material;
  9786. };
  9787. /**
  9788. * @author mrdoob / http://mrdoob.com/
  9789. *
  9790. * parameters = {
  9791. * color: <hex>,
  9792. * program: <function>,
  9793. * opacity: <float>,
  9794. * blending: THREE.NormalBlending
  9795. * }
  9796. */
  9797. THREE.SpriteCanvasMaterial = function ( parameters ) {
  9798. THREE.Material.call( this );
  9799. this.color = new THREE.Color( 0xffffff );
  9800. this.program = function ( context, color ) {};
  9801. this.setValues( parameters );
  9802. };
  9803. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  9804. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  9805. var material = new THREE.SpriteCanvasMaterial();
  9806. THREE.Material.prototype.clone.call( this, material );
  9807. material.color.copy( this.color );
  9808. material.program = this.program;
  9809. return material;
  9810. };
  9811. // backwards compatibility
  9812. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  9813. /**
  9814. * @author mrdoob / http://mrdoob.com/
  9815. * @author alteredq / http://alteredqualia.com/
  9816. * @author szimek / https://github.com/szimek/
  9817. */
  9818. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9819. this.id = THREE.TextureIdCount ++;
  9820. this.uuid = THREE.Math.generateUUID();
  9821. this.name = '';
  9822. this.image = image;
  9823. this.mipmaps = [];
  9824. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  9825. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9826. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9827. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9828. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9829. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9830. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9831. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9832. this.offset = new THREE.Vector2( 0, 0 );
  9833. this.repeat = new THREE.Vector2( 1, 1 );
  9834. this.generateMipmaps = true;
  9835. this.premultiplyAlpha = false;
  9836. this.flipY = true;
  9837. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9838. this._needsUpdate = false;
  9839. this.onUpdate = null;
  9840. };
  9841. THREE.Texture.prototype = {
  9842. constructor: THREE.Texture,
  9843. get needsUpdate () {
  9844. return this._needsUpdate;
  9845. },
  9846. set needsUpdate ( value ) {
  9847. if ( value === true ) this.update();
  9848. this._needsUpdate = value;
  9849. },
  9850. clone: function ( texture ) {
  9851. if ( texture === undefined ) texture = new THREE.Texture();
  9852. texture.image = this.image;
  9853. texture.mipmaps = this.mipmaps.slice(0);
  9854. texture.mapping = this.mapping;
  9855. texture.wrapS = this.wrapS;
  9856. texture.wrapT = this.wrapT;
  9857. texture.magFilter = this.magFilter;
  9858. texture.minFilter = this.minFilter;
  9859. texture.anisotropy = this.anisotropy;
  9860. texture.format = this.format;
  9861. texture.type = this.type;
  9862. texture.offset.copy( this.offset );
  9863. texture.repeat.copy( this.repeat );
  9864. texture.generateMipmaps = this.generateMipmaps;
  9865. texture.premultiplyAlpha = this.premultiplyAlpha;
  9866. texture.flipY = this.flipY;
  9867. texture.unpackAlignment = this.unpackAlignment;
  9868. return texture;
  9869. },
  9870. update: function () {
  9871. this.dispatchEvent( { type: 'update' } );
  9872. },
  9873. dispose: function () {
  9874. this.dispatchEvent( { type: 'dispose' } );
  9875. }
  9876. };
  9877. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9878. THREE.TextureIdCount = 0;
  9879. /**
  9880. * @author alteredq / http://alteredqualia.com/
  9881. */
  9882. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9883. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9884. this.image = { width: width, height: height };
  9885. this.mipmaps = mipmaps;
  9886. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  9887. };
  9888. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9889. THREE.CompressedTexture.prototype.clone = function () {
  9890. var texture = new THREE.CompressedTexture();
  9891. THREE.Texture.prototype.clone.call( this, texture );
  9892. return texture;
  9893. };
  9894. /**
  9895. * @author alteredq / http://alteredqualia.com/
  9896. */
  9897. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9898. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9899. this.image = { data: data, width: width, height: height };
  9900. };
  9901. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9902. THREE.DataTexture.prototype.clone = function () {
  9903. var texture = new THREE.DataTexture();
  9904. THREE.Texture.prototype.clone.call( this, texture );
  9905. return texture;
  9906. };
  9907. /**
  9908. * @author alteredq / http://alteredqualia.com/
  9909. */
  9910. THREE.ParticleSystem = function ( geometry, material ) {
  9911. THREE.Object3D.call( this );
  9912. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9913. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9914. this.sortParticles = false;
  9915. this.frustumCulled = false;
  9916. };
  9917. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9918. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9919. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9920. object.sortParticles = this.sortParticles;
  9921. THREE.Object3D.prototype.clone.call( this, object );
  9922. return object;
  9923. };
  9924. /**
  9925. * @author mrdoob / http://mrdoob.com/
  9926. */
  9927. THREE.Line = function ( geometry, material, type ) {
  9928. THREE.Object3D.call( this );
  9929. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9930. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9931. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9932. };
  9933. THREE.LineStrip = 0;
  9934. THREE.LinePieces = 1;
  9935. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9936. THREE.Line.prototype.clone = function ( object ) {
  9937. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9938. THREE.Object3D.prototype.clone.call( this, object );
  9939. return object;
  9940. };
  9941. /**
  9942. * @author mrdoob / http://mrdoob.com/
  9943. * @author alteredq / http://alteredqualia.com/
  9944. * @author mikael emtinger / http://gomo.se/
  9945. * @author jonobr1 / http://jonobr1.com/
  9946. */
  9947. THREE.Mesh = function ( geometry, material ) {
  9948. THREE.Object3D.call( this );
  9949. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9950. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9951. this.updateMorphTargets();
  9952. };
  9953. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9954. THREE.Mesh.prototype.updateMorphTargets = function () {
  9955. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9956. this.morphTargetBase = -1;
  9957. this.morphTargetForcedOrder = [];
  9958. this.morphTargetInfluences = [];
  9959. this.morphTargetDictionary = {};
  9960. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9961. this.morphTargetInfluences.push( 0 );
  9962. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9963. }
  9964. }
  9965. };
  9966. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9967. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9968. return this.morphTargetDictionary[ name ];
  9969. }
  9970. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9971. return 0;
  9972. };
  9973. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9974. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9975. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9976. return object;
  9977. };
  9978. /**
  9979. * @author mikael emtinger / http://gomo.se/
  9980. * @author alteredq / http://alteredqualia.com/
  9981. */
  9982. THREE.Bone = function( belongsToSkin ) {
  9983. THREE.Object3D.call( this );
  9984. this.skin = belongsToSkin;
  9985. this.skinMatrix = new THREE.Matrix4();
  9986. };
  9987. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9988. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9989. // update local
  9990. if ( this.matrixAutoUpdate ) {
  9991. forceUpdate |= this.updateMatrix();
  9992. }
  9993. // update skin matrix
  9994. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9995. if ( parentSkinMatrix ) {
  9996. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9997. } else {
  9998. this.skinMatrix.copy( this.matrix );
  9999. }
  10000. this.matrixWorldNeedsUpdate = false;
  10001. forceUpdate = true;
  10002. }
  10003. // update children
  10004. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10005. this.children[ i ].update( this.skinMatrix, forceUpdate );
  10006. }
  10007. };
  10008. /**
  10009. * @author mikael emtinger / http://gomo.se/
  10010. * @author alteredq / http://alteredqualia.com/
  10011. */
  10012. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  10013. THREE.Mesh.call( this, geometry, material );
  10014. //
  10015. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  10016. // init bones
  10017. this.identityMatrix = new THREE.Matrix4();
  10018. this.bones = [];
  10019. this.boneMatrices = [];
  10020. var b, bone, gbone, p, q, s;
  10021. if ( this.geometry && this.geometry.bones !== undefined ) {
  10022. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  10023. gbone = this.geometry.bones[ b ];
  10024. p = gbone.pos;
  10025. q = gbone.rotq;
  10026. s = gbone.scl;
  10027. bone = this.addBone();
  10028. bone.name = gbone.name;
  10029. bone.position.set( p[0], p[1], p[2] );
  10030. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  10031. if ( s !== undefined ) {
  10032. bone.scale.set( s[0], s[1], s[2] );
  10033. } else {
  10034. bone.scale.set( 1, 1, 1 );
  10035. }
  10036. }
  10037. for ( b = 0; b < this.bones.length; b ++ ) {
  10038. gbone = this.geometry.bones[ b ];
  10039. bone = this.bones[ b ];
  10040. if ( gbone.parent === -1 ) {
  10041. this.add( bone );
  10042. } else {
  10043. this.bones[ gbone.parent ].add( bone );
  10044. }
  10045. }
  10046. //
  10047. var nBones = this.bones.length;
  10048. if ( this.useVertexTexture ) {
  10049. // layout (1 matrix = 4 pixels)
  10050. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  10051. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  10052. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  10053. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  10054. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  10055. var size;
  10056. if ( nBones > 256 )
  10057. size = 64;
  10058. else if ( nBones > 64 )
  10059. size = 32;
  10060. else if ( nBones > 16 )
  10061. size = 16;
  10062. else
  10063. size = 8;
  10064. this.boneTextureWidth = size;
  10065. this.boneTextureHeight = size;
  10066. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  10067. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  10068. this.boneTexture.minFilter = THREE.NearestFilter;
  10069. this.boneTexture.magFilter = THREE.NearestFilter;
  10070. this.boneTexture.generateMipmaps = false;
  10071. this.boneTexture.flipY = false;
  10072. } else {
  10073. this.boneMatrices = new Float32Array( 16 * nBones );
  10074. }
  10075. this.pose();
  10076. }
  10077. };
  10078. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  10079. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  10080. if ( bone === undefined ) {
  10081. bone = new THREE.Bone( this );
  10082. }
  10083. this.bones.push( bone );
  10084. return bone;
  10085. };
  10086. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  10087. var offsetMatrix = new THREE.Matrix4();
  10088. return function ( force ) {
  10089. this.matrixAutoUpdate && this.updateMatrix();
  10090. // update matrixWorld
  10091. if ( this.matrixWorldNeedsUpdate || force ) {
  10092. if ( this.parent ) {
  10093. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10094. } else {
  10095. this.matrixWorld.copy( this.matrix );
  10096. }
  10097. this.matrixWorldNeedsUpdate = false;
  10098. force = true;
  10099. }
  10100. // update children
  10101. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10102. var child = this.children[ i ];
  10103. if ( child instanceof THREE.Bone ) {
  10104. child.update( this.identityMatrix, false );
  10105. } else {
  10106. child.updateMatrixWorld( true );
  10107. }
  10108. }
  10109. // make a snapshot of the bones' rest position
  10110. if ( this.boneInverses == undefined ) {
  10111. this.boneInverses = [];
  10112. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10113. var inverse = new THREE.Matrix4();
  10114. inverse.getInverse( this.bones[ b ].skinMatrix );
  10115. this.boneInverses.push( inverse );
  10116. }
  10117. }
  10118. // flatten bone matrices to array
  10119. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10120. // compute the offset between the current and the original transform;
  10121. // TODO: we could get rid of this multiplication step if the skinMatrix
  10122. // was already representing the offset; however, this requires some
  10123. // major changes to the animation system
  10124. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  10125. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  10126. }
  10127. if ( this.useVertexTexture ) {
  10128. this.boneTexture.needsUpdate = true;
  10129. }
  10130. };
  10131. }();
  10132. THREE.SkinnedMesh.prototype.pose = function () {
  10133. this.updateMatrixWorld( true );
  10134. this.normalizeSkinWeights();
  10135. };
  10136. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  10137. if ( this.geometry instanceof THREE.Geometry ) {
  10138. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  10139. var sw = this.geometry.skinWeights[ i ];
  10140. var scale = 1.0 / sw.lengthManhattan();
  10141. if ( scale !== Infinity ) {
  10142. sw.multiplyScalar( scale );
  10143. } else {
  10144. sw.set( 1 ); // this will be normalized by the shader anyway
  10145. }
  10146. }
  10147. } else {
  10148. // skinning weights assumed to be normalized for THREE.BufferGeometry
  10149. }
  10150. };
  10151. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  10152. if ( object === undefined ) {
  10153. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  10154. }
  10155. THREE.Mesh.prototype.clone.call( this, object );
  10156. return object;
  10157. };
  10158. /**
  10159. * @author alteredq / http://alteredqualia.com/
  10160. */
  10161. THREE.MorphAnimMesh = function ( geometry, material ) {
  10162. THREE.Mesh.call( this, geometry, material );
  10163. // API
  10164. this.duration = 1000; // milliseconds
  10165. this.mirroredLoop = false;
  10166. this.time = 0;
  10167. // internals
  10168. this.lastKeyframe = 0;
  10169. this.currentKeyframe = 0;
  10170. this.direction = 1;
  10171. this.directionBackwards = false;
  10172. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  10173. };
  10174. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  10175. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  10176. this.startKeyframe = start;
  10177. this.endKeyframe = end;
  10178. this.length = this.endKeyframe - this.startKeyframe + 1;
  10179. };
  10180. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  10181. this.direction = 1;
  10182. this.directionBackwards = false;
  10183. };
  10184. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  10185. this.direction = -1;
  10186. this.directionBackwards = true;
  10187. };
  10188. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  10189. var geometry = this.geometry;
  10190. if ( ! geometry.animations ) geometry.animations = {};
  10191. var firstAnimation, animations = geometry.animations;
  10192. var pattern = /([a-z]+)(\d+)/;
  10193. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  10194. var morph = geometry.morphTargets[ i ];
  10195. var parts = morph.name.match( pattern );
  10196. if ( parts && parts.length > 1 ) {
  10197. var label = parts[ 1 ];
  10198. var num = parts[ 2 ];
  10199. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  10200. var animation = animations[ label ];
  10201. if ( i < animation.start ) animation.start = i;
  10202. if ( i > animation.end ) animation.end = i;
  10203. if ( ! firstAnimation ) firstAnimation = label;
  10204. }
  10205. }
  10206. geometry.firstAnimation = firstAnimation;
  10207. };
  10208. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  10209. if ( ! this.geometry.animations ) this.geometry.animations = {};
  10210. this.geometry.animations[ label ] = { start: start, end: end };
  10211. };
  10212. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  10213. var animation = this.geometry.animations[ label ];
  10214. if ( animation ) {
  10215. this.setFrameRange( animation.start, animation.end );
  10216. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  10217. this.time = 0;
  10218. } else {
  10219. console.warn( "animation[" + label + "] undefined" );
  10220. }
  10221. };
  10222. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  10223. var frameTime = this.duration / this.length;
  10224. this.time += this.direction * delta;
  10225. if ( this.mirroredLoop ) {
  10226. if ( this.time > this.duration || this.time < 0 ) {
  10227. this.direction *= -1;
  10228. if ( this.time > this.duration ) {
  10229. this.time = this.duration;
  10230. this.directionBackwards = true;
  10231. }
  10232. if ( this.time < 0 ) {
  10233. this.time = 0;
  10234. this.directionBackwards = false;
  10235. }
  10236. }
  10237. } else {
  10238. this.time = this.time % this.duration;
  10239. if ( this.time < 0 ) this.time += this.duration;
  10240. }
  10241. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  10242. if ( keyframe !== this.currentKeyframe ) {
  10243. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  10244. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  10245. this.morphTargetInfluences[ keyframe ] = 0;
  10246. this.lastKeyframe = this.currentKeyframe;
  10247. this.currentKeyframe = keyframe;
  10248. }
  10249. var mix = ( this.time % frameTime ) / frameTime;
  10250. if ( this.directionBackwards ) {
  10251. mix = 1 - mix;
  10252. }
  10253. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  10254. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  10255. };
  10256. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  10257. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  10258. object.duration = this.duration;
  10259. object.mirroredLoop = this.mirroredLoop;
  10260. object.time = this.time;
  10261. object.lastKeyframe = this.lastKeyframe;
  10262. object.currentKeyframe = this.currentKeyframe;
  10263. object.direction = this.direction;
  10264. object.directionBackwards = this.directionBackwards;
  10265. THREE.Mesh.prototype.clone.call( this, object );
  10266. return object;
  10267. };
  10268. /**
  10269. * @author mikael emtinger / http://gomo.se/
  10270. * @author alteredq / http://alteredqualia.com/
  10271. * @author mrdoob / http://mrdoob.com/
  10272. */
  10273. THREE.LOD = function () {
  10274. THREE.Object3D.call( this );
  10275. this.objects = [];
  10276. };
  10277. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  10278. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  10279. if ( distance === undefined ) distance = 0;
  10280. distance = Math.abs( distance );
  10281. for ( var l = 0; l < this.objects.length; l ++ ) {
  10282. if ( distance < this.objects[ l ].distance ) {
  10283. break;
  10284. }
  10285. }
  10286. this.objects.splice( l, 0, { distance: distance, object: object } );
  10287. this.add( object );
  10288. };
  10289. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  10290. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  10291. if ( distance < this.objects[ i ].distance ) {
  10292. break;
  10293. }
  10294. }
  10295. return this.objects[ i - 1 ].object;
  10296. };
  10297. THREE.LOD.prototype.update = function () {
  10298. var v1 = new THREE.Vector3();
  10299. var v2 = new THREE.Vector3();
  10300. return function ( camera ) {
  10301. if ( this.objects.length > 1 ) {
  10302. v1.setFromMatrixPosition( camera.matrixWorld );
  10303. v2.setFromMatrixPosition( this.matrixWorld );
  10304. var distance = v1.distanceTo( v2 );
  10305. this.objects[ 0 ].object.visible = true;
  10306. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  10307. if ( distance >= this.objects[ i ].distance ) {
  10308. this.objects[ i - 1 ].object.visible = false;
  10309. this.objects[ i ].object.visible = true;
  10310. } else {
  10311. break;
  10312. }
  10313. }
  10314. for( ; i < l; i ++ ) {
  10315. this.objects[ i ].object.visible = false;
  10316. }
  10317. }
  10318. };
  10319. }();
  10320. THREE.LOD.prototype.clone = function ( object ) {
  10321. if ( object === undefined ) object = new THREE.LOD();
  10322. THREE.Object3D.prototype.clone.call( this, object );
  10323. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  10324. var x = this.objects[i].object.clone();
  10325. x.visible = i === 0;
  10326. object.addLevel( x, this.objects[i].distance );
  10327. }
  10328. return object;
  10329. };
  10330. /**
  10331. * @author mikael emtinger / http://gomo.se/
  10332. * @author alteredq / http://alteredqualia.com/
  10333. */
  10334. THREE.Sprite = ( function () {
  10335. var vertices = new THREE.Float32Attribute( 3, 3 );
  10336. vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  10337. var geometry = new THREE.BufferGeometry();
  10338. geometry.addAttribute( 'position', vertices );
  10339. return function ( material ) {
  10340. THREE.Object3D.call( this );
  10341. this.geometry = geometry;
  10342. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  10343. };
  10344. } )();
  10345. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  10346. /*
  10347. * Custom update matrix
  10348. */
  10349. THREE.Sprite.prototype.updateMatrix = function () {
  10350. this.matrix.compose( this.position, this.quaternion, this.scale );
  10351. this.matrixWorldNeedsUpdate = true;
  10352. };
  10353. THREE.Sprite.prototype.clone = function ( object ) {
  10354. if ( object === undefined ) object = new THREE.Sprite( this.material );
  10355. THREE.Object3D.prototype.clone.call( this, object );
  10356. return object;
  10357. };
  10358. // Backwards compatibility
  10359. THREE.Particle = THREE.Sprite;
  10360. /**
  10361. * @author mrdoob / http://mrdoob.com/
  10362. */
  10363. THREE.Scene = function () {
  10364. THREE.Object3D.call( this );
  10365. this.fog = null;
  10366. this.overrideMaterial = null;
  10367. this.autoUpdate = true; // checked by the renderer
  10368. this.matrixAutoUpdate = false;
  10369. this.__lights = [];
  10370. this.__objectsAdded = [];
  10371. this.__objectsRemoved = [];
  10372. };
  10373. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  10374. THREE.Scene.prototype.__addObject = function ( object ) {
  10375. if ( object instanceof THREE.Light ) {
  10376. if ( this.__lights.indexOf( object ) === - 1 ) {
  10377. this.__lights.push( object );
  10378. }
  10379. if ( object.target && object.target.parent === undefined ) {
  10380. this.add( object.target );
  10381. }
  10382. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  10383. this.__objectsAdded.push( object );
  10384. // check if previously removed
  10385. var i = this.__objectsRemoved.indexOf( object );
  10386. if ( i !== -1 ) {
  10387. this.__objectsRemoved.splice( i, 1 );
  10388. }
  10389. }
  10390. this.dispatchEvent( { type: 'objectAdded', object: object } );
  10391. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  10392. for ( var c = 0; c < object.children.length; c ++ ) {
  10393. this.__addObject( object.children[ c ] );
  10394. }
  10395. };
  10396. THREE.Scene.prototype.__removeObject = function ( object ) {
  10397. if ( object instanceof THREE.Light ) {
  10398. var i = this.__lights.indexOf( object );
  10399. if ( i !== -1 ) {
  10400. this.__lights.splice( i, 1 );
  10401. }
  10402. if ( object.shadowCascadeArray ) {
  10403. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  10404. this.__removeObject( object.shadowCascadeArray[ x ] );
  10405. }
  10406. }
  10407. } else if ( !( object instanceof THREE.Camera ) ) {
  10408. this.__objectsRemoved.push( object );
  10409. // check if previously added
  10410. var i = this.__objectsAdded.indexOf( object );
  10411. if ( i !== -1 ) {
  10412. this.__objectsAdded.splice( i, 1 );
  10413. }
  10414. }
  10415. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  10416. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  10417. for ( var c = 0; c < object.children.length; c ++ ) {
  10418. this.__removeObject( object.children[ c ] );
  10419. }
  10420. };
  10421. THREE.Scene.prototype.clone = function ( object ) {
  10422. if ( object === undefined ) object = new THREE.Scene();
  10423. THREE.Object3D.prototype.clone.call(this, object);
  10424. if ( this.fog !== null ) object.fog = this.fog.clone();
  10425. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  10426. object.autoUpdate = this.autoUpdate;
  10427. object.matrixAutoUpdate = this.matrixAutoUpdate;
  10428. return object;
  10429. };
  10430. /**
  10431. * @author mrdoob / http://mrdoob.com/
  10432. * @author alteredq / http://alteredqualia.com/
  10433. */
  10434. THREE.Fog = function ( color, near, far ) {
  10435. this.name = '';
  10436. this.color = new THREE.Color( color );
  10437. this.near = ( near !== undefined ) ? near : 1;
  10438. this.far = ( far !== undefined ) ? far : 1000;
  10439. };
  10440. THREE.Fog.prototype.clone = function () {
  10441. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  10442. };
  10443. /**
  10444. * @author mrdoob / http://mrdoob.com/
  10445. * @author alteredq / http://alteredqualia.com/
  10446. */
  10447. THREE.FogExp2 = function ( color, density ) {
  10448. this.name = '';
  10449. this.color = new THREE.Color( color );
  10450. this.density = ( density !== undefined ) ? density : 0.00025;
  10451. };
  10452. THREE.FogExp2.prototype.clone = function () {
  10453. return new THREE.FogExp2( this.color.getHex(), this.density );
  10454. };
  10455. /**
  10456. * @author mrdoob / http://mrdoob.com/
  10457. */
  10458. THREE.CanvasRenderer = function ( parameters ) {
  10459. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  10460. var smoothstep = THREE.Math.smoothstep;
  10461. parameters = parameters || {};
  10462. var _this = this,
  10463. _renderData, _elements, _lights,
  10464. _projector = new THREE.Projector(),
  10465. _canvas = parameters.canvas !== undefined
  10466. ? parameters.canvas
  10467. : document.createElement( 'canvas' ),
  10468. _canvasWidth = _canvas.width,
  10469. _canvasHeight = _canvas.height,
  10470. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  10471. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  10472. _context = _canvas.getContext( '2d', {
  10473. alpha: parameters.alpha === true
  10474. } ),
  10475. _clearColor = new THREE.Color( 0x000000 ),
  10476. _clearAlpha = 0,
  10477. _contextGlobalAlpha = 1,
  10478. _contextGlobalCompositeOperation = 0,
  10479. _contextStrokeStyle = null,
  10480. _contextFillStyle = null,
  10481. _contextLineWidth = null,
  10482. _contextLineCap = null,
  10483. _contextLineJoin = null,
  10484. _contextDashSize = null,
  10485. _contextGapSize = 0,
  10486. _camera,
  10487. _v1, _v2, _v3, _v4,
  10488. _v5 = new THREE.RenderableVertex(),
  10489. _v6 = new THREE.RenderableVertex(),
  10490. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  10491. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  10492. _color = new THREE.Color(),
  10493. _color1 = new THREE.Color(),
  10494. _color2 = new THREE.Color(),
  10495. _color3 = new THREE.Color(),
  10496. _color4 = new THREE.Color(),
  10497. _diffuseColor = new THREE.Color(),
  10498. _emissiveColor = new THREE.Color(),
  10499. _lightColor = new THREE.Color(),
  10500. _patterns = {},
  10501. _image, _uvs,
  10502. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  10503. _clipBox = new THREE.Box2(),
  10504. _clearBox = new THREE.Box2(),
  10505. _elemBox = new THREE.Box2(),
  10506. _ambientLight = new THREE.Color(),
  10507. _directionalLights = new THREE.Color(),
  10508. _pointLights = new THREE.Color(),
  10509. _vector3 = new THREE.Vector3(), // Needed for PointLight
  10510. _centroid = new THREE.Vector3(),
  10511. _normal = new THREE.Vector3(),
  10512. _normalViewMatrix = new THREE.Matrix3();
  10513. // dash+gap fallbacks for Firefox and everything else
  10514. if ( _context.setLineDash === undefined ) {
  10515. _context.setLineDash = function () {}
  10516. }
  10517. this.domElement = _canvas;
  10518. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10519. ? parameters.devicePixelRatio
  10520. : self.devicePixelRatio !== undefined
  10521. ? self.devicePixelRatio
  10522. : 1;
  10523. this.autoClear = true;
  10524. this.sortObjects = true;
  10525. this.sortElements = true;
  10526. this.info = {
  10527. render: {
  10528. vertices: 0,
  10529. faces: 0
  10530. }
  10531. }
  10532. // WebGLRenderer compatibility
  10533. this.supportsVertexTextures = function () {};
  10534. this.setFaceCulling = function () {};
  10535. this.setSize = function ( width, height, updateStyle ) {
  10536. _canvasWidth = width * this.devicePixelRatio;
  10537. _canvasHeight = height * this.devicePixelRatio;
  10538. _canvas.width = _canvasWidth;
  10539. _canvas.height = _canvasHeight;
  10540. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  10541. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  10542. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  10543. _canvas.style.width = width + 'px';
  10544. _canvas.style.height = height + 'px';
  10545. }
  10546. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  10547. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10548. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  10549. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10550. _contextGlobalAlpha = 1;
  10551. _contextGlobalCompositeOperation = 0;
  10552. _contextStrokeStyle = null;
  10553. _contextFillStyle = null;
  10554. _contextLineWidth = null;
  10555. _contextLineCap = null;
  10556. _contextLineJoin = null;
  10557. this.setViewport( 0, 0, width, height );
  10558. };
  10559. this.setViewport = function ( x, y, width, height ) {
  10560. var viewportX = x * this.devicePixelRatio;
  10561. var viewportY = y * this.devicePixelRatio;
  10562. var viewportWidth = width * this.devicePixelRatio;
  10563. var viewportHeight = height * this.devicePixelRatio;
  10564. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  10565. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  10566. };
  10567. this.setScissor = function () {};
  10568. this.enableScissorTest = function () {};
  10569. this.setClearColor = function ( color, alpha ) {
  10570. _clearColor.set( color );
  10571. _clearAlpha = alpha !== undefined ? alpha : 1;
  10572. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  10573. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10574. };
  10575. this.setClearColorHex = function ( hex, alpha ) {
  10576. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  10577. this.setClearColor( hex, alpha );
  10578. };
  10579. this.getMaxAnisotropy = function () {
  10580. return 0;
  10581. };
  10582. this.clear = function () {
  10583. if ( _clearBox.empty() === false ) {
  10584. _clearBox.intersect( _clipBox );
  10585. _clearBox.expandByScalar( 2 );
  10586. if ( _clearAlpha < 1 ) {
  10587. _context.clearRect(
  10588. _clearBox.min.x | 0,
  10589. _clearBox.min.y | 0,
  10590. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10591. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10592. );
  10593. }
  10594. if ( _clearAlpha > 0 ) {
  10595. setBlending( THREE.NormalBlending );
  10596. setOpacity( 1 );
  10597. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  10598. _context.fillRect(
  10599. _clearBox.min.x | 0,
  10600. _clearBox.min.y | 0,
  10601. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10602. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10603. );
  10604. }
  10605. _clearBox.makeEmpty();
  10606. }
  10607. };
  10608. // compatibility
  10609. this.clearColor = function () {};
  10610. this.clearDepth = function () {};
  10611. this.clearStencil = function () {};
  10612. this.render = function ( scene, camera ) {
  10613. if ( camera instanceof THREE.Camera === false ) {
  10614. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  10615. return;
  10616. }
  10617. if ( this.autoClear === true ) this.clear();
  10618. _this.info.render.vertices = 0;
  10619. _this.info.render.faces = 0;
  10620. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  10621. _elements = _renderData.elements;
  10622. _lights = _renderData.lights;
  10623. _camera = camera;
  10624. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  10625. /* DEBUG
  10626. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  10627. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  10628. */
  10629. calculateLights();
  10630. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  10631. var element = _elements[ e ];
  10632. var material = element.material;
  10633. if ( material === undefined || material.opacity === 0 ) continue;
  10634. _elemBox.makeEmpty();
  10635. if ( element instanceof THREE.RenderableSprite ) {
  10636. _v1 = element;
  10637. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  10638. renderSprite( _v1, element, material );
  10639. } else if ( element instanceof THREE.RenderableLine ) {
  10640. _v1 = element.v1; _v2 = element.v2;
  10641. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10642. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10643. _elemBox.setFromPoints( [
  10644. _v1.positionScreen,
  10645. _v2.positionScreen
  10646. ] );
  10647. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10648. renderLine( _v1, _v2, element, material );
  10649. }
  10650. } else if ( element instanceof THREE.RenderableFace ) {
  10651. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  10652. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  10653. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  10654. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  10655. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10656. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10657. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  10658. if ( material.overdraw > 0 ) {
  10659. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  10660. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  10661. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  10662. }
  10663. _elemBox.setFromPoints( [
  10664. _v1.positionScreen,
  10665. _v2.positionScreen,
  10666. _v3.positionScreen
  10667. ] );
  10668. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10669. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  10670. }
  10671. }
  10672. /* DEBUG
  10673. setLineWidth( 1 );
  10674. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  10675. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  10676. */
  10677. _clearBox.union( _elemBox );
  10678. }
  10679. /* DEBUG
  10680. setLineWidth( 1 );
  10681. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  10682. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  10683. */
  10684. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  10685. };
  10686. //
  10687. function calculateLights() {
  10688. _ambientLight.setRGB( 0, 0, 0 );
  10689. _directionalLights.setRGB( 0, 0, 0 );
  10690. _pointLights.setRGB( 0, 0, 0 );
  10691. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10692. var light = _lights[ l ];
  10693. var lightColor = light.color;
  10694. if ( light instanceof THREE.AmbientLight ) {
  10695. _ambientLight.add( lightColor );
  10696. } else if ( light instanceof THREE.DirectionalLight ) {
  10697. // for sprites
  10698. _directionalLights.add( lightColor );
  10699. } else if ( light instanceof THREE.PointLight ) {
  10700. // for sprites
  10701. _pointLights.add( lightColor );
  10702. }
  10703. }
  10704. }
  10705. function calculateLight( position, normal, color ) {
  10706. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10707. var light = _lights[ l ];
  10708. _lightColor.copy( light.color );
  10709. if ( light instanceof THREE.DirectionalLight ) {
  10710. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  10711. var amount = normal.dot( lightPosition );
  10712. if ( amount <= 0 ) continue;
  10713. amount *= light.intensity;
  10714. color.add( _lightColor.multiplyScalar( amount ) );
  10715. } else if ( light instanceof THREE.PointLight ) {
  10716. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  10717. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  10718. if ( amount <= 0 ) continue;
  10719. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  10720. if ( amount == 0 ) continue;
  10721. amount *= light.intensity;
  10722. color.add( _lightColor.multiplyScalar( amount ) );
  10723. }
  10724. }
  10725. }
  10726. function renderSprite( v1, element, material ) {
  10727. setOpacity( material.opacity );
  10728. setBlending( material.blending );
  10729. var scaleX = element.scale.x * _canvasWidthHalf;
  10730. var scaleY = element.scale.y * _canvasHeightHalf;
  10731. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  10732. _elemBox.min.set( v1.x - dist, v1.y - dist );
  10733. _elemBox.max.set( v1.x + dist, v1.y + dist );
  10734. if ( material instanceof THREE.SpriteMaterial ||
  10735. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  10736. var texture = material.map;
  10737. if ( texture !== null ) {
  10738. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10739. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10740. textureToPattern( texture );
  10741. }
  10742. texture.addEventListener( 'update', onTextureUpdate );
  10743. }
  10744. var pattern = _patterns[ texture.id ];
  10745. if ( pattern !== undefined ) {
  10746. setFillStyle( pattern );
  10747. } else {
  10748. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  10749. }
  10750. //
  10751. var bitmap = texture.image;
  10752. var ox = bitmap.width * texture.offset.x;
  10753. var oy = bitmap.height * texture.offset.y;
  10754. var sx = bitmap.width * texture.repeat.x;
  10755. var sy = bitmap.height * texture.repeat.y;
  10756. var cx = scaleX / sx;
  10757. var cy = scaleY / sy;
  10758. _context.save();
  10759. _context.translate( v1.x, v1.y );
  10760. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10761. _context.translate( - scaleX / 2, - scaleY / 2 );
  10762. _context.scale( cx, cy );
  10763. _context.translate( - ox, - oy );
  10764. _context.fillRect( ox, oy, sx, sy );
  10765. _context.restore();
  10766. } else { // no texture
  10767. setFillStyle( material.color.getStyle() );
  10768. _context.save();
  10769. _context.translate( v1.x, v1.y );
  10770. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10771. _context.scale( scaleX, - scaleY );
  10772. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  10773. _context.restore();
  10774. }
  10775. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  10776. setStrokeStyle( material.color.getStyle() );
  10777. setFillStyle( material.color.getStyle() );
  10778. _context.save();
  10779. _context.translate( v1.x, v1.y );
  10780. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10781. _context.scale( scaleX, scaleY );
  10782. material.program( _context );
  10783. _context.restore();
  10784. }
  10785. /* DEBUG
  10786. setStrokeStyle( 'rgb(255,255,0)' );
  10787. _context.beginPath();
  10788. _context.moveTo( v1.x - 10, v1.y );
  10789. _context.lineTo( v1.x + 10, v1.y );
  10790. _context.moveTo( v1.x, v1.y - 10 );
  10791. _context.lineTo( v1.x, v1.y + 10 );
  10792. _context.stroke();
  10793. */
  10794. }
  10795. function renderLine( v1, v2, element, material ) {
  10796. setOpacity( material.opacity );
  10797. setBlending( material.blending );
  10798. _context.beginPath();
  10799. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  10800. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  10801. if ( material instanceof THREE.LineBasicMaterial ) {
  10802. setLineWidth( material.linewidth );
  10803. setLineCap( material.linecap );
  10804. setLineJoin( material.linejoin );
  10805. if ( material.vertexColors !== THREE.VertexColors ) {
  10806. setStrokeStyle( material.color.getStyle() );
  10807. } else {
  10808. var colorStyle1 = element.vertexColors[0].getStyle();
  10809. var colorStyle2 = element.vertexColors[1].getStyle();
  10810. if ( colorStyle1 === colorStyle2 ) {
  10811. setStrokeStyle( colorStyle1 );
  10812. } else {
  10813. try {
  10814. var grad = _context.createLinearGradient(
  10815. v1.positionScreen.x,
  10816. v1.positionScreen.y,
  10817. v2.positionScreen.x,
  10818. v2.positionScreen.y
  10819. );
  10820. grad.addColorStop( 0, colorStyle1 );
  10821. grad.addColorStop( 1, colorStyle2 );
  10822. } catch ( exception ) {
  10823. grad = colorStyle1;
  10824. }
  10825. setStrokeStyle( grad );
  10826. }
  10827. }
  10828. _context.stroke();
  10829. _elemBox.expandByScalar( material.linewidth * 2 );
  10830. } else if ( material instanceof THREE.LineDashedMaterial ) {
  10831. setLineWidth( material.linewidth );
  10832. setLineCap( material.linecap );
  10833. setLineJoin( material.linejoin );
  10834. setStrokeStyle( material.color.getStyle() );
  10835. setDashAndGap( material.dashSize, material.gapSize );
  10836. _context.stroke();
  10837. _elemBox.expandByScalar( material.linewidth * 2 );
  10838. setDashAndGap( null, null );
  10839. }
  10840. }
  10841. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  10842. _this.info.render.vertices += 3;
  10843. _this.info.render.faces ++;
  10844. setOpacity( material.opacity );
  10845. setBlending( material.blending );
  10846. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  10847. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  10848. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  10849. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  10850. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  10851. _diffuseColor.copy( material.color );
  10852. _emissiveColor.copy( material.emissive );
  10853. if ( material.vertexColors === THREE.FaceColors ) {
  10854. _diffuseColor.multiply( element.color );
  10855. }
  10856. _color.copy( _ambientLight );
  10857. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  10858. calculateLight( _centroid, element.normalModel, _color );
  10859. _color.multiply( _diffuseColor ).add( _emissiveColor );
  10860. material.wireframe === true
  10861. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10862. : fillPath( _color );
  10863. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  10864. if ( material.map !== null ) {
  10865. if ( material.map.mapping instanceof THREE.UVMapping ) {
  10866. _uvs = element.uvs;
  10867. 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 );
  10868. }
  10869. } else if ( material.envMap !== null ) {
  10870. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  10871. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10872. _uv1x = 0.5 * _normal.x + 0.5;
  10873. _uv1y = 0.5 * _normal.y + 0.5;
  10874. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10875. _uv2x = 0.5 * _normal.x + 0.5;
  10876. _uv2y = 0.5 * _normal.y + 0.5;
  10877. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10878. _uv3x = 0.5 * _normal.x + 0.5;
  10879. _uv3y = 0.5 * _normal.y + 0.5;
  10880. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10881. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  10882. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10883. _uv1x = - 0.5 * _normal.x + 0.5;
  10884. _uv1y = - 0.5 * _normal.y + 0.5;
  10885. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10886. _uv2x = - 0.5 * _normal.x + 0.5;
  10887. _uv2y = - 0.5 * _normal.y + 0.5;
  10888. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10889. _uv3x = - 0.5 * _normal.x + 0.5;
  10890. _uv3y = - 0.5 * _normal.y + 0.5;
  10891. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10892. }
  10893. } else {
  10894. _color.copy( material.color );
  10895. if ( material.vertexColors === THREE.FaceColors ) {
  10896. _color.multiply( element.color );
  10897. }
  10898. material.wireframe === true
  10899. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10900. : fillPath( _color );
  10901. }
  10902. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  10903. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  10904. material.wireframe === true
  10905. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10906. : fillPath( _color );
  10907. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10908. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10909. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10910. material.wireframe === true
  10911. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10912. : fillPath( _color );
  10913. } else {
  10914. _color.setRGB( 1, 1, 1 );
  10915. material.wireframe === true
  10916. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10917. : fillPath( _color );
  10918. }
  10919. }
  10920. //
  10921. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10922. _context.beginPath();
  10923. _context.moveTo( x0, y0 );
  10924. _context.lineTo( x1, y1 );
  10925. _context.lineTo( x2, y2 );
  10926. _context.closePath();
  10927. }
  10928. function strokePath( color, linewidth, linecap, linejoin ) {
  10929. setLineWidth( linewidth );
  10930. setLineCap( linecap );
  10931. setLineJoin( linejoin );
  10932. setStrokeStyle( color.getStyle() );
  10933. _context.stroke();
  10934. _elemBox.expandByScalar( linewidth * 2 );
  10935. }
  10936. function fillPath( color ) {
  10937. setFillStyle( color.getStyle() );
  10938. _context.fill();
  10939. }
  10940. function onTextureUpdate ( event ) {
  10941. textureToPattern( event.target );
  10942. }
  10943. function textureToPattern( texture ) {
  10944. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10945. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10946. var image = texture.image;
  10947. var canvas = document.createElement( 'canvas' );
  10948. canvas.width = image.width;
  10949. canvas.height = image.height;
  10950. var context = canvas.getContext( '2d' );
  10951. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10952. context.drawImage( image, 0, 0 );
  10953. _patterns[ texture.id ] = _context.createPattern(
  10954. canvas, repeatX === true && repeatY === true
  10955. ? 'repeat'
  10956. : repeatX === true && repeatY === false
  10957. ? 'repeat-x'
  10958. : repeatX === false && repeatY === true
  10959. ? 'repeat-y'
  10960. : 'no-repeat'
  10961. );
  10962. }
  10963. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10964. if ( texture instanceof THREE.DataTexture ) return;
  10965. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10966. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10967. textureToPattern( texture );
  10968. }
  10969. texture.addEventListener( 'update', onTextureUpdate );
  10970. }
  10971. var pattern = _patterns[ texture.id ];
  10972. if ( pattern !== undefined ) {
  10973. setFillStyle( pattern );
  10974. } else {
  10975. setFillStyle( 'rgba(0,0,0,1)' );
  10976. _context.fill();
  10977. return;
  10978. }
  10979. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10980. var a, b, c, d, e, f, det, idet,
  10981. offsetX = texture.offset.x / texture.repeat.x,
  10982. offsetY = texture.offset.y / texture.repeat.y,
  10983. width = texture.image.width * texture.repeat.x,
  10984. height = texture.image.height * texture.repeat.y;
  10985. u0 = ( u0 + offsetX ) * width;
  10986. v0 = ( v0 + offsetY ) * height;
  10987. u1 = ( u1 + offsetX ) * width;
  10988. v1 = ( v1 + offsetY ) * height;
  10989. u2 = ( u2 + offsetX ) * width;
  10990. v2 = ( v2 + offsetY ) * height;
  10991. x1 -= x0; y1 -= y0;
  10992. x2 -= x0; y2 -= y0;
  10993. u1 -= u0; v1 -= v0;
  10994. u2 -= u0; v2 -= v0;
  10995. det = u1 * v2 - u2 * v1;
  10996. if ( det === 0 ) return;
  10997. idet = 1 / det;
  10998. a = ( v2 * x1 - v1 * x2 ) * idet;
  10999. b = ( v2 * y1 - v1 * y2 ) * idet;
  11000. c = ( u1 * x2 - u2 * x1 ) * idet;
  11001. d = ( u1 * y2 - u2 * y1 ) * idet;
  11002. e = x0 - a * u0 - c * v0;
  11003. f = y0 - b * u0 - d * v0;
  11004. _context.save();
  11005. _context.transform( a, b, c, d, e, f );
  11006. _context.fill();
  11007. _context.restore();
  11008. }
  11009. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  11010. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  11011. var a, b, c, d, e, f, det, idet,
  11012. width = image.width - 1,
  11013. height = image.height - 1;
  11014. u0 *= width; v0 *= height;
  11015. u1 *= width; v1 *= height;
  11016. u2 *= width; v2 *= height;
  11017. x1 -= x0; y1 -= y0;
  11018. x2 -= x0; y2 -= y0;
  11019. u1 -= u0; v1 -= v0;
  11020. u2 -= u0; v2 -= v0;
  11021. det = u1 * v2 - u2 * v1;
  11022. idet = 1 / det;
  11023. a = ( v2 * x1 - v1 * x2 ) * idet;
  11024. b = ( v2 * y1 - v1 * y2 ) * idet;
  11025. c = ( u1 * x2 - u2 * x1 ) * idet;
  11026. d = ( u1 * y2 - u2 * y1 ) * idet;
  11027. e = x0 - a * u0 - c * v0;
  11028. f = y0 - b * u0 - d * v0;
  11029. _context.save();
  11030. _context.transform( a, b, c, d, e, f );
  11031. _context.clip();
  11032. _context.drawImage( image, 0, 0 );
  11033. _context.restore();
  11034. }
  11035. // Hide anti-alias gaps
  11036. function expand( v1, v2, pixels ) {
  11037. var x = v2.x - v1.x, y = v2.y - v1.y,
  11038. det = x * x + y * y, idet;
  11039. if ( det === 0 ) return;
  11040. idet = pixels / Math.sqrt( det );
  11041. x *= idet; y *= idet;
  11042. v2.x += x; v2.y += y;
  11043. v1.x -= x; v1.y -= y;
  11044. }
  11045. // Context cached methods.
  11046. function setOpacity( value ) {
  11047. if ( _contextGlobalAlpha !== value ) {
  11048. _context.globalAlpha = value;
  11049. _contextGlobalAlpha = value;
  11050. }
  11051. }
  11052. function setBlending( value ) {
  11053. if ( _contextGlobalCompositeOperation !== value ) {
  11054. if ( value === THREE.NormalBlending ) {
  11055. _context.globalCompositeOperation = 'source-over';
  11056. } else if ( value === THREE.AdditiveBlending ) {
  11057. _context.globalCompositeOperation = 'lighter';
  11058. } else if ( value === THREE.SubtractiveBlending ) {
  11059. _context.globalCompositeOperation = 'darker';
  11060. }
  11061. _contextGlobalCompositeOperation = value;
  11062. }
  11063. }
  11064. function setLineWidth( value ) {
  11065. if ( _contextLineWidth !== value ) {
  11066. _context.lineWidth = value;
  11067. _contextLineWidth = value;
  11068. }
  11069. }
  11070. function setLineCap( value ) {
  11071. // "butt", "round", "square"
  11072. if ( _contextLineCap !== value ) {
  11073. _context.lineCap = value;
  11074. _contextLineCap = value;
  11075. }
  11076. }
  11077. function setLineJoin( value ) {
  11078. // "round", "bevel", "miter"
  11079. if ( _contextLineJoin !== value ) {
  11080. _context.lineJoin = value;
  11081. _contextLineJoin = value;
  11082. }
  11083. }
  11084. function setStrokeStyle( value ) {
  11085. if ( _contextStrokeStyle !== value ) {
  11086. _context.strokeStyle = value;
  11087. _contextStrokeStyle = value;
  11088. }
  11089. }
  11090. function setFillStyle( value ) {
  11091. if ( _contextFillStyle !== value ) {
  11092. _context.fillStyle = value;
  11093. _contextFillStyle = value;
  11094. }
  11095. }
  11096. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  11097. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  11098. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  11099. _contextDashSize = dashSizeValue;
  11100. _contextGapSize = gapSizeValue;
  11101. }
  11102. }
  11103. };
  11104. /**
  11105. * Shader chunks for WebLG Shader library
  11106. *
  11107. * @author alteredq / http://alteredqualia.com/
  11108. * @author mrdoob / http://mrdoob.com/
  11109. * @author mikael emtinger / http://gomo.se/
  11110. */
  11111. THREE.ShaderChunk = {
  11112. // FOG
  11113. fog_pars_fragment: [
  11114. "#ifdef USE_FOG",
  11115. " uniform vec3 fogColor;",
  11116. " #ifdef FOG_EXP2",
  11117. " uniform float fogDensity;",
  11118. " #else",
  11119. " uniform float fogNear;",
  11120. " uniform float fogFar;",
  11121. " #endif",
  11122. "#endif"
  11123. ].join("\n"),
  11124. fog_fragment: [
  11125. "#ifdef USE_FOG",
  11126. " #ifdef USE_LOGDEPTHBUF_EXT",
  11127. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11128. " #else",
  11129. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11130. " #endif",
  11131. " #ifdef FOG_EXP2",
  11132. " const float LOG2 = 1.442695;",
  11133. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  11134. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  11135. " #else",
  11136. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  11137. " #endif",
  11138. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  11139. "#endif"
  11140. ].join("\n"),
  11141. // ENVIRONMENT MAP
  11142. envmap_pars_fragment: [
  11143. "#ifdef USE_ENVMAP",
  11144. " uniform float reflectivity;",
  11145. " uniform samplerCube envMap;",
  11146. " uniform float flipEnvMap;",
  11147. " uniform int combine;",
  11148. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  11149. " uniform bool useRefract;",
  11150. " uniform float refractionRatio;",
  11151. " #else",
  11152. " varying vec3 vReflect;",
  11153. " #endif",
  11154. "#endif"
  11155. ].join("\n"),
  11156. envmap_fragment: [
  11157. "#ifdef USE_ENVMAP",
  11158. " vec3 reflectVec;",
  11159. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  11160. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11161. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  11162. // "Transforming Normal Vectors with the Inverse Transformation"
  11163. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  11164. " if ( useRefract ) {",
  11165. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  11166. " } else { ",
  11167. " reflectVec = reflect( cameraToVertex, worldNormal );",
  11168. " }",
  11169. " #else",
  11170. " reflectVec = vReflect;",
  11171. " #endif",
  11172. " #ifdef DOUBLE_SIDED",
  11173. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  11174. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  11175. " #else",
  11176. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  11177. " #endif",
  11178. " #ifdef GAMMA_INPUT",
  11179. " cubeColor.xyz *= cubeColor.xyz;",
  11180. " #endif",
  11181. " if ( combine == 1 ) {",
  11182. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  11183. " } else if ( combine == 2 ) {",
  11184. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  11185. " } else {",
  11186. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  11187. " }",
  11188. "#endif"
  11189. ].join("\n"),
  11190. envmap_pars_vertex: [
  11191. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  11192. " varying vec3 vReflect;",
  11193. " uniform float refractionRatio;",
  11194. " uniform bool useRefract;",
  11195. "#endif"
  11196. ].join("\n"),
  11197. worldpos_vertex : [
  11198. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  11199. " #ifdef USE_SKINNING",
  11200. " vec4 worldPosition = modelMatrix * skinned;",
  11201. " #endif",
  11202. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  11203. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  11204. " #endif",
  11205. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  11206. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11207. " #endif",
  11208. "#endif"
  11209. ].join("\n"),
  11210. envmap_vertex : [
  11211. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  11212. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  11213. " worldNormal = normalize( worldNormal );",
  11214. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  11215. " if ( useRefract ) {",
  11216. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  11217. " } else {",
  11218. " vReflect = reflect( cameraToVertex, worldNormal );",
  11219. " }",
  11220. "#endif"
  11221. ].join("\n"),
  11222. // COLOR MAP (particles)
  11223. map_particle_pars_fragment: [
  11224. "#ifdef USE_MAP",
  11225. " uniform sampler2D map;",
  11226. "#endif"
  11227. ].join("\n"),
  11228. map_particle_fragment: [
  11229. "#ifdef USE_MAP",
  11230. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  11231. "#endif"
  11232. ].join("\n"),
  11233. // COLOR MAP (triangles)
  11234. map_pars_vertex: [
  11235. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  11236. " varying vec2 vUv;",
  11237. " uniform vec4 offsetRepeat;",
  11238. "#endif"
  11239. ].join("\n"),
  11240. map_pars_fragment: [
  11241. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  11242. " varying vec2 vUv;",
  11243. "#endif",
  11244. "#ifdef USE_MAP",
  11245. " uniform sampler2D map;",
  11246. "#endif"
  11247. ].join("\n"),
  11248. map_vertex: [
  11249. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  11250. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  11251. "#endif"
  11252. ].join("\n"),
  11253. map_fragment: [
  11254. "#ifdef USE_MAP",
  11255. " vec4 texelColor = texture2D( map, vUv );",
  11256. " #ifdef GAMMA_INPUT",
  11257. " texelColor.xyz *= texelColor.xyz;",
  11258. " #endif",
  11259. " gl_FragColor = gl_FragColor * texelColor;",
  11260. "#endif"
  11261. ].join("\n"),
  11262. // LIGHT MAP
  11263. lightmap_pars_fragment: [
  11264. "#ifdef USE_LIGHTMAP",
  11265. " varying vec2 vUv2;",
  11266. " uniform sampler2D lightMap;",
  11267. "#endif"
  11268. ].join("\n"),
  11269. lightmap_pars_vertex: [
  11270. "#ifdef USE_LIGHTMAP",
  11271. " varying vec2 vUv2;",
  11272. "#endif"
  11273. ].join("\n"),
  11274. lightmap_fragment: [
  11275. "#ifdef USE_LIGHTMAP",
  11276. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  11277. "#endif"
  11278. ].join("\n"),
  11279. lightmap_vertex: [
  11280. "#ifdef USE_LIGHTMAP",
  11281. " vUv2 = uv2;",
  11282. "#endif"
  11283. ].join("\n"),
  11284. // BUMP MAP
  11285. bumpmap_pars_fragment: [
  11286. "#ifdef USE_BUMPMAP",
  11287. " uniform sampler2D bumpMap;",
  11288. " uniform float bumpScale;",
  11289. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  11290. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  11291. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11292. " vec2 dHdxy_fwd() {",
  11293. " vec2 dSTdx = dFdx( vUv );",
  11294. " vec2 dSTdy = dFdy( vUv );",
  11295. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  11296. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  11297. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  11298. " return vec2( dBx, dBy );",
  11299. " }",
  11300. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  11301. " vec3 vSigmaX = dFdx( surf_pos );",
  11302. " vec3 vSigmaY = dFdy( surf_pos );",
  11303. " vec3 vN = surf_norm;", // normalized
  11304. " vec3 R1 = cross( vSigmaY, vN );",
  11305. " vec3 R2 = cross( vN, vSigmaX );",
  11306. " float fDet = dot( vSigmaX, R1 );",
  11307. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  11308. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  11309. " }",
  11310. "#endif"
  11311. ].join("\n"),
  11312. // NORMAL MAP
  11313. normalmap_pars_fragment: [
  11314. "#ifdef USE_NORMALMAP",
  11315. " uniform sampler2D normalMap;",
  11316. " uniform vec2 normalScale;",
  11317. // Per-Pixel Tangent Space Normal Mapping
  11318. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  11319. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  11320. " vec3 q0 = dFdx( eye_pos.xyz );",
  11321. " vec3 q1 = dFdy( eye_pos.xyz );",
  11322. " vec2 st0 = dFdx( vUv.st );",
  11323. " vec2 st1 = dFdy( vUv.st );",
  11324. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  11325. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  11326. " vec3 N = normalize( surf_norm );",
  11327. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  11328. " mapN.xy = normalScale * mapN.xy;",
  11329. " mat3 tsn = mat3( S, T, N );",
  11330. " return normalize( tsn * mapN );",
  11331. " }",
  11332. "#endif"
  11333. ].join("\n"),
  11334. // SPECULAR MAP
  11335. specularmap_pars_fragment: [
  11336. "#ifdef USE_SPECULARMAP",
  11337. " uniform sampler2D specularMap;",
  11338. "#endif"
  11339. ].join("\n"),
  11340. specularmap_fragment: [
  11341. "float specularStrength;",
  11342. "#ifdef USE_SPECULARMAP",
  11343. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  11344. " specularStrength = texelSpecular.r;",
  11345. "#else",
  11346. " specularStrength = 1.0;",
  11347. "#endif"
  11348. ].join("\n"),
  11349. // LIGHTS LAMBERT
  11350. lights_lambert_pars_vertex: [
  11351. "uniform vec3 ambient;",
  11352. "uniform vec3 diffuse;",
  11353. "uniform vec3 emissive;",
  11354. "uniform vec3 ambientLightColor;",
  11355. "#if MAX_DIR_LIGHTS > 0",
  11356. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11357. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11358. "#endif",
  11359. "#if MAX_HEMI_LIGHTS > 0",
  11360. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11361. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11362. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11363. "#endif",
  11364. "#if MAX_POINT_LIGHTS > 0",
  11365. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11366. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11367. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11368. "#endif",
  11369. "#if MAX_SPOT_LIGHTS > 0",
  11370. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11371. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11372. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11373. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11374. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11375. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11376. "#endif",
  11377. "#ifdef WRAP_AROUND",
  11378. " uniform vec3 wrapRGB;",
  11379. "#endif"
  11380. ].join("\n"),
  11381. lights_lambert_vertex: [
  11382. "vLightFront = vec3( 0.0 );",
  11383. "#ifdef DOUBLE_SIDED",
  11384. " vLightBack = vec3( 0.0 );",
  11385. "#endif",
  11386. "transformedNormal = normalize( transformedNormal );",
  11387. "#if MAX_DIR_LIGHTS > 0",
  11388. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  11389. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11390. " vec3 dirVector = normalize( lDirection.xyz );",
  11391. " float dotProduct = dot( transformedNormal, dirVector );",
  11392. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  11393. " #ifdef DOUBLE_SIDED",
  11394. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  11395. " #ifdef WRAP_AROUND",
  11396. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  11397. " #endif",
  11398. " #endif",
  11399. " #ifdef WRAP_AROUND",
  11400. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  11401. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  11402. " #ifdef DOUBLE_SIDED",
  11403. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  11404. " #endif",
  11405. " #endif",
  11406. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  11407. " #ifdef DOUBLE_SIDED",
  11408. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  11409. " #endif",
  11410. "}",
  11411. "#endif",
  11412. "#if MAX_POINT_LIGHTS > 0",
  11413. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11414. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11415. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11416. " float lDistance = 1.0;",
  11417. " if ( pointLightDistance[ i ] > 0.0 )",
  11418. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11419. " lVector = normalize( lVector );",
  11420. " float dotProduct = dot( transformedNormal, lVector );",
  11421. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  11422. " #ifdef DOUBLE_SIDED",
  11423. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  11424. " #ifdef WRAP_AROUND",
  11425. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  11426. " #endif",
  11427. " #endif",
  11428. " #ifdef WRAP_AROUND",
  11429. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  11430. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  11431. " #ifdef DOUBLE_SIDED",
  11432. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  11433. " #endif",
  11434. " #endif",
  11435. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  11436. " #ifdef DOUBLE_SIDED",
  11437. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  11438. " #endif",
  11439. " }",
  11440. "#endif",
  11441. "#if MAX_SPOT_LIGHTS > 0",
  11442. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11443. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11444. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11445. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  11446. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11447. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11448. " float lDistance = 1.0;",
  11449. " if ( spotLightDistance[ i ] > 0.0 )",
  11450. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  11451. " lVector = normalize( lVector );",
  11452. " float dotProduct = dot( transformedNormal, lVector );",
  11453. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  11454. " #ifdef DOUBLE_SIDED",
  11455. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  11456. " #ifdef WRAP_AROUND",
  11457. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  11458. " #endif",
  11459. " #endif",
  11460. " #ifdef WRAP_AROUND",
  11461. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  11462. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  11463. " #ifdef DOUBLE_SIDED",
  11464. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  11465. " #endif",
  11466. " #endif",
  11467. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  11468. " #ifdef DOUBLE_SIDED",
  11469. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  11470. " #endif",
  11471. " }",
  11472. " }",
  11473. "#endif",
  11474. "#if MAX_HEMI_LIGHTS > 0",
  11475. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11476. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11477. " vec3 lVector = normalize( lDirection.xyz );",
  11478. " float dotProduct = dot( transformedNormal, lVector );",
  11479. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11480. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  11481. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11482. " #ifdef DOUBLE_SIDED",
  11483. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  11484. " #endif",
  11485. " }",
  11486. "#endif",
  11487. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  11488. "#ifdef DOUBLE_SIDED",
  11489. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  11490. "#endif"
  11491. ].join("\n"),
  11492. // LIGHTS PHONG
  11493. lights_phong_pars_vertex: [
  11494. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  11495. " varying vec3 vWorldPosition;",
  11496. "#endif"
  11497. ].join("\n"),
  11498. lights_phong_vertex: [
  11499. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  11500. " vWorldPosition = worldPosition.xyz;",
  11501. "#endif"
  11502. ].join("\n"),
  11503. lights_phong_pars_fragment: [
  11504. "uniform vec3 ambientLightColor;",
  11505. "#if MAX_DIR_LIGHTS > 0",
  11506. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11507. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11508. "#endif",
  11509. "#if MAX_HEMI_LIGHTS > 0",
  11510. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11511. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11512. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11513. "#endif",
  11514. "#if MAX_POINT_LIGHTS > 0",
  11515. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11516. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11517. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11518. "#endif",
  11519. "#if MAX_SPOT_LIGHTS > 0",
  11520. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11521. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11522. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11523. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11524. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11525. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11526. "#endif",
  11527. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  11528. " varying vec3 vWorldPosition;",
  11529. "#endif",
  11530. "#ifdef WRAP_AROUND",
  11531. " uniform vec3 wrapRGB;",
  11532. "#endif",
  11533. "varying vec3 vViewPosition;",
  11534. "varying vec3 vNormal;"
  11535. ].join("\n"),
  11536. lights_phong_fragment: [
  11537. "vec3 normal = normalize( vNormal );",
  11538. "vec3 viewPosition = normalize( vViewPosition );",
  11539. "#ifdef DOUBLE_SIDED",
  11540. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  11541. "#endif",
  11542. "#ifdef USE_NORMALMAP",
  11543. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  11544. "#elif defined( USE_BUMPMAP )",
  11545. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  11546. "#endif",
  11547. "#if MAX_POINT_LIGHTS > 0",
  11548. " vec3 pointDiffuse = vec3( 0.0 );",
  11549. " vec3 pointSpecular = vec3( 0.0 );",
  11550. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11551. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11552. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  11553. " float lDistance = 1.0;",
  11554. " if ( pointLightDistance[ i ] > 0.0 )",
  11555. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11556. " lVector = normalize( lVector );",
  11557. // diffuse
  11558. " float dotProduct = dot( normal, lVector );",
  11559. " #ifdef WRAP_AROUND",
  11560. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  11561. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11562. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11563. " #else",
  11564. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  11565. " #endif",
  11566. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  11567. // specular
  11568. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  11569. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11570. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11571. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11572. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11573. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  11574. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  11575. " }",
  11576. "#endif",
  11577. "#if MAX_SPOT_LIGHTS > 0",
  11578. " vec3 spotDiffuse = vec3( 0.0 );",
  11579. " vec3 spotSpecular = vec3( 0.0 );",
  11580. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11581. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11582. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  11583. " float lDistance = 1.0;",
  11584. " if ( spotLightDistance[ i ] > 0.0 )",
  11585. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  11586. " lVector = normalize( lVector );",
  11587. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11588. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11589. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11590. // diffuse
  11591. " float dotProduct = dot( normal, lVector );",
  11592. " #ifdef WRAP_AROUND",
  11593. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  11594. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11595. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11596. " #else",
  11597. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  11598. " #endif",
  11599. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  11600. // specular
  11601. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  11602. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11603. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11604. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11605. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11606. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  11607. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  11608. " }",
  11609. " }",
  11610. "#endif",
  11611. "#if MAX_DIR_LIGHTS > 0",
  11612. " vec3 dirDiffuse = vec3( 0.0 );",
  11613. " vec3 dirSpecular = vec3( 0.0 );" ,
  11614. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  11615. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11616. " vec3 dirVector = normalize( lDirection.xyz );",
  11617. // diffuse
  11618. " float dotProduct = dot( normal, dirVector );",
  11619. " #ifdef WRAP_AROUND",
  11620. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  11621. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11622. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  11623. " #else",
  11624. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  11625. " #endif",
  11626. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  11627. // specular
  11628. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11629. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11630. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11631. /*
  11632. // fresnel term from skin shader
  11633. " const float F0 = 0.128;",
  11634. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  11635. " float exponential = pow( base, 5.0 );",
  11636. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  11637. */
  11638. /*
  11639. // fresnel term from fresnel shader
  11640. " const float mFresnelBias = 0.08;",
  11641. " const float mFresnelScale = 0.3;",
  11642. " const float mFresnelPower = 5.0;",
  11643. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  11644. */
  11645. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11646. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11647. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  11648. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  11649. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11650. " }",
  11651. "#endif",
  11652. "#if MAX_HEMI_LIGHTS > 0",
  11653. " vec3 hemiDiffuse = vec3( 0.0 );",
  11654. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11655. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11656. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11657. " vec3 lVector = normalize( lDirection.xyz );",
  11658. // diffuse
  11659. " float dotProduct = dot( normal, lVector );",
  11660. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11661. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11662. " hemiDiffuse += diffuse * hemiColor;",
  11663. // specular (sky light)
  11664. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11665. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11666. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11667. // specular (ground light)
  11668. " vec3 lVectorGround = -lVector;",
  11669. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11670. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11671. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11672. " float dotProductGround = dot( normal, lVectorGround );",
  11673. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11674. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11675. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  11676. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  11677. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11678. " }",
  11679. "#endif",
  11680. "vec3 totalDiffuse = vec3( 0.0 );",
  11681. "vec3 totalSpecular = vec3( 0.0 );",
  11682. "#if MAX_DIR_LIGHTS > 0",
  11683. " totalDiffuse += dirDiffuse;",
  11684. " totalSpecular += dirSpecular;",
  11685. "#endif",
  11686. "#if MAX_HEMI_LIGHTS > 0",
  11687. " totalDiffuse += hemiDiffuse;",
  11688. " totalSpecular += hemiSpecular;",
  11689. "#endif",
  11690. "#if MAX_POINT_LIGHTS > 0",
  11691. " totalDiffuse += pointDiffuse;",
  11692. " totalSpecular += pointSpecular;",
  11693. "#endif",
  11694. "#if MAX_SPOT_LIGHTS > 0",
  11695. " totalDiffuse += spotDiffuse;",
  11696. " totalSpecular += spotSpecular;",
  11697. "#endif",
  11698. "#ifdef METAL",
  11699. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11700. "#else",
  11701. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11702. "#endif"
  11703. ].join("\n"),
  11704. // VERTEX COLORS
  11705. color_pars_fragment: [
  11706. "#ifdef USE_COLOR",
  11707. " varying vec3 vColor;",
  11708. "#endif"
  11709. ].join("\n"),
  11710. color_fragment: [
  11711. "#ifdef USE_COLOR",
  11712. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  11713. "#endif"
  11714. ].join("\n"),
  11715. color_pars_vertex: [
  11716. "#ifdef USE_COLOR",
  11717. " varying vec3 vColor;",
  11718. "#endif"
  11719. ].join("\n"),
  11720. color_vertex: [
  11721. "#ifdef USE_COLOR",
  11722. " #ifdef GAMMA_INPUT",
  11723. " vColor = color * color;",
  11724. " #else",
  11725. " vColor = color;",
  11726. " #endif",
  11727. "#endif"
  11728. ].join("\n"),
  11729. // SKINNING
  11730. skinning_pars_vertex: [
  11731. "#ifdef USE_SKINNING",
  11732. " #ifdef BONE_TEXTURE",
  11733. " uniform sampler2D boneTexture;",
  11734. " uniform int boneTextureWidth;",
  11735. " uniform int boneTextureHeight;",
  11736. " mat4 getBoneMatrix( const in float i ) {",
  11737. " float j = i * 4.0;",
  11738. " float x = mod( j, float( boneTextureWidth ) );",
  11739. " float y = floor( j / float( boneTextureWidth ) );",
  11740. " float dx = 1.0 / float( boneTextureWidth );",
  11741. " float dy = 1.0 / float( boneTextureHeight );",
  11742. " y = dy * ( y + 0.5 );",
  11743. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  11744. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  11745. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  11746. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  11747. " mat4 bone = mat4( v1, v2, v3, v4 );",
  11748. " return bone;",
  11749. " }",
  11750. " #else",
  11751. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  11752. " mat4 getBoneMatrix( const in float i ) {",
  11753. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  11754. " return bone;",
  11755. " }",
  11756. " #endif",
  11757. "#endif"
  11758. ].join("\n"),
  11759. skinbase_vertex: [
  11760. "#ifdef USE_SKINNING",
  11761. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  11762. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  11763. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  11764. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  11765. "#endif"
  11766. ].join("\n"),
  11767. skinning_vertex: [
  11768. "#ifdef USE_SKINNING",
  11769. " #ifdef USE_MORPHTARGETS",
  11770. " vec4 skinVertex = vec4( morphed, 1.0 );",
  11771. " #else",
  11772. " vec4 skinVertex = vec4( position, 1.0 );",
  11773. " #endif",
  11774. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11775. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11776. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11777. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11778. "#endif"
  11779. ].join("\n"),
  11780. // MORPHING
  11781. morphtarget_pars_vertex: [
  11782. "#ifdef USE_MORPHTARGETS",
  11783. " #ifndef USE_MORPHNORMALS",
  11784. " uniform float morphTargetInfluences[ 8 ];",
  11785. " #else",
  11786. " uniform float morphTargetInfluences[ 4 ];",
  11787. " #endif",
  11788. "#endif"
  11789. ].join("\n"),
  11790. morphtarget_vertex: [
  11791. "#ifdef USE_MORPHTARGETS",
  11792. " vec3 morphed = vec3( 0.0 );",
  11793. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  11794. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  11795. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  11796. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  11797. " #ifndef USE_MORPHNORMALS",
  11798. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  11799. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  11800. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  11801. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  11802. " #endif",
  11803. " morphed += position;",
  11804. "#endif"
  11805. ].join("\n"),
  11806. default_vertex : [
  11807. "vec4 mvPosition;",
  11808. "#ifdef USE_SKINNING",
  11809. " mvPosition = modelViewMatrix * skinned;",
  11810. "#endif",
  11811. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  11812. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  11813. "#endif",
  11814. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  11815. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11816. "#endif",
  11817. "gl_Position = projectionMatrix * mvPosition;"
  11818. ].join("\n"),
  11819. morphnormal_vertex: [
  11820. "#ifdef USE_MORPHNORMALS",
  11821. " vec3 morphedNormal = vec3( 0.0 );",
  11822. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  11823. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  11824. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  11825. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  11826. " morphedNormal += normal;",
  11827. "#endif"
  11828. ].join("\n"),
  11829. skinnormal_vertex: [
  11830. "#ifdef USE_SKINNING",
  11831. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  11832. " skinMatrix += skinWeight.y * boneMatY;",
  11833. " skinMatrix += skinWeight.z * boneMatZ;",
  11834. " skinMatrix += skinWeight.w * boneMatW;",
  11835. " #ifdef USE_MORPHNORMALS",
  11836. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  11837. " #else",
  11838. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  11839. " #endif",
  11840. "#endif"
  11841. ].join("\n"),
  11842. defaultnormal_vertex: [
  11843. "vec3 objectNormal;",
  11844. "#ifdef USE_SKINNING",
  11845. " objectNormal = skinnedNormal.xyz;",
  11846. "#endif",
  11847. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  11848. " objectNormal = morphedNormal;",
  11849. "#endif",
  11850. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  11851. " objectNormal = normal;",
  11852. "#endif",
  11853. "#ifdef FLIP_SIDED",
  11854. " objectNormal = -objectNormal;",
  11855. "#endif",
  11856. "vec3 transformedNormal = normalMatrix * objectNormal;"
  11857. ].join("\n"),
  11858. // SHADOW MAP
  11859. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  11860. // http://spidergl.org/example.php?id=6
  11861. // http://fabiensanglard.net/shadowmapping
  11862. shadowmap_pars_fragment: [
  11863. "#ifdef USE_SHADOWMAP",
  11864. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  11865. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  11866. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  11867. " uniform float shadowBias[ MAX_SHADOWS ];",
  11868. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11869. " float unpackDepth( const in vec4 rgba_depth ) {",
  11870. " 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 );",
  11871. " float depth = dot( rgba_depth, bit_shift );",
  11872. " return depth;",
  11873. " }",
  11874. "#endif"
  11875. ].join("\n"),
  11876. shadowmap_fragment: [
  11877. "#ifdef USE_SHADOWMAP",
  11878. " #ifdef SHADOWMAP_DEBUG",
  11879. " vec3 frustumColors[3];",
  11880. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  11881. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  11882. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  11883. " #endif",
  11884. " #ifdef SHADOWMAP_CASCADE",
  11885. " int inFrustumCount = 0;",
  11886. " #endif",
  11887. " float fDepth;",
  11888. " vec3 shadowColor = vec3( 1.0 );",
  11889. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11890. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  11891. // "if ( something && something )" breaks ATI OpenGL shader compiler
  11892. // "if ( all( something, something ) )" using this instead
  11893. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  11894. " bool inFrustum = all( inFrustumVec );",
  11895. // don't shadow pixels outside of light frustum
  11896. // use just first frustum (for cascades)
  11897. // don't shadow pixels behind far plane of light frustum
  11898. " #ifdef SHADOWMAP_CASCADE",
  11899. " inFrustumCount += int( inFrustum );",
  11900. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  11901. " #else",
  11902. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  11903. " #endif",
  11904. " bool frustumTest = all( frustumTestVec );",
  11905. " if ( frustumTest ) {",
  11906. " shadowCoord.z += shadowBias[ i ];",
  11907. " #if defined( SHADOWMAP_TYPE_PCF )",
  11908. // Percentage-close filtering
  11909. // (9 pixel kernel)
  11910. // http://fabiensanglard.net/shadowmappingPCF/
  11911. " float shadow = 0.0;",
  11912. /*
  11913. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11914. // must enroll loop manually
  11915. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11916. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11917. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11918. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11919. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11920. " float fDepth = unpackDepth( rgbaDepth );",
  11921. " if ( fDepth < shadowCoord.z )",
  11922. " shadow += 1.0;",
  11923. " }",
  11924. " shadow /= 9.0;",
  11925. */
  11926. " const float shadowDelta = 1.0 / 9.0;",
  11927. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11928. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11929. " float dx0 = -1.25 * xPixelOffset;",
  11930. " float dy0 = -1.25 * yPixelOffset;",
  11931. " float dx1 = 1.25 * xPixelOffset;",
  11932. " float dy1 = 1.25 * yPixelOffset;",
  11933. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11934. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11935. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11936. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11937. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11938. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11939. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11940. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11941. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11942. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11943. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11944. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11945. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11946. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11947. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11948. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11949. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11950. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11951. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11952. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11953. // Percentage-close filtering
  11954. // (9 pixel kernel)
  11955. // http://fabiensanglard.net/shadowmappingPCF/
  11956. " float shadow = 0.0;",
  11957. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11958. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11959. " float dx0 = -1.0 * xPixelOffset;",
  11960. " float dy0 = -1.0 * yPixelOffset;",
  11961. " float dx1 = 1.0 * xPixelOffset;",
  11962. " float dy1 = 1.0 * yPixelOffset;",
  11963. " mat3 shadowKernel;",
  11964. " mat3 depthKernel;",
  11965. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11966. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11967. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11968. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11969. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11970. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11971. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11972. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11973. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11974. " vec3 shadowZ = vec3( shadowCoord.z );",
  11975. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11976. " shadowKernel[0] *= vec3(0.25);",
  11977. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11978. " shadowKernel[1] *= vec3(0.25);",
  11979. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11980. " shadowKernel[2] *= vec3(0.25);",
  11981. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11982. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11983. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11984. " vec4 shadowValues;",
  11985. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11986. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11987. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11988. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11989. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  11990. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11991. " #else",
  11992. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11993. " float fDepth = unpackDepth( rgbaDepth );",
  11994. " if ( fDepth < shadowCoord.z )",
  11995. // spot with multiple shadows is darker
  11996. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11997. // spot with multiple shadows has the same color as single shadow spot
  11998. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11999. " #endif",
  12000. " }",
  12001. " #ifdef SHADOWMAP_DEBUG",
  12002. " #ifdef SHADOWMAP_CASCADE",
  12003. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  12004. " #else",
  12005. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  12006. " #endif",
  12007. " #endif",
  12008. " }",
  12009. " #ifdef GAMMA_OUTPUT",
  12010. " shadowColor *= shadowColor;",
  12011. " #endif",
  12012. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  12013. "#endif"
  12014. ].join("\n"),
  12015. shadowmap_pars_vertex: [
  12016. "#ifdef USE_SHADOWMAP",
  12017. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  12018. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  12019. "#endif"
  12020. ].join("\n"),
  12021. shadowmap_vertex: [
  12022. "#ifdef USE_SHADOWMAP",
  12023. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12024. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12025. " }",
  12026. "#endif"
  12027. ].join("\n"),
  12028. // ALPHATEST
  12029. alphatest_fragment: [
  12030. "#ifdef ALPHATEST",
  12031. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  12032. "#endif"
  12033. ].join("\n"),
  12034. // LINEAR SPACE
  12035. linear_to_gamma_fragment: [
  12036. "#ifdef GAMMA_OUTPUT",
  12037. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  12038. "#endif"
  12039. ].join("\n"),
  12040. // LOGARITHMIC DEPTH BUFFER
  12041. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  12042. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  12043. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  12044. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  12045. // the camera is near the surface.
  12046. logdepthbuf_pars_vertex: [
  12047. "#ifdef USE_LOGDEPTHBUF",
  12048. " #ifdef USE_LOGDEPTHBUF_EXT",
  12049. " varying float vFragDepth;",
  12050. " #endif",
  12051. " uniform float logDepthBufFC;",
  12052. "#endif",
  12053. ].join('\n'),
  12054. logdepthbuf_vertex: [
  12055. "#ifdef USE_LOGDEPTHBUF",
  12056. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  12057. " #ifdef USE_LOGDEPTHBUF_EXT",
  12058. " vFragDepth = 1.0 + gl_Position.w;",
  12059. "#else",
  12060. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  12061. " #endif",
  12062. "#endif"
  12063. ].join("\n"),
  12064. logdepthbuf_pars_fragment: [
  12065. "#ifdef USE_LOGDEPTHBUF",
  12066. " uniform float logDepthBufFC;",
  12067. " #ifdef USE_LOGDEPTHBUF_EXT",
  12068. " #extension GL_EXT_frag_depth : enable",
  12069. " varying float vFragDepth;",
  12070. " #endif",
  12071. "#endif"
  12072. ].join('\n'),
  12073. logdepthbuf_fragment: [
  12074. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  12075. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  12076. "#endif"
  12077. ].join("\n")
  12078. };
  12079. /**
  12080. * Uniform Utilities
  12081. */
  12082. THREE.UniformsUtils = {
  12083. merge: function ( uniforms ) {
  12084. var u, p, tmp, merged = {};
  12085. for ( u = 0; u < uniforms.length; u ++ ) {
  12086. tmp = this.clone( uniforms[ u ] );
  12087. for ( p in tmp ) {
  12088. merged[ p ] = tmp[ p ];
  12089. }
  12090. }
  12091. return merged;
  12092. },
  12093. clone: function ( uniforms_src ) {
  12094. var u, p, parameter, parameter_src, uniforms_dst = {};
  12095. for ( u in uniforms_src ) {
  12096. uniforms_dst[ u ] = {};
  12097. for ( p in uniforms_src[ u ] ) {
  12098. parameter_src = uniforms_src[ u ][ p ];
  12099. if ( parameter_src instanceof THREE.Color ||
  12100. parameter_src instanceof THREE.Vector2 ||
  12101. parameter_src instanceof THREE.Vector3 ||
  12102. parameter_src instanceof THREE.Vector4 ||
  12103. parameter_src instanceof THREE.Matrix4 ||
  12104. parameter_src instanceof THREE.Texture ) {
  12105. uniforms_dst[ u ][ p ] = parameter_src.clone();
  12106. } else if ( parameter_src instanceof Array ) {
  12107. uniforms_dst[ u ][ p ] = parameter_src.slice();
  12108. } else {
  12109. uniforms_dst[ u ][ p ] = parameter_src;
  12110. }
  12111. }
  12112. }
  12113. return uniforms_dst;
  12114. }
  12115. };
  12116. /**
  12117. * Uniforms library for shared webgl shaders
  12118. */
  12119. THREE.UniformsLib = {
  12120. common: {
  12121. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  12122. "opacity" : { type: "f", value: 1.0 },
  12123. "map" : { type: "t", value: null },
  12124. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  12125. "lightMap" : { type: "t", value: null },
  12126. "specularMap" : { type: "t", value: null },
  12127. "envMap" : { type: "t", value: null },
  12128. "flipEnvMap" : { type: "f", value: -1 },
  12129. "useRefract" : { type: "i", value: 0 },
  12130. "reflectivity" : { type: "f", value: 1.0 },
  12131. "refractionRatio" : { type: "f", value: 0.98 },
  12132. "combine" : { type: "i", value: 0 },
  12133. "morphTargetInfluences" : { type: "f", value: 0 }
  12134. },
  12135. bump: {
  12136. "bumpMap" : { type: "t", value: null },
  12137. "bumpScale" : { type: "f", value: 1 }
  12138. },
  12139. normalmap: {
  12140. "normalMap" : { type: "t", value: null },
  12141. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  12142. },
  12143. fog : {
  12144. "fogDensity" : { type: "f", value: 0.00025 },
  12145. "fogNear" : { type: "f", value: 1 },
  12146. "fogFar" : { type: "f", value: 2000 },
  12147. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  12148. },
  12149. lights: {
  12150. "ambientLightColor" : { type: "fv", value: [] },
  12151. "directionalLightDirection" : { type: "fv", value: [] },
  12152. "directionalLightColor" : { type: "fv", value: [] },
  12153. "hemisphereLightDirection" : { type: "fv", value: [] },
  12154. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  12155. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  12156. "pointLightColor" : { type: "fv", value: [] },
  12157. "pointLightPosition" : { type: "fv", value: [] },
  12158. "pointLightDistance" : { type: "fv1", value: [] },
  12159. "spotLightColor" : { type: "fv", value: [] },
  12160. "spotLightPosition" : { type: "fv", value: [] },
  12161. "spotLightDirection" : { type: "fv", value: [] },
  12162. "spotLightDistance" : { type: "fv1", value: [] },
  12163. "spotLightAngleCos" : { type: "fv1", value: [] },
  12164. "spotLightExponent" : { type: "fv1", value: [] }
  12165. },
  12166. particle: {
  12167. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  12168. "opacity" : { type: "f", value: 1.0 },
  12169. "size" : { type: "f", value: 1.0 },
  12170. "scale" : { type: "f", value: 1.0 },
  12171. "map" : { type: "t", value: null },
  12172. "fogDensity" : { type: "f", value: 0.00025 },
  12173. "fogNear" : { type: "f", value: 1 },
  12174. "fogFar" : { type: "f", value: 2000 },
  12175. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  12176. },
  12177. shadowmap: {
  12178. "shadowMap": { type: "tv", value: [] },
  12179. "shadowMapSize": { type: "v2v", value: [] },
  12180. "shadowBias" : { type: "fv1", value: [] },
  12181. "shadowDarkness": { type: "fv1", value: [] },
  12182. "shadowMatrix" : { type: "m4v", value: [] }
  12183. }
  12184. };
  12185. /**
  12186. * Webgl Shader Library for three.js
  12187. *
  12188. * @author alteredq / http://alteredqualia.com/
  12189. * @author mrdoob / http://mrdoob.com/
  12190. * @author mikael emtinger / http://gomo.se/
  12191. */
  12192. THREE.ShaderLib = {
  12193. 'basic': {
  12194. uniforms: THREE.UniformsUtils.merge( [
  12195. THREE.UniformsLib[ "common" ],
  12196. THREE.UniformsLib[ "fog" ],
  12197. THREE.UniformsLib[ "shadowmap" ]
  12198. ] ),
  12199. vertexShader: [
  12200. THREE.ShaderChunk[ "map_pars_vertex" ],
  12201. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  12202. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12203. THREE.ShaderChunk[ "color_pars_vertex" ],
  12204. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12205. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12206. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12207. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12208. "void main() {",
  12209. THREE.ShaderChunk[ "map_vertex" ],
  12210. THREE.ShaderChunk[ "lightmap_vertex" ],
  12211. THREE.ShaderChunk[ "color_vertex" ],
  12212. THREE.ShaderChunk[ "skinbase_vertex" ],
  12213. " #ifdef USE_ENVMAP",
  12214. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12215. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12216. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12217. " #endif",
  12218. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12219. THREE.ShaderChunk[ "skinning_vertex" ],
  12220. THREE.ShaderChunk[ "default_vertex" ],
  12221. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12222. THREE.ShaderChunk[ "worldpos_vertex" ],
  12223. THREE.ShaderChunk[ "envmap_vertex" ],
  12224. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12225. "}"
  12226. ].join("\n"),
  12227. fragmentShader: [
  12228. "uniform vec3 diffuse;",
  12229. "uniform float opacity;",
  12230. THREE.ShaderChunk[ "color_pars_fragment" ],
  12231. THREE.ShaderChunk[ "map_pars_fragment" ],
  12232. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  12233. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12234. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12235. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12236. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12237. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12238. "void main() {",
  12239. " gl_FragColor = vec4( diffuse, opacity );",
  12240. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12241. THREE.ShaderChunk[ "map_fragment" ],
  12242. THREE.ShaderChunk[ "alphatest_fragment" ],
  12243. THREE.ShaderChunk[ "specularmap_fragment" ],
  12244. THREE.ShaderChunk[ "lightmap_fragment" ],
  12245. THREE.ShaderChunk[ "color_fragment" ],
  12246. THREE.ShaderChunk[ "envmap_fragment" ],
  12247. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12248. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12249. THREE.ShaderChunk[ "fog_fragment" ],
  12250. "}"
  12251. ].join("\n")
  12252. },
  12253. 'lambert': {
  12254. uniforms: THREE.UniformsUtils.merge( [
  12255. THREE.UniformsLib[ "common" ],
  12256. THREE.UniformsLib[ "fog" ],
  12257. THREE.UniformsLib[ "lights" ],
  12258. THREE.UniformsLib[ "shadowmap" ],
  12259. {
  12260. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  12261. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  12262. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  12263. }
  12264. ] ),
  12265. vertexShader: [
  12266. "#define LAMBERT",
  12267. "varying vec3 vLightFront;",
  12268. "#ifdef DOUBLE_SIDED",
  12269. " varying vec3 vLightBack;",
  12270. "#endif",
  12271. THREE.ShaderChunk[ "map_pars_vertex" ],
  12272. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  12273. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12274. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  12275. THREE.ShaderChunk[ "color_pars_vertex" ],
  12276. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12277. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12278. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12279. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12280. "void main() {",
  12281. THREE.ShaderChunk[ "map_vertex" ],
  12282. THREE.ShaderChunk[ "lightmap_vertex" ],
  12283. THREE.ShaderChunk[ "color_vertex" ],
  12284. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12285. THREE.ShaderChunk[ "skinbase_vertex" ],
  12286. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12287. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12288. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12289. THREE.ShaderChunk[ "skinning_vertex" ],
  12290. THREE.ShaderChunk[ "default_vertex" ],
  12291. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12292. THREE.ShaderChunk[ "worldpos_vertex" ],
  12293. THREE.ShaderChunk[ "envmap_vertex" ],
  12294. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  12295. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12296. "}"
  12297. ].join("\n"),
  12298. fragmentShader: [
  12299. "uniform float opacity;",
  12300. "varying vec3 vLightFront;",
  12301. "#ifdef DOUBLE_SIDED",
  12302. " varying vec3 vLightBack;",
  12303. "#endif",
  12304. THREE.ShaderChunk[ "color_pars_fragment" ],
  12305. THREE.ShaderChunk[ "map_pars_fragment" ],
  12306. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  12307. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12308. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12309. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12310. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12311. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12312. "void main() {",
  12313. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  12314. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12315. THREE.ShaderChunk[ "map_fragment" ],
  12316. THREE.ShaderChunk[ "alphatest_fragment" ],
  12317. THREE.ShaderChunk[ "specularmap_fragment" ],
  12318. " #ifdef DOUBLE_SIDED",
  12319. //"float isFront = float( gl_FrontFacing );",
  12320. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  12321. " if ( gl_FrontFacing )",
  12322. " gl_FragColor.xyz *= vLightFront;",
  12323. " else",
  12324. " gl_FragColor.xyz *= vLightBack;",
  12325. " #else",
  12326. " gl_FragColor.xyz *= vLightFront;",
  12327. " #endif",
  12328. THREE.ShaderChunk[ "lightmap_fragment" ],
  12329. THREE.ShaderChunk[ "color_fragment" ],
  12330. THREE.ShaderChunk[ "envmap_fragment" ],
  12331. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12332. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12333. THREE.ShaderChunk[ "fog_fragment" ],
  12334. "}"
  12335. ].join("\n")
  12336. },
  12337. 'phong': {
  12338. uniforms: THREE.UniformsUtils.merge( [
  12339. THREE.UniformsLib[ "common" ],
  12340. THREE.UniformsLib[ "bump" ],
  12341. THREE.UniformsLib[ "normalmap" ],
  12342. THREE.UniformsLib[ "fog" ],
  12343. THREE.UniformsLib[ "lights" ],
  12344. THREE.UniformsLib[ "shadowmap" ],
  12345. {
  12346. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  12347. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  12348. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  12349. "shininess": { type: "f", value: 30 },
  12350. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  12351. }
  12352. ] ),
  12353. vertexShader: [
  12354. "#define PHONG",
  12355. "varying vec3 vViewPosition;",
  12356. "varying vec3 vNormal;",
  12357. THREE.ShaderChunk[ "map_pars_vertex" ],
  12358. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  12359. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12360. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  12361. THREE.ShaderChunk[ "color_pars_vertex" ],
  12362. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12363. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12364. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12365. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12366. "void main() {",
  12367. THREE.ShaderChunk[ "map_vertex" ],
  12368. THREE.ShaderChunk[ "lightmap_vertex" ],
  12369. THREE.ShaderChunk[ "color_vertex" ],
  12370. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12371. THREE.ShaderChunk[ "skinbase_vertex" ],
  12372. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12373. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12374. " vNormal = normalize( transformedNormal );",
  12375. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12376. THREE.ShaderChunk[ "skinning_vertex" ],
  12377. THREE.ShaderChunk[ "default_vertex" ],
  12378. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12379. " vViewPosition = -mvPosition.xyz;",
  12380. THREE.ShaderChunk[ "worldpos_vertex" ],
  12381. THREE.ShaderChunk[ "envmap_vertex" ],
  12382. THREE.ShaderChunk[ "lights_phong_vertex" ],
  12383. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12384. "}"
  12385. ].join("\n"),
  12386. fragmentShader: [
  12387. "uniform vec3 diffuse;",
  12388. "uniform float opacity;",
  12389. "uniform vec3 ambient;",
  12390. "uniform vec3 emissive;",
  12391. "uniform vec3 specular;",
  12392. "uniform float shininess;",
  12393. THREE.ShaderChunk[ "color_pars_fragment" ],
  12394. THREE.ShaderChunk[ "map_pars_fragment" ],
  12395. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  12396. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12397. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12398. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  12399. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12400. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  12401. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  12402. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12403. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12404. "void main() {",
  12405. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  12406. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12407. THREE.ShaderChunk[ "map_fragment" ],
  12408. THREE.ShaderChunk[ "alphatest_fragment" ],
  12409. THREE.ShaderChunk[ "specularmap_fragment" ],
  12410. THREE.ShaderChunk[ "lights_phong_fragment" ],
  12411. THREE.ShaderChunk[ "lightmap_fragment" ],
  12412. THREE.ShaderChunk[ "color_fragment" ],
  12413. THREE.ShaderChunk[ "envmap_fragment" ],
  12414. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12415. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12416. THREE.ShaderChunk[ "fog_fragment" ],
  12417. "}"
  12418. ].join("\n")
  12419. },
  12420. 'particle_basic': {
  12421. uniforms: THREE.UniformsUtils.merge( [
  12422. THREE.UniformsLib[ "particle" ],
  12423. THREE.UniformsLib[ "shadowmap" ]
  12424. ] ),
  12425. vertexShader: [
  12426. "uniform float size;",
  12427. "uniform float scale;",
  12428. THREE.ShaderChunk[ "color_pars_vertex" ],
  12429. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12430. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12431. "void main() {",
  12432. THREE.ShaderChunk[ "color_vertex" ],
  12433. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  12434. " #ifdef USE_SIZEATTENUATION",
  12435. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  12436. " #else",
  12437. " gl_PointSize = size;",
  12438. " #endif",
  12439. " gl_Position = projectionMatrix * mvPosition;",
  12440. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12441. THREE.ShaderChunk[ "worldpos_vertex" ],
  12442. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12443. "}"
  12444. ].join("\n"),
  12445. fragmentShader: [
  12446. "uniform vec3 psColor;",
  12447. "uniform float opacity;",
  12448. THREE.ShaderChunk[ "color_pars_fragment" ],
  12449. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  12450. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12451. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12452. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12453. "void main() {",
  12454. " gl_FragColor = vec4( psColor, opacity );",
  12455. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12456. THREE.ShaderChunk[ "map_particle_fragment" ],
  12457. THREE.ShaderChunk[ "alphatest_fragment" ],
  12458. THREE.ShaderChunk[ "color_fragment" ],
  12459. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12460. THREE.ShaderChunk[ "fog_fragment" ],
  12461. "}"
  12462. ].join("\n")
  12463. },
  12464. 'dashed': {
  12465. uniforms: THREE.UniformsUtils.merge( [
  12466. THREE.UniformsLib[ "common" ],
  12467. THREE.UniformsLib[ "fog" ],
  12468. {
  12469. "scale": { type: "f", value: 1 },
  12470. "dashSize": { type: "f", value: 1 },
  12471. "totalSize": { type: "f", value: 2 }
  12472. }
  12473. ] ),
  12474. vertexShader: [
  12475. "uniform float scale;",
  12476. "attribute float lineDistance;",
  12477. "varying float vLineDistance;",
  12478. THREE.ShaderChunk[ "color_pars_vertex" ],
  12479. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12480. "void main() {",
  12481. THREE.ShaderChunk[ "color_vertex" ],
  12482. " vLineDistance = scale * lineDistance;",
  12483. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  12484. " gl_Position = projectionMatrix * mvPosition;",
  12485. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12486. "}"
  12487. ].join("\n"),
  12488. fragmentShader: [
  12489. "uniform vec3 diffuse;",
  12490. "uniform float opacity;",
  12491. "uniform float dashSize;",
  12492. "uniform float totalSize;",
  12493. "varying float vLineDistance;",
  12494. THREE.ShaderChunk[ "color_pars_fragment" ],
  12495. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12496. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12497. "void main() {",
  12498. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  12499. " discard;",
  12500. " }",
  12501. " gl_FragColor = vec4( diffuse, opacity );",
  12502. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12503. THREE.ShaderChunk[ "color_fragment" ],
  12504. THREE.ShaderChunk[ "fog_fragment" ],
  12505. "}"
  12506. ].join("\n")
  12507. },
  12508. 'depth': {
  12509. uniforms: {
  12510. "mNear": { type: "f", value: 1.0 },
  12511. "mFar" : { type: "f", value: 2000.0 },
  12512. "opacity" : { type: "f", value: 1.0 }
  12513. },
  12514. vertexShader: [
  12515. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12516. "void main() {",
  12517. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12518. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12519. "}"
  12520. ].join("\n"),
  12521. fragmentShader: [
  12522. "uniform float mNear;",
  12523. "uniform float mFar;",
  12524. "uniform float opacity;",
  12525. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12526. "void main() {",
  12527. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12528. " #ifdef USE_LOGDEPTHBUF_EXT",
  12529. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  12530. " #else",
  12531. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  12532. " #endif",
  12533. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  12534. " gl_FragColor = vec4( vec3( color ), opacity );",
  12535. "}"
  12536. ].join("\n")
  12537. },
  12538. 'normal': {
  12539. uniforms: {
  12540. "opacity" : { type: "f", value: 1.0 }
  12541. },
  12542. vertexShader: [
  12543. "varying vec3 vNormal;",
  12544. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12545. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12546. "void main() {",
  12547. " vNormal = normalize( normalMatrix * normal );",
  12548. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12549. THREE.ShaderChunk[ "default_vertex" ],
  12550. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12551. "}"
  12552. ].join("\n"),
  12553. fragmentShader: [
  12554. "uniform float opacity;",
  12555. "varying vec3 vNormal;",
  12556. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12557. "void main() {",
  12558. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  12559. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12560. "}"
  12561. ].join("\n")
  12562. },
  12563. /* -------------------------------------------------------------------------
  12564. // Normal map shader
  12565. // - Blinn-Phong
  12566. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  12567. // - point and directional lights (use with "lights: true" material option)
  12568. ------------------------------------------------------------------------- */
  12569. 'normalmap' : {
  12570. uniforms: THREE.UniformsUtils.merge( [
  12571. THREE.UniformsLib[ "fog" ],
  12572. THREE.UniformsLib[ "lights" ],
  12573. THREE.UniformsLib[ "shadowmap" ],
  12574. {
  12575. "enableAO" : { type: "i", value: 0 },
  12576. "enableDiffuse" : { type: "i", value: 0 },
  12577. "enableSpecular" : { type: "i", value: 0 },
  12578. "enableReflection": { type: "i", value: 0 },
  12579. "enableDisplacement": { type: "i", value: 0 },
  12580. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  12581. "tDiffuse" : { type: "t", value: null },
  12582. "tCube" : { type: "t", value: null },
  12583. "tNormal" : { type: "t", value: null },
  12584. "tSpecular" : { type: "t", value: null },
  12585. "tAO" : { type: "t", value: null },
  12586. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12587. "uDisplacementBias": { type: "f", value: 0.0 },
  12588. "uDisplacementScale": { type: "f", value: 1.0 },
  12589. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  12590. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  12591. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  12592. "shininess": { type: "f", value: 30 },
  12593. "opacity": { type: "f", value: 1 },
  12594. "useRefract": { type: "i", value: 0 },
  12595. "refractionRatio": { type: "f", value: 0.98 },
  12596. "reflectivity": { type: "f", value: 0.5 },
  12597. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  12598. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12599. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  12600. }
  12601. ] ),
  12602. fragmentShader: [
  12603. "uniform vec3 ambient;",
  12604. "uniform vec3 diffuse;",
  12605. "uniform vec3 specular;",
  12606. "uniform float shininess;",
  12607. "uniform float opacity;",
  12608. "uniform bool enableDiffuse;",
  12609. "uniform bool enableSpecular;",
  12610. "uniform bool enableAO;",
  12611. "uniform bool enableReflection;",
  12612. "uniform sampler2D tDiffuse;",
  12613. "uniform sampler2D tNormal;",
  12614. "uniform sampler2D tSpecular;",
  12615. "uniform sampler2D tAO;",
  12616. "uniform samplerCube tCube;",
  12617. "uniform vec2 uNormalScale;",
  12618. "uniform bool useRefract;",
  12619. "uniform float refractionRatio;",
  12620. "uniform float reflectivity;",
  12621. "varying vec3 vTangent;",
  12622. "varying vec3 vBinormal;",
  12623. "varying vec3 vNormal;",
  12624. "varying vec2 vUv;",
  12625. "uniform vec3 ambientLightColor;",
  12626. "#if MAX_DIR_LIGHTS > 0",
  12627. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  12628. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  12629. "#endif",
  12630. "#if MAX_HEMI_LIGHTS > 0",
  12631. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  12632. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  12633. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  12634. "#endif",
  12635. "#if MAX_POINT_LIGHTS > 0",
  12636. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  12637. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  12638. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  12639. "#endif",
  12640. "#if MAX_SPOT_LIGHTS > 0",
  12641. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  12642. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  12643. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  12644. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  12645. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  12646. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  12647. "#endif",
  12648. "#ifdef WRAP_AROUND",
  12649. " uniform vec3 wrapRGB;",
  12650. "#endif",
  12651. "varying vec3 vWorldPosition;",
  12652. "varying vec3 vViewPosition;",
  12653. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12654. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12655. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12656. "void main() {",
  12657. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12658. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  12659. " vec3 specularTex = vec3( 1.0 );",
  12660. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  12661. " normalTex.xy *= uNormalScale;",
  12662. " normalTex = normalize( normalTex );",
  12663. " if( enableDiffuse ) {",
  12664. " #ifdef GAMMA_INPUT",
  12665. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  12666. " texelColor.xyz *= texelColor.xyz;",
  12667. " gl_FragColor = gl_FragColor * texelColor;",
  12668. " #else",
  12669. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  12670. " #endif",
  12671. " }",
  12672. " if( enableAO ) {",
  12673. " #ifdef GAMMA_INPUT",
  12674. " vec4 aoColor = texture2D( tAO, vUv );",
  12675. " aoColor.xyz *= aoColor.xyz;",
  12676. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  12677. " #else",
  12678. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  12679. " #endif",
  12680. " }",
  12681. " if( enableSpecular )",
  12682. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  12683. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  12684. " vec3 finalNormal = tsb * normalTex;",
  12685. " #ifdef FLIP_SIDED",
  12686. " finalNormal = -finalNormal;",
  12687. " #endif",
  12688. " vec3 normal = normalize( finalNormal );",
  12689. " vec3 viewPosition = normalize( vViewPosition );",
  12690. // point lights
  12691. " #if MAX_POINT_LIGHTS > 0",
  12692. " vec3 pointDiffuse = vec3( 0.0 );",
  12693. " vec3 pointSpecular = vec3( 0.0 );",
  12694. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  12695. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  12696. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  12697. " float pointDistance = 1.0;",
  12698. " if ( pointLightDistance[ i ] > 0.0 )",
  12699. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  12700. " pointVector = normalize( pointVector );",
  12701. // diffuse
  12702. " #ifdef WRAP_AROUND",
  12703. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  12704. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  12705. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  12706. " #else",
  12707. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  12708. " #endif",
  12709. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  12710. // specular
  12711. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  12712. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  12713. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  12714. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12715. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12716. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  12717. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  12718. " }",
  12719. " #endif",
  12720. // spot lights
  12721. " #if MAX_SPOT_LIGHTS > 0",
  12722. " vec3 spotDiffuse = vec3( 0.0 );",
  12723. " vec3 spotSpecular = vec3( 0.0 );",
  12724. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  12725. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  12726. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  12727. " float spotDistance = 1.0;",
  12728. " if ( spotLightDistance[ i ] > 0.0 )",
  12729. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  12730. " spotVector = normalize( spotVector );",
  12731. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  12732. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  12733. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  12734. // diffuse
  12735. " #ifdef WRAP_AROUND",
  12736. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  12737. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  12738. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  12739. " #else",
  12740. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  12741. " #endif",
  12742. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  12743. // specular
  12744. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  12745. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  12746. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  12747. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12748. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12749. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  12750. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  12751. " }",
  12752. " }",
  12753. " #endif",
  12754. // directional lights
  12755. " #if MAX_DIR_LIGHTS > 0",
  12756. " vec3 dirDiffuse = vec3( 0.0 );",
  12757. " vec3 dirSpecular = vec3( 0.0 );",
  12758. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  12759. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  12760. " vec3 dirVector = normalize( lDirection.xyz );",
  12761. // diffuse
  12762. " #ifdef WRAP_AROUND",
  12763. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  12764. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  12765. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  12766. " #else",
  12767. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  12768. " #endif",
  12769. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  12770. // specular
  12771. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  12772. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  12773. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  12774. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12775. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12776. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  12777. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  12778. " }",
  12779. " #endif",
  12780. // hemisphere lights
  12781. " #if MAX_HEMI_LIGHTS > 0",
  12782. " vec3 hemiDiffuse = vec3( 0.0 );",
  12783. " vec3 hemiSpecular = vec3( 0.0 );" ,
  12784. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  12785. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  12786. " vec3 lVector = normalize( lDirection.xyz );",
  12787. // diffuse
  12788. " float dotProduct = dot( normal, lVector );",
  12789. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  12790. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  12791. " hemiDiffuse += diffuse * hemiColor;",
  12792. // specular (sky light)
  12793. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  12794. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  12795. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  12796. // specular (ground light)
  12797. " vec3 lVectorGround = -lVector;",
  12798. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  12799. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  12800. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  12801. " float dotProductGround = dot( normal, lVectorGround );",
  12802. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12803. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12804. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  12805. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  12806. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  12807. " }",
  12808. " #endif",
  12809. // all lights contribution summation
  12810. " vec3 totalDiffuse = vec3( 0.0 );",
  12811. " vec3 totalSpecular = vec3( 0.0 );",
  12812. " #if MAX_DIR_LIGHTS > 0",
  12813. " totalDiffuse += dirDiffuse;",
  12814. " totalSpecular += dirSpecular;",
  12815. " #endif",
  12816. " #if MAX_HEMI_LIGHTS > 0",
  12817. " totalDiffuse += hemiDiffuse;",
  12818. " totalSpecular += hemiSpecular;",
  12819. " #endif",
  12820. " #if MAX_POINT_LIGHTS > 0",
  12821. " totalDiffuse += pointDiffuse;",
  12822. " totalSpecular += pointSpecular;",
  12823. " #endif",
  12824. " #if MAX_SPOT_LIGHTS > 0",
  12825. " totalDiffuse += spotDiffuse;",
  12826. " totalSpecular += spotSpecular;",
  12827. " #endif",
  12828. " #ifdef METAL",
  12829. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  12830. " #else",
  12831. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  12832. " #endif",
  12833. " if ( enableReflection ) {",
  12834. " vec3 vReflect;",
  12835. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  12836. " if ( useRefract ) {",
  12837. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  12838. " } else {",
  12839. " vReflect = reflect( cameraToVertex, normal );",
  12840. " }",
  12841. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  12842. " #ifdef GAMMA_INPUT",
  12843. " cubeColor.xyz *= cubeColor.xyz;",
  12844. " #endif",
  12845. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  12846. " }",
  12847. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12848. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12849. THREE.ShaderChunk[ "fog_fragment" ],
  12850. "}"
  12851. ].join("\n"),
  12852. vertexShader: [
  12853. "attribute vec4 tangent;",
  12854. "uniform vec2 uOffset;",
  12855. "uniform vec2 uRepeat;",
  12856. "uniform bool enableDisplacement;",
  12857. "#ifdef VERTEX_TEXTURES",
  12858. " uniform sampler2D tDisplacement;",
  12859. " uniform float uDisplacementScale;",
  12860. " uniform float uDisplacementBias;",
  12861. "#endif",
  12862. "varying vec3 vTangent;",
  12863. "varying vec3 vBinormal;",
  12864. "varying vec3 vNormal;",
  12865. "varying vec2 vUv;",
  12866. "varying vec3 vWorldPosition;",
  12867. "varying vec3 vViewPosition;",
  12868. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12869. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12870. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12871. "void main() {",
  12872. THREE.ShaderChunk[ "skinbase_vertex" ],
  12873. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12874. // normal, tangent and binormal vectors
  12875. " #ifdef USE_SKINNING",
  12876. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  12877. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  12878. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  12879. " #else",
  12880. " vNormal = normalize( normalMatrix * normal );",
  12881. " vTangent = normalize( normalMatrix * tangent.xyz );",
  12882. " #endif",
  12883. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  12884. " vUv = uv * uRepeat + uOffset;",
  12885. // displacement mapping
  12886. " vec3 displacedPosition;",
  12887. " #ifdef VERTEX_TEXTURES",
  12888. " if ( enableDisplacement ) {",
  12889. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  12890. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  12891. " displacedPosition = position + normalize( normal ) * df;",
  12892. " } else {",
  12893. " #ifdef USE_SKINNING",
  12894. " vec4 skinVertex = vec4( position, 1.0 );",
  12895. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12896. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12897. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12898. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12899. " displacedPosition = skinned.xyz;",
  12900. " #else",
  12901. " displacedPosition = position;",
  12902. " #endif",
  12903. " }",
  12904. " #else",
  12905. " #ifdef USE_SKINNING",
  12906. " vec4 skinVertex = vec4( position, 1.0 );",
  12907. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12908. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12909. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12910. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12911. " displacedPosition = skinned.xyz;",
  12912. " #else",
  12913. " displacedPosition = position;",
  12914. " #endif",
  12915. " #endif",
  12916. //
  12917. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  12918. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  12919. " gl_Position = projectionMatrix * mvPosition;",
  12920. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12921. //
  12922. " vWorldPosition = worldPosition.xyz;",
  12923. " vViewPosition = -mvPosition.xyz;",
  12924. // shadows
  12925. " #ifdef USE_SHADOWMAP",
  12926. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12927. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12928. " }",
  12929. " #endif",
  12930. "}"
  12931. ].join("\n")
  12932. },
  12933. /* -------------------------------------------------------------------------
  12934. // Cube map shader
  12935. ------------------------------------------------------------------------- */
  12936. 'cube': {
  12937. uniforms: { "tCube": { type: "t", value: null },
  12938. "tFlip": { type: "f", value: -1 } },
  12939. vertexShader: [
  12940. "varying vec3 vWorldPosition;",
  12941. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12942. "void main() {",
  12943. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  12944. " vWorldPosition = worldPosition.xyz;",
  12945. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12946. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12947. "}"
  12948. ].join("\n"),
  12949. fragmentShader: [
  12950. "uniform samplerCube tCube;",
  12951. "uniform float tFlip;",
  12952. "varying vec3 vWorldPosition;",
  12953. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12954. "void main() {",
  12955. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12956. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12957. "}"
  12958. ].join("\n")
  12959. },
  12960. // Depth encoding into RGBA texture
  12961. // based on SpiderGL shadow map example
  12962. // http://spidergl.org/example.php?id=6
  12963. // originally from
  12964. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12965. // see also here:
  12966. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12967. 'depthRGBA': {
  12968. uniforms: {},
  12969. vertexShader: [
  12970. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12971. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12972. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12973. "void main() {",
  12974. THREE.ShaderChunk[ "skinbase_vertex" ],
  12975. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12976. THREE.ShaderChunk[ "skinning_vertex" ],
  12977. THREE.ShaderChunk[ "default_vertex" ],
  12978. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12979. "}"
  12980. ].join("\n"),
  12981. fragmentShader: [
  12982. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12983. "vec4 pack_depth( const in float depth ) {",
  12984. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12985. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12986. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  12987. " res -= res.xxyz * bit_mask;",
  12988. " return res;",
  12989. "}",
  12990. "void main() {",
  12991. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12992. " #ifdef USE_LOGDEPTHBUF_EXT",
  12993. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  12994. " #else",
  12995. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12996. " #endif",
  12997. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12998. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12999. //"gl_FragData[ 0 ] = pack_depth( z );",
  13000. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  13001. "}"
  13002. ].join("\n")
  13003. }
  13004. };
  13005. /**
  13006. * @author supereggbert / http://www.paulbrunt.co.uk/
  13007. * @author mrdoob / http://mrdoob.com/
  13008. * @author alteredq / http://alteredqualia.com/
  13009. * @author szimek / https://github.com/szimek/
  13010. */
  13011. THREE.WebGLRenderer = function ( parameters ) {
  13012. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  13013. parameters = parameters || {};
  13014. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  13015. _context = parameters.context !== undefined ? parameters.context : null,
  13016. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  13017. _buffers = {},
  13018. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13019. _depth = parameters.depth !== undefined ? parameters.depth : true,
  13020. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  13021. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  13022. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  13023. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  13024. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  13025. _clearColor = new THREE.Color( 0x000000 ),
  13026. _clearAlpha = 0;
  13027. // public properties
  13028. this.domElement = _canvas;
  13029. this.context = null;
  13030. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  13031. ? parameters.devicePixelRatio
  13032. : self.devicePixelRatio !== undefined
  13033. ? self.devicePixelRatio
  13034. : 1;
  13035. // clearing
  13036. this.autoClear = true;
  13037. this.autoClearColor = true;
  13038. this.autoClearDepth = true;
  13039. this.autoClearStencil = true;
  13040. // scene graph
  13041. this.sortObjects = true;
  13042. this.autoUpdateObjects = true;
  13043. // physically based shading
  13044. this.gammaInput = false;
  13045. this.gammaOutput = false;
  13046. // shadow map
  13047. this.shadowMapEnabled = false;
  13048. this.shadowMapAutoUpdate = true;
  13049. this.shadowMapType = THREE.PCFShadowMap;
  13050. this.shadowMapCullFace = THREE.CullFaceFront;
  13051. this.shadowMapDebug = false;
  13052. this.shadowMapCascade = false;
  13053. // morphs
  13054. this.maxMorphTargets = 8;
  13055. this.maxMorphNormals = 4;
  13056. // flags
  13057. this.autoScaleCubemaps = true;
  13058. // custom render plugins
  13059. this.renderPluginsPre = [];
  13060. this.renderPluginsPost = [];
  13061. // info
  13062. this.info = {
  13063. memory: {
  13064. programs: 0,
  13065. geometries: 0,
  13066. textures: 0
  13067. },
  13068. render: {
  13069. calls: 0,
  13070. vertices: 0,
  13071. faces: 0,
  13072. points: 0
  13073. }
  13074. };
  13075. // internal properties
  13076. var _this = this,
  13077. _programs = [],
  13078. // internal state cache
  13079. _currentProgram = null,
  13080. _currentFramebuffer = null,
  13081. _currentMaterialId = -1,
  13082. _currentGeometryGroupHash = null,
  13083. _currentCamera = null,
  13084. _usedTextureUnits = 0,
  13085. // GL state cache
  13086. _oldDoubleSided = -1,
  13087. _oldFlipSided = -1,
  13088. _oldBlending = -1,
  13089. _oldBlendEquation = -1,
  13090. _oldBlendSrc = -1,
  13091. _oldBlendDst = -1,
  13092. _oldDepthTest = -1,
  13093. _oldDepthWrite = -1,
  13094. _oldPolygonOffset = null,
  13095. _oldPolygonOffsetFactor = null,
  13096. _oldPolygonOffsetUnits = null,
  13097. _oldLineWidth = null,
  13098. _viewportX = 0,
  13099. _viewportY = 0,
  13100. _viewportWidth = _canvas.width,
  13101. _viewportHeight = _canvas.height,
  13102. _currentWidth = 0,
  13103. _currentHeight = 0,
  13104. _newAttributes = new Uint8Array( 16 ),
  13105. _enabledAttributes = new Uint8Array( 16 ),
  13106. // frustum
  13107. _frustum = new THREE.Frustum(),
  13108. // camera matrices cache
  13109. _projScreenMatrix = new THREE.Matrix4(),
  13110. _projScreenMatrixPS = new THREE.Matrix4(),
  13111. _vector3 = new THREE.Vector3(),
  13112. // light arrays cache
  13113. _direction = new THREE.Vector3(),
  13114. _lightsNeedUpdate = true,
  13115. _lights = {
  13116. ambient: [ 0, 0, 0 ],
  13117. directional: { length: 0, colors: new Array(), positions: new Array() },
  13118. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  13119. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  13120. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  13121. };
  13122. // initialize
  13123. var _gl;
  13124. var _glExtensionTextureFloat;
  13125. var _glExtensionTextureFloatLinear;
  13126. var _glExtensionStandardDerivatives;
  13127. var _glExtensionTextureFilterAnisotropic;
  13128. var _glExtensionCompressedTextureS3TC;
  13129. var _glExtensionElementIndexUint;
  13130. var _glExtensionFragDepth;
  13131. initGL();
  13132. setDefaultGLState();
  13133. this.context = _gl;
  13134. // GPU capabilities
  13135. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  13136. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  13137. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  13138. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  13139. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  13140. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  13141. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  13142. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  13143. //
  13144. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  13145. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  13146. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  13147. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  13148. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  13149. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  13150. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  13151. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  13152. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  13153. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  13154. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  13155. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  13156. // clamp precision to maximum available
  13157. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  13158. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  13159. if ( _precision === "highp" && ! highpAvailable ) {
  13160. if ( mediumpAvailable ) {
  13161. _precision = "mediump";
  13162. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  13163. } else {
  13164. _precision = "lowp";
  13165. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  13166. }
  13167. }
  13168. if ( _precision === "mediump" && ! mediumpAvailable ) {
  13169. _precision = "lowp";
  13170. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  13171. }
  13172. // API
  13173. this.getContext = function () {
  13174. return _gl;
  13175. };
  13176. this.supportsVertexTextures = function () {
  13177. return _supportsVertexTextures;
  13178. };
  13179. this.supportsFloatTextures = function () {
  13180. return _glExtensionTextureFloat;
  13181. };
  13182. this.supportsStandardDerivatives = function () {
  13183. return _glExtensionStandardDerivatives;
  13184. };
  13185. this.supportsCompressedTextureS3TC = function () {
  13186. return _glExtensionCompressedTextureS3TC;
  13187. };
  13188. this.getMaxAnisotropy = function () {
  13189. return _maxAnisotropy;
  13190. };
  13191. this.getPrecision = function () {
  13192. return _precision;
  13193. };
  13194. this.setSize = function ( width, height, updateStyle ) {
  13195. _canvas.width = width * this.devicePixelRatio;
  13196. _canvas.height = height * this.devicePixelRatio;
  13197. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  13198. _canvas.style.width = width + 'px';
  13199. _canvas.style.height = height + 'px';
  13200. }
  13201. this.setViewport( 0, 0, width, height );
  13202. };
  13203. this.setViewport = function ( x, y, width, height ) {
  13204. _viewportX = x * this.devicePixelRatio;
  13205. _viewportY = y * this.devicePixelRatio;
  13206. _viewportWidth = width * this.devicePixelRatio;
  13207. _viewportHeight = height * this.devicePixelRatio;
  13208. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  13209. };
  13210. this.setScissor = function ( x, y, width, height ) {
  13211. _gl.scissor(
  13212. x * this.devicePixelRatio,
  13213. y * this.devicePixelRatio,
  13214. width * this.devicePixelRatio,
  13215. height * this.devicePixelRatio
  13216. );
  13217. };
  13218. this.enableScissorTest = function ( enable ) {
  13219. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  13220. };
  13221. // Clearing
  13222. this.setClearColor = function ( color, alpha ) {
  13223. _clearColor.set( color );
  13224. _clearAlpha = alpha !== undefined ? alpha : 1;
  13225. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13226. };
  13227. this.setClearColorHex = function ( hex, alpha ) {
  13228. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  13229. this.setClearColor( hex, alpha );
  13230. };
  13231. this.getClearColor = function () {
  13232. return _clearColor;
  13233. };
  13234. this.getClearAlpha = function () {
  13235. return _clearAlpha;
  13236. };
  13237. this.clear = function ( color, depth, stencil ) {
  13238. var bits = 0;
  13239. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  13240. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  13241. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  13242. _gl.clear( bits );
  13243. };
  13244. this.clearColor = function () {
  13245. _gl.clear( _gl.COLOR_BUFFER_BIT );
  13246. };
  13247. this.clearDepth = function () {
  13248. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  13249. };
  13250. this.clearStencil = function () {
  13251. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  13252. };
  13253. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  13254. this.setRenderTarget( renderTarget );
  13255. this.clear( color, depth, stencil );
  13256. };
  13257. // Plugins
  13258. this.addPostPlugin = function ( plugin ) {
  13259. plugin.init( this );
  13260. this.renderPluginsPost.push( plugin );
  13261. };
  13262. this.addPrePlugin = function ( plugin ) {
  13263. plugin.init( this );
  13264. this.renderPluginsPre.push( plugin );
  13265. };
  13266. // Rendering
  13267. this.updateShadowMap = function ( scene, camera ) {
  13268. _currentProgram = null;
  13269. _oldBlending = -1;
  13270. _oldDepthTest = -1;
  13271. _oldDepthWrite = -1;
  13272. _currentGeometryGroupHash = -1;
  13273. _currentMaterialId = -1;
  13274. _lightsNeedUpdate = true;
  13275. _oldDoubleSided = -1;
  13276. _oldFlipSided = -1;
  13277. this.shadowMapPlugin.update( scene, camera );
  13278. };
  13279. // Internal functions
  13280. // Buffer allocation
  13281. function createParticleBuffers ( geometry ) {
  13282. geometry.__webglVertexBuffer = _gl.createBuffer();
  13283. geometry.__webglColorBuffer = _gl.createBuffer();
  13284. _this.info.memory.geometries ++;
  13285. };
  13286. function createLineBuffers ( geometry ) {
  13287. geometry.__webglVertexBuffer = _gl.createBuffer();
  13288. geometry.__webglColorBuffer = _gl.createBuffer();
  13289. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  13290. _this.info.memory.geometries ++;
  13291. };
  13292. function createMeshBuffers ( geometryGroup ) {
  13293. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  13294. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  13295. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  13296. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  13297. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  13298. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  13299. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  13300. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  13301. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  13302. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  13303. var m, ml;
  13304. if ( geometryGroup.numMorphTargets ) {
  13305. geometryGroup.__webglMorphTargetsBuffers = [];
  13306. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13307. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  13308. }
  13309. }
  13310. if ( geometryGroup.numMorphNormals ) {
  13311. geometryGroup.__webglMorphNormalsBuffers = [];
  13312. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13313. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  13314. }
  13315. }
  13316. _this.info.memory.geometries ++;
  13317. };
  13318. // Events
  13319. var onGeometryDispose = function ( event ) {
  13320. var geometry = event.target;
  13321. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13322. deallocateGeometry( geometry );
  13323. };
  13324. var onTextureDispose = function ( event ) {
  13325. var texture = event.target;
  13326. texture.removeEventListener( 'dispose', onTextureDispose );
  13327. deallocateTexture( texture );
  13328. _this.info.memory.textures --;
  13329. };
  13330. var onRenderTargetDispose = function ( event ) {
  13331. var renderTarget = event.target;
  13332. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13333. deallocateRenderTarget( renderTarget );
  13334. _this.info.memory.textures --;
  13335. };
  13336. var onMaterialDispose = function ( event ) {
  13337. var material = event.target;
  13338. material.removeEventListener( 'dispose', onMaterialDispose );
  13339. deallocateMaterial( material );
  13340. };
  13341. // Buffer deallocation
  13342. var deleteBuffers = function ( geometry ) {
  13343. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  13344. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  13345. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  13346. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  13347. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  13348. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  13349. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  13350. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  13351. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  13352. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  13353. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  13354. // custom attributes
  13355. if ( geometry.__webglCustomAttributesList !== undefined ) {
  13356. for ( var id in geometry.__webglCustomAttributesList ) {
  13357. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  13358. }
  13359. }
  13360. _this.info.memory.geometries --;
  13361. };
  13362. var deallocateGeometry = function ( geometry ) {
  13363. geometry.__webglInit = undefined;
  13364. if ( geometry instanceof THREE.BufferGeometry ) {
  13365. var attributes = geometry.attributes;
  13366. for ( var key in attributes ) {
  13367. if ( attributes[ key ].buffer !== undefined ) {
  13368. _gl.deleteBuffer( attributes[ key ].buffer );
  13369. }
  13370. }
  13371. _this.info.memory.geometries --;
  13372. } else {
  13373. if ( geometry.geometryGroups !== undefined ) {
  13374. for ( var g in geometry.geometryGroups ) {
  13375. var geometryGroup = geometry.geometryGroups[ g ];
  13376. if ( geometryGroup.numMorphTargets !== undefined ) {
  13377. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13378. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  13379. }
  13380. }
  13381. if ( geometryGroup.numMorphNormals !== undefined ) {
  13382. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13383. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  13384. }
  13385. }
  13386. deleteBuffers( geometryGroup );
  13387. }
  13388. } else {
  13389. deleteBuffers( geometry );
  13390. }
  13391. }
  13392. };
  13393. var deallocateTexture = function ( texture ) {
  13394. if ( texture.image && texture.image.__webglTextureCube ) {
  13395. // cube texture
  13396. _gl.deleteTexture( texture.image.__webglTextureCube );
  13397. } else {
  13398. // 2D texture
  13399. if ( ! texture.__webglInit ) return;
  13400. texture.__webglInit = false;
  13401. _gl.deleteTexture( texture.__webglTexture );
  13402. }
  13403. };
  13404. var deallocateRenderTarget = function ( renderTarget ) {
  13405. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  13406. _gl.deleteTexture( renderTarget.__webglTexture );
  13407. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13408. for ( var i = 0; i < 6; i ++ ) {
  13409. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  13410. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  13411. }
  13412. } else {
  13413. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  13414. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  13415. }
  13416. };
  13417. var deallocateMaterial = function ( material ) {
  13418. var program = material.program;
  13419. if ( program === undefined ) return;
  13420. material.program = undefined;
  13421. // only deallocate GL program if this was the last use of shared program
  13422. // assumed there is only single copy of any program in the _programs list
  13423. // (that's how it's constructed)
  13424. var i, il, programInfo;
  13425. var deleteProgram = false;
  13426. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  13427. programInfo = _programs[ i ];
  13428. if ( programInfo.program === program ) {
  13429. programInfo.usedTimes --;
  13430. if ( programInfo.usedTimes === 0 ) {
  13431. deleteProgram = true;
  13432. }
  13433. break;
  13434. }
  13435. }
  13436. if ( deleteProgram === true ) {
  13437. // avoid using array.splice, this is costlier than creating new array from scratch
  13438. var newPrograms = [];
  13439. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  13440. programInfo = _programs[ i ];
  13441. if ( programInfo.program !== program ) {
  13442. newPrograms.push( programInfo );
  13443. }
  13444. }
  13445. _programs = newPrograms;
  13446. _gl.deleteProgram( program );
  13447. _this.info.memory.programs --;
  13448. }
  13449. };
  13450. // Buffer initialization
  13451. function initCustomAttributes ( geometry, object ) {
  13452. var nvertices = geometry.vertices.length;
  13453. var material = object.material;
  13454. if ( material.attributes ) {
  13455. if ( geometry.__webglCustomAttributesList === undefined ) {
  13456. geometry.__webglCustomAttributesList = [];
  13457. }
  13458. for ( var a in material.attributes ) {
  13459. var attribute = material.attributes[ a ];
  13460. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13461. attribute.__webglInitialized = true;
  13462. var size = 1; // "f" and "i"
  13463. if ( attribute.type === "v2" ) size = 2;
  13464. else if ( attribute.type === "v3" ) size = 3;
  13465. else if ( attribute.type === "v4" ) size = 4;
  13466. else if ( attribute.type === "c" ) size = 3;
  13467. attribute.size = size;
  13468. attribute.array = new Float32Array( nvertices * size );
  13469. attribute.buffer = _gl.createBuffer();
  13470. attribute.buffer.belongsToAttribute = a;
  13471. attribute.needsUpdate = true;
  13472. }
  13473. geometry.__webglCustomAttributesList.push( attribute );
  13474. }
  13475. }
  13476. };
  13477. function initParticleBuffers ( geometry, object ) {
  13478. var nvertices = geometry.vertices.length;
  13479. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  13480. geometry.__colorArray = new Float32Array( nvertices * 3 );
  13481. geometry.__sortArray = [];
  13482. geometry.__webglParticleCount = nvertices;
  13483. initCustomAttributes ( geometry, object );
  13484. };
  13485. function initLineBuffers ( geometry, object ) {
  13486. var nvertices = geometry.vertices.length;
  13487. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  13488. geometry.__colorArray = new Float32Array( nvertices * 3 );
  13489. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  13490. geometry.__webglLineCount = nvertices;
  13491. initCustomAttributes ( geometry, object );
  13492. };
  13493. function initMeshBuffers ( geometryGroup, object ) {
  13494. var geometry = object.geometry,
  13495. faces3 = geometryGroup.faces3,
  13496. nvertices = faces3.length * 3,
  13497. ntris = faces3.length * 1,
  13498. nlines = faces3.length * 3,
  13499. material = getBufferMaterial( object, geometryGroup ),
  13500. uvType = bufferGuessUVType( material ),
  13501. normalType = bufferGuessNormalType( material ),
  13502. vertexColorType = bufferGuessVertexColorType( material );
  13503. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  13504. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  13505. if ( normalType ) {
  13506. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  13507. }
  13508. if ( geometry.hasTangents ) {
  13509. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  13510. }
  13511. if ( vertexColorType ) {
  13512. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  13513. }
  13514. if ( uvType ) {
  13515. if ( geometry.faceVertexUvs.length > 0 ) {
  13516. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  13517. }
  13518. if ( geometry.faceVertexUvs.length > 1 ) {
  13519. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  13520. }
  13521. }
  13522. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  13523. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  13524. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  13525. }
  13526. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  13527. geometryGroup.__typeArray = UintArray;
  13528. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  13529. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  13530. var m, ml;
  13531. if ( geometryGroup.numMorphTargets ) {
  13532. geometryGroup.__morphTargetsArrays = [];
  13533. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13534. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  13535. }
  13536. }
  13537. if ( geometryGroup.numMorphNormals ) {
  13538. geometryGroup.__morphNormalsArrays = [];
  13539. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13540. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  13541. }
  13542. }
  13543. geometryGroup.__webglFaceCount = ntris * 3;
  13544. geometryGroup.__webglLineCount = nlines * 2;
  13545. // custom attributes
  13546. if ( material.attributes ) {
  13547. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  13548. geometryGroup.__webglCustomAttributesList = [];
  13549. }
  13550. for ( var a in material.attributes ) {
  13551. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  13552. // attribute buffers which are correctly indexed in the setMeshBuffers function
  13553. var originalAttribute = material.attributes[ a ];
  13554. var attribute = {};
  13555. for ( var property in originalAttribute ) {
  13556. attribute[ property ] = originalAttribute[ property ];
  13557. }
  13558. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13559. attribute.__webglInitialized = true;
  13560. var size = 1; // "f" and "i"
  13561. if( attribute.type === "v2" ) size = 2;
  13562. else if( attribute.type === "v3" ) size = 3;
  13563. else if( attribute.type === "v4" ) size = 4;
  13564. else if( attribute.type === "c" ) size = 3;
  13565. attribute.size = size;
  13566. attribute.array = new Float32Array( nvertices * size );
  13567. attribute.buffer = _gl.createBuffer();
  13568. attribute.buffer.belongsToAttribute = a;
  13569. originalAttribute.needsUpdate = true;
  13570. attribute.__original = originalAttribute;
  13571. }
  13572. geometryGroup.__webglCustomAttributesList.push( attribute );
  13573. }
  13574. }
  13575. geometryGroup.__inittedArrays = true;
  13576. };
  13577. function getBufferMaterial( object, geometryGroup ) {
  13578. return object.material instanceof THREE.MeshFaceMaterial
  13579. ? object.material.materials[ geometryGroup.materialIndex ]
  13580. : object.material;
  13581. };
  13582. function materialNeedsSmoothNormals ( material ) {
  13583. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  13584. };
  13585. function bufferGuessNormalType ( material ) {
  13586. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  13587. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  13588. return false;
  13589. }
  13590. if ( materialNeedsSmoothNormals( material ) ) {
  13591. return THREE.SmoothShading;
  13592. } else {
  13593. return THREE.FlatShading;
  13594. }
  13595. };
  13596. function bufferGuessVertexColorType( material ) {
  13597. if ( material.vertexColors ) {
  13598. return material.vertexColors;
  13599. }
  13600. return false;
  13601. };
  13602. function bufferGuessUVType( material ) {
  13603. // material must use some texture to require uvs
  13604. if ( material.map ||
  13605. material.lightMap ||
  13606. material.bumpMap ||
  13607. material.normalMap ||
  13608. material.specularMap ||
  13609. material instanceof THREE.ShaderMaterial ) {
  13610. return true;
  13611. }
  13612. return false;
  13613. };
  13614. //
  13615. function initDirectBuffers( geometry ) {
  13616. for ( var name in geometry.attributes ) {
  13617. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  13618. var attribute = geometry.attributes[ name ];
  13619. attribute.buffer = _gl.createBuffer();
  13620. _gl.bindBuffer( bufferType, attribute.buffer );
  13621. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  13622. }
  13623. }
  13624. // Buffer setting
  13625. function setParticleBuffers ( geometry, hint, object ) {
  13626. var v, c, vertex, offset, index, color,
  13627. vertices = geometry.vertices,
  13628. vl = vertices.length,
  13629. colors = geometry.colors,
  13630. cl = colors.length,
  13631. vertexArray = geometry.__vertexArray,
  13632. colorArray = geometry.__colorArray,
  13633. sortArray = geometry.__sortArray,
  13634. dirtyVertices = geometry.verticesNeedUpdate,
  13635. dirtyElements = geometry.elementsNeedUpdate,
  13636. dirtyColors = geometry.colorsNeedUpdate,
  13637. customAttributes = geometry.__webglCustomAttributesList,
  13638. i, il,
  13639. a, ca, cal, value,
  13640. customAttribute;
  13641. if ( object.sortParticles ) {
  13642. _projScreenMatrixPS.copy( _projScreenMatrix );
  13643. _projScreenMatrixPS.multiply( object.matrixWorld );
  13644. for ( v = 0; v < vl; v ++ ) {
  13645. vertex = vertices[ v ];
  13646. _vector3.copy( vertex );
  13647. _vector3.applyProjection( _projScreenMatrixPS );
  13648. sortArray[ v ] = [ _vector3.z, v ];
  13649. }
  13650. sortArray.sort( numericalSort );
  13651. for ( v = 0; v < vl; v ++ ) {
  13652. vertex = vertices[ sortArray[v][1] ];
  13653. offset = v * 3;
  13654. vertexArray[ offset ] = vertex.x;
  13655. vertexArray[ offset + 1 ] = vertex.y;
  13656. vertexArray[ offset + 2 ] = vertex.z;
  13657. }
  13658. for ( c = 0; c < cl; c ++ ) {
  13659. offset = c * 3;
  13660. color = colors[ sortArray[c][1] ];
  13661. colorArray[ offset ] = color.r;
  13662. colorArray[ offset + 1 ] = color.g;
  13663. colorArray[ offset + 2 ] = color.b;
  13664. }
  13665. if ( customAttributes ) {
  13666. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13667. customAttribute = customAttributes[ i ];
  13668. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  13669. offset = 0;
  13670. cal = customAttribute.value.length;
  13671. if ( customAttribute.size === 1 ) {
  13672. for ( ca = 0; ca < cal; ca ++ ) {
  13673. index = sortArray[ ca ][ 1 ];
  13674. customAttribute.array[ ca ] = customAttribute.value[ index ];
  13675. }
  13676. } else if ( customAttribute.size === 2 ) {
  13677. for ( ca = 0; ca < cal; ca ++ ) {
  13678. index = sortArray[ ca ][ 1 ];
  13679. value = customAttribute.value[ index ];
  13680. customAttribute.array[ offset ] = value.x;
  13681. customAttribute.array[ offset + 1 ] = value.y;
  13682. offset += 2;
  13683. }
  13684. } else if ( customAttribute.size === 3 ) {
  13685. if ( customAttribute.type === "c" ) {
  13686. for ( ca = 0; ca < cal; ca ++ ) {
  13687. index = sortArray[ ca ][ 1 ];
  13688. value = customAttribute.value[ index ];
  13689. customAttribute.array[ offset ] = value.r;
  13690. customAttribute.array[ offset + 1 ] = value.g;
  13691. customAttribute.array[ offset + 2 ] = value.b;
  13692. offset += 3;
  13693. }
  13694. } else {
  13695. for ( ca = 0; ca < cal; ca ++ ) {
  13696. index = sortArray[ ca ][ 1 ];
  13697. value = customAttribute.value[ index ];
  13698. customAttribute.array[ offset ] = value.x;
  13699. customAttribute.array[ offset + 1 ] = value.y;
  13700. customAttribute.array[ offset + 2 ] = value.z;
  13701. offset += 3;
  13702. }
  13703. }
  13704. } else if ( customAttribute.size === 4 ) {
  13705. for ( ca = 0; ca < cal; ca ++ ) {
  13706. index = sortArray[ ca ][ 1 ];
  13707. value = customAttribute.value[ index ];
  13708. customAttribute.array[ offset ] = value.x;
  13709. customAttribute.array[ offset + 1 ] = value.y;
  13710. customAttribute.array[ offset + 2 ] = value.z;
  13711. customAttribute.array[ offset + 3 ] = value.w;
  13712. offset += 4;
  13713. }
  13714. }
  13715. }
  13716. }
  13717. } else {
  13718. if ( dirtyVertices ) {
  13719. for ( v = 0; v < vl; v ++ ) {
  13720. vertex = vertices[ v ];
  13721. offset = v * 3;
  13722. vertexArray[ offset ] = vertex.x;
  13723. vertexArray[ offset + 1 ] = vertex.y;
  13724. vertexArray[ offset + 2 ] = vertex.z;
  13725. }
  13726. }
  13727. if ( dirtyColors ) {
  13728. for ( c = 0; c < cl; c ++ ) {
  13729. color = colors[ c ];
  13730. offset = c * 3;
  13731. colorArray[ offset ] = color.r;
  13732. colorArray[ offset + 1 ] = color.g;
  13733. colorArray[ offset + 2 ] = color.b;
  13734. }
  13735. }
  13736. if ( customAttributes ) {
  13737. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13738. customAttribute = customAttributes[ i ];
  13739. if ( customAttribute.needsUpdate &&
  13740. ( customAttribute.boundTo === undefined ||
  13741. customAttribute.boundTo === "vertices") ) {
  13742. cal = customAttribute.value.length;
  13743. offset = 0;
  13744. if ( customAttribute.size === 1 ) {
  13745. for ( ca = 0; ca < cal; ca ++ ) {
  13746. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13747. }
  13748. } else if ( customAttribute.size === 2 ) {
  13749. for ( ca = 0; ca < cal; ca ++ ) {
  13750. value = customAttribute.value[ ca ];
  13751. customAttribute.array[ offset ] = value.x;
  13752. customAttribute.array[ offset + 1 ] = value.y;
  13753. offset += 2;
  13754. }
  13755. } else if ( customAttribute.size === 3 ) {
  13756. if ( customAttribute.type === "c" ) {
  13757. for ( ca = 0; ca < cal; ca ++ ) {
  13758. value = customAttribute.value[ ca ];
  13759. customAttribute.array[ offset ] = value.r;
  13760. customAttribute.array[ offset + 1 ] = value.g;
  13761. customAttribute.array[ offset + 2 ] = value.b;
  13762. offset += 3;
  13763. }
  13764. } else {
  13765. for ( ca = 0; ca < cal; ca ++ ) {
  13766. value = customAttribute.value[ ca ];
  13767. customAttribute.array[ offset ] = value.x;
  13768. customAttribute.array[ offset + 1 ] = value.y;
  13769. customAttribute.array[ offset + 2 ] = value.z;
  13770. offset += 3;
  13771. }
  13772. }
  13773. } else if ( customAttribute.size === 4 ) {
  13774. for ( ca = 0; ca < cal; ca ++ ) {
  13775. value = customAttribute.value[ ca ];
  13776. customAttribute.array[ offset ] = value.x;
  13777. customAttribute.array[ offset + 1 ] = value.y;
  13778. customAttribute.array[ offset + 2 ] = value.z;
  13779. customAttribute.array[ offset + 3 ] = value.w;
  13780. offset += 4;
  13781. }
  13782. }
  13783. }
  13784. }
  13785. }
  13786. }
  13787. if ( dirtyVertices || object.sortParticles ) {
  13788. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13789. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13790. }
  13791. if ( dirtyColors || object.sortParticles ) {
  13792. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13793. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13794. }
  13795. if ( customAttributes ) {
  13796. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13797. customAttribute = customAttributes[ i ];
  13798. if ( customAttribute.needsUpdate || object.sortParticles ) {
  13799. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13800. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13801. }
  13802. }
  13803. }
  13804. }
  13805. function setLineBuffers ( geometry, hint ) {
  13806. var v, c, d, vertex, offset, color,
  13807. vertices = geometry.vertices,
  13808. colors = geometry.colors,
  13809. lineDistances = geometry.lineDistances,
  13810. vl = vertices.length,
  13811. cl = colors.length,
  13812. dl = lineDistances.length,
  13813. vertexArray = geometry.__vertexArray,
  13814. colorArray = geometry.__colorArray,
  13815. lineDistanceArray = geometry.__lineDistanceArray,
  13816. dirtyVertices = geometry.verticesNeedUpdate,
  13817. dirtyColors = geometry.colorsNeedUpdate,
  13818. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  13819. customAttributes = geometry.__webglCustomAttributesList,
  13820. i, il,
  13821. a, ca, cal, value,
  13822. customAttribute;
  13823. if ( dirtyVertices ) {
  13824. for ( v = 0; v < vl; v ++ ) {
  13825. vertex = vertices[ v ];
  13826. offset = v * 3;
  13827. vertexArray[ offset ] = vertex.x;
  13828. vertexArray[ offset + 1 ] = vertex.y;
  13829. vertexArray[ offset + 2 ] = vertex.z;
  13830. }
  13831. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13832. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13833. }
  13834. if ( dirtyColors ) {
  13835. for ( c = 0; c < cl; c ++ ) {
  13836. color = colors[ c ];
  13837. offset = c * 3;
  13838. colorArray[ offset ] = color.r;
  13839. colorArray[ offset + 1 ] = color.g;
  13840. colorArray[ offset + 2 ] = color.b;
  13841. }
  13842. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13843. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13844. }
  13845. if ( dirtyLineDistances ) {
  13846. for ( d = 0; d < dl; d ++ ) {
  13847. lineDistanceArray[ d ] = lineDistances[ d ];
  13848. }
  13849. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  13850. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  13851. }
  13852. if ( customAttributes ) {
  13853. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13854. customAttribute = customAttributes[ i ];
  13855. if ( customAttribute.needsUpdate &&
  13856. ( customAttribute.boundTo === undefined ||
  13857. customAttribute.boundTo === "vertices" ) ) {
  13858. offset = 0;
  13859. cal = customAttribute.value.length;
  13860. if ( customAttribute.size === 1 ) {
  13861. for ( ca = 0; ca < cal; ca ++ ) {
  13862. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13863. }
  13864. } else if ( customAttribute.size === 2 ) {
  13865. for ( ca = 0; ca < cal; ca ++ ) {
  13866. value = customAttribute.value[ ca ];
  13867. customAttribute.array[ offset ] = value.x;
  13868. customAttribute.array[ offset + 1 ] = value.y;
  13869. offset += 2;
  13870. }
  13871. } else if ( customAttribute.size === 3 ) {
  13872. if ( customAttribute.type === "c" ) {
  13873. for ( ca = 0; ca < cal; ca ++ ) {
  13874. value = customAttribute.value[ ca ];
  13875. customAttribute.array[ offset ] = value.r;
  13876. customAttribute.array[ offset + 1 ] = value.g;
  13877. customAttribute.array[ offset + 2 ] = value.b;
  13878. offset += 3;
  13879. }
  13880. } else {
  13881. for ( ca = 0; ca < cal; ca ++ ) {
  13882. value = customAttribute.value[ ca ];
  13883. customAttribute.array[ offset ] = value.x;
  13884. customAttribute.array[ offset + 1 ] = value.y;
  13885. customAttribute.array[ offset + 2 ] = value.z;
  13886. offset += 3;
  13887. }
  13888. }
  13889. } else if ( customAttribute.size === 4 ) {
  13890. for ( ca = 0; ca < cal; ca ++ ) {
  13891. value = customAttribute.value[ ca ];
  13892. customAttribute.array[ offset ] = value.x;
  13893. customAttribute.array[ offset + 1 ] = value.y;
  13894. customAttribute.array[ offset + 2 ] = value.z;
  13895. customAttribute.array[ offset + 3 ] = value.w;
  13896. offset += 4;
  13897. }
  13898. }
  13899. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13900. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13901. }
  13902. }
  13903. }
  13904. }
  13905. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  13906. if ( ! geometryGroup.__inittedArrays ) {
  13907. return;
  13908. }
  13909. var normalType = bufferGuessNormalType( material ),
  13910. vertexColorType = bufferGuessVertexColorType( material ),
  13911. uvType = bufferGuessUVType( material ),
  13912. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13913. var f, fl, fi, face,
  13914. vertexNormals, faceNormal, normal,
  13915. vertexColors, faceColor,
  13916. vertexTangents,
  13917. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13918. c1, c2, c3, c4,
  13919. sw1, sw2, sw3, sw4,
  13920. si1, si2, si3, si4,
  13921. sa1, sa2, sa3, sa4,
  13922. sb1, sb2, sb3, sb4,
  13923. m, ml, i, il,
  13924. vn, uvi, uv2i,
  13925. vk, vkl, vka,
  13926. nka, chf, faceVertexNormals,
  13927. a,
  13928. vertexIndex = 0,
  13929. offset = 0,
  13930. offset_uv = 0,
  13931. offset_uv2 = 0,
  13932. offset_face = 0,
  13933. offset_normal = 0,
  13934. offset_tangent = 0,
  13935. offset_line = 0,
  13936. offset_color = 0,
  13937. offset_skin = 0,
  13938. offset_morphTarget = 0,
  13939. offset_custom = 0,
  13940. offset_customSrc = 0,
  13941. value,
  13942. vertexArray = geometryGroup.__vertexArray,
  13943. uvArray = geometryGroup.__uvArray,
  13944. uv2Array = geometryGroup.__uv2Array,
  13945. normalArray = geometryGroup.__normalArray,
  13946. tangentArray = geometryGroup.__tangentArray,
  13947. colorArray = geometryGroup.__colorArray,
  13948. skinIndexArray = geometryGroup.__skinIndexArray,
  13949. skinWeightArray = geometryGroup.__skinWeightArray,
  13950. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13951. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13952. customAttributes = geometryGroup.__webglCustomAttributesList,
  13953. customAttribute,
  13954. faceArray = geometryGroup.__faceArray,
  13955. lineArray = geometryGroup.__lineArray,
  13956. geometry = object.geometry, // this is shared for all chunks
  13957. dirtyVertices = geometry.verticesNeedUpdate,
  13958. dirtyElements = geometry.elementsNeedUpdate,
  13959. dirtyUvs = geometry.uvsNeedUpdate,
  13960. dirtyNormals = geometry.normalsNeedUpdate,
  13961. dirtyTangents = geometry.tangentsNeedUpdate,
  13962. dirtyColors = geometry.colorsNeedUpdate,
  13963. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13964. vertices = geometry.vertices,
  13965. chunk_faces3 = geometryGroup.faces3,
  13966. obj_faces = geometry.faces,
  13967. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13968. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13969. obj_colors = geometry.colors,
  13970. obj_skinIndices = geometry.skinIndices,
  13971. obj_skinWeights = geometry.skinWeights,
  13972. morphTargets = geometry.morphTargets,
  13973. morphNormals = geometry.morphNormals;
  13974. if ( dirtyVertices ) {
  13975. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13976. face = obj_faces[ chunk_faces3[ f ] ];
  13977. v1 = vertices[ face.a ];
  13978. v2 = vertices[ face.b ];
  13979. v3 = vertices[ face.c ];
  13980. vertexArray[ offset ] = v1.x;
  13981. vertexArray[ offset + 1 ] = v1.y;
  13982. vertexArray[ offset + 2 ] = v1.z;
  13983. vertexArray[ offset + 3 ] = v2.x;
  13984. vertexArray[ offset + 4 ] = v2.y;
  13985. vertexArray[ offset + 5 ] = v2.z;
  13986. vertexArray[ offset + 6 ] = v3.x;
  13987. vertexArray[ offset + 7 ] = v3.y;
  13988. vertexArray[ offset + 8 ] = v3.z;
  13989. offset += 9;
  13990. }
  13991. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13992. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13993. }
  13994. if ( dirtyMorphTargets ) {
  13995. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13996. offset_morphTarget = 0;
  13997. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13998. chf = chunk_faces3[ f ];
  13999. face = obj_faces[ chf ];
  14000. // morph positions
  14001. v1 = morphTargets[ vk ].vertices[ face.a ];
  14002. v2 = morphTargets[ vk ].vertices[ face.b ];
  14003. v3 = morphTargets[ vk ].vertices[ face.c ];
  14004. vka = morphTargetsArrays[ vk ];
  14005. vka[ offset_morphTarget ] = v1.x;
  14006. vka[ offset_morphTarget + 1 ] = v1.y;
  14007. vka[ offset_morphTarget + 2 ] = v1.z;
  14008. vka[ offset_morphTarget + 3 ] = v2.x;
  14009. vka[ offset_morphTarget + 4 ] = v2.y;
  14010. vka[ offset_morphTarget + 5 ] = v2.z;
  14011. vka[ offset_morphTarget + 6 ] = v3.x;
  14012. vka[ offset_morphTarget + 7 ] = v3.y;
  14013. vka[ offset_morphTarget + 8 ] = v3.z;
  14014. // morph normals
  14015. if ( material.morphNormals ) {
  14016. if ( needsSmoothNormals ) {
  14017. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  14018. n1 = faceVertexNormals.a;
  14019. n2 = faceVertexNormals.b;
  14020. n3 = faceVertexNormals.c;
  14021. } else {
  14022. n1 = morphNormals[ vk ].faceNormals[ chf ];
  14023. n2 = n1;
  14024. n3 = n1;
  14025. }
  14026. nka = morphNormalsArrays[ vk ];
  14027. nka[ offset_morphTarget ] = n1.x;
  14028. nka[ offset_morphTarget + 1 ] = n1.y;
  14029. nka[ offset_morphTarget + 2 ] = n1.z;
  14030. nka[ offset_morphTarget + 3 ] = n2.x;
  14031. nka[ offset_morphTarget + 4 ] = n2.y;
  14032. nka[ offset_morphTarget + 5 ] = n2.z;
  14033. nka[ offset_morphTarget + 6 ] = n3.x;
  14034. nka[ offset_morphTarget + 7 ] = n3.y;
  14035. nka[ offset_morphTarget + 8 ] = n3.z;
  14036. }
  14037. //
  14038. offset_morphTarget += 9;
  14039. }
  14040. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  14041. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  14042. if ( material.morphNormals ) {
  14043. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  14044. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  14045. }
  14046. }
  14047. }
  14048. if ( obj_skinWeights.length ) {
  14049. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14050. face = obj_faces[ chunk_faces3[ f ] ];
  14051. // weights
  14052. sw1 = obj_skinWeights[ face.a ];
  14053. sw2 = obj_skinWeights[ face.b ];
  14054. sw3 = obj_skinWeights[ face.c ];
  14055. skinWeightArray[ offset_skin ] = sw1.x;
  14056. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14057. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14058. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14059. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14060. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14061. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14062. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14063. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14064. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14065. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14066. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14067. // indices
  14068. si1 = obj_skinIndices[ face.a ];
  14069. si2 = obj_skinIndices[ face.b ];
  14070. si3 = obj_skinIndices[ face.c ];
  14071. skinIndexArray[ offset_skin ] = si1.x;
  14072. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14073. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14074. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14075. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14076. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14077. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14078. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14079. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14080. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14081. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14082. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14083. offset_skin += 12;
  14084. }
  14085. if ( offset_skin > 0 ) {
  14086. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  14087. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  14088. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  14089. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  14090. }
  14091. }
  14092. if ( dirtyColors && vertexColorType ) {
  14093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14094. face = obj_faces[ chunk_faces3[ f ] ];
  14095. vertexColors = face.vertexColors;
  14096. faceColor = face.color;
  14097. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  14098. c1 = vertexColors[ 0 ];
  14099. c2 = vertexColors[ 1 ];
  14100. c3 = vertexColors[ 2 ];
  14101. } else {
  14102. c1 = faceColor;
  14103. c2 = faceColor;
  14104. c3 = faceColor;
  14105. }
  14106. colorArray[ offset_color ] = c1.r;
  14107. colorArray[ offset_color + 1 ] = c1.g;
  14108. colorArray[ offset_color + 2 ] = c1.b;
  14109. colorArray[ offset_color + 3 ] = c2.r;
  14110. colorArray[ offset_color + 4 ] = c2.g;
  14111. colorArray[ offset_color + 5 ] = c2.b;
  14112. colorArray[ offset_color + 6 ] = c3.r;
  14113. colorArray[ offset_color + 7 ] = c3.g;
  14114. colorArray[ offset_color + 8 ] = c3.b;
  14115. offset_color += 9;
  14116. }
  14117. if ( offset_color > 0 ) {
  14118. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  14119. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  14120. }
  14121. }
  14122. if ( dirtyTangents && geometry.hasTangents ) {
  14123. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14124. face = obj_faces[ chunk_faces3[ f ] ];
  14125. vertexTangents = face.vertexTangents;
  14126. t1 = vertexTangents[ 0 ];
  14127. t2 = vertexTangents[ 1 ];
  14128. t3 = vertexTangents[ 2 ];
  14129. tangentArray[ offset_tangent ] = t1.x;
  14130. tangentArray[ offset_tangent + 1 ] = t1.y;
  14131. tangentArray[ offset_tangent + 2 ] = t1.z;
  14132. tangentArray[ offset_tangent + 3 ] = t1.w;
  14133. tangentArray[ offset_tangent + 4 ] = t2.x;
  14134. tangentArray[ offset_tangent + 5 ] = t2.y;
  14135. tangentArray[ offset_tangent + 6 ] = t2.z;
  14136. tangentArray[ offset_tangent + 7 ] = t2.w;
  14137. tangentArray[ offset_tangent + 8 ] = t3.x;
  14138. tangentArray[ offset_tangent + 9 ] = t3.y;
  14139. tangentArray[ offset_tangent + 10 ] = t3.z;
  14140. tangentArray[ offset_tangent + 11 ] = t3.w;
  14141. offset_tangent += 12;
  14142. }
  14143. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  14144. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  14145. }
  14146. if ( dirtyNormals && normalType ) {
  14147. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14148. face = obj_faces[ chunk_faces3[ f ] ];
  14149. vertexNormals = face.vertexNormals;
  14150. faceNormal = face.normal;
  14151. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  14152. for ( i = 0; i < 3; i ++ ) {
  14153. vn = vertexNormals[ i ];
  14154. normalArray[ offset_normal ] = vn.x;
  14155. normalArray[ offset_normal + 1 ] = vn.y;
  14156. normalArray[ offset_normal + 2 ] = vn.z;
  14157. offset_normal += 3;
  14158. }
  14159. } else {
  14160. for ( i = 0; i < 3; i ++ ) {
  14161. normalArray[ offset_normal ] = faceNormal.x;
  14162. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14163. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14164. offset_normal += 3;
  14165. }
  14166. }
  14167. }
  14168. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  14169. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  14170. }
  14171. if ( dirtyUvs && obj_uvs && uvType ) {
  14172. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14173. fi = chunk_faces3[ f ];
  14174. uv = obj_uvs[ fi ];
  14175. if ( uv === undefined ) continue;
  14176. for ( i = 0; i < 3; i ++ ) {
  14177. uvi = uv[ i ];
  14178. uvArray[ offset_uv ] = uvi.x;
  14179. uvArray[ offset_uv + 1 ] = uvi.y;
  14180. offset_uv += 2;
  14181. }
  14182. }
  14183. if ( offset_uv > 0 ) {
  14184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  14185. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  14186. }
  14187. }
  14188. if ( dirtyUvs && obj_uvs2 && uvType ) {
  14189. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14190. fi = chunk_faces3[ f ];
  14191. uv2 = obj_uvs2[ fi ];
  14192. if ( uv2 === undefined ) continue;
  14193. for ( i = 0; i < 3; i ++ ) {
  14194. uv2i = uv2[ i ];
  14195. uv2Array[ offset_uv2 ] = uv2i.x;
  14196. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14197. offset_uv2 += 2;
  14198. }
  14199. }
  14200. if ( offset_uv2 > 0 ) {
  14201. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  14202. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  14203. }
  14204. }
  14205. if ( dirtyElements ) {
  14206. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14207. faceArray[ offset_face ] = vertexIndex;
  14208. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14209. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  14210. offset_face += 3;
  14211. lineArray[ offset_line ] = vertexIndex;
  14212. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14213. lineArray[ offset_line + 2 ] = vertexIndex;
  14214. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  14215. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14216. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14217. offset_line += 6;
  14218. vertexIndex += 3;
  14219. }
  14220. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  14221. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  14222. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  14223. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  14224. }
  14225. if ( customAttributes ) {
  14226. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14227. customAttribute = customAttributes[ i ];
  14228. if ( ! customAttribute.__original.needsUpdate ) continue;
  14229. offset_custom = 0;
  14230. offset_customSrc = 0;
  14231. if ( customAttribute.size === 1 ) {
  14232. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14233. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14234. face = obj_faces[ chunk_faces3[ f ] ];
  14235. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14236. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14237. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14238. offset_custom += 3;
  14239. }
  14240. } else if ( customAttribute.boundTo === "faces" ) {
  14241. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14242. value = customAttribute.value[ chunk_faces3[ f ] ];
  14243. customAttribute.array[ offset_custom ] = value;
  14244. customAttribute.array[ offset_custom + 1 ] = value;
  14245. customAttribute.array[ offset_custom + 2 ] = value;
  14246. offset_custom += 3;
  14247. }
  14248. }
  14249. } else if ( customAttribute.size === 2 ) {
  14250. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14251. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14252. face = obj_faces[ chunk_faces3[ f ] ];
  14253. v1 = customAttribute.value[ face.a ];
  14254. v2 = customAttribute.value[ face.b ];
  14255. v3 = customAttribute.value[ face.c ];
  14256. customAttribute.array[ offset_custom ] = v1.x;
  14257. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14258. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14259. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14260. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14261. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14262. offset_custom += 6;
  14263. }
  14264. } else if ( customAttribute.boundTo === "faces" ) {
  14265. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14266. value = customAttribute.value[ chunk_faces3[ f ] ];
  14267. v1 = value;
  14268. v2 = value;
  14269. v3 = value;
  14270. customAttribute.array[ offset_custom ] = v1.x;
  14271. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14272. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14273. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14274. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14275. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14276. offset_custom += 6;
  14277. }
  14278. }
  14279. } else if ( customAttribute.size === 3 ) {
  14280. var pp;
  14281. if ( customAttribute.type === "c" ) {
  14282. pp = [ "r", "g", "b" ];
  14283. } else {
  14284. pp = [ "x", "y", "z" ];
  14285. }
  14286. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14287. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14288. face = obj_faces[ chunk_faces3[ f ] ];
  14289. v1 = customAttribute.value[ face.a ];
  14290. v2 = customAttribute.value[ face.b ];
  14291. v3 = customAttribute.value[ face.c ];
  14292. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14293. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14294. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14295. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14296. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14297. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14298. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14299. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14300. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14301. offset_custom += 9;
  14302. }
  14303. } else if ( customAttribute.boundTo === "faces" ) {
  14304. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14305. value = customAttribute.value[ chunk_faces3[ f ] ];
  14306. v1 = value;
  14307. v2 = value;
  14308. v3 = value;
  14309. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14310. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14311. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14312. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14313. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14314. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14315. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14316. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14317. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14318. offset_custom += 9;
  14319. }
  14320. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14321. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14322. value = customAttribute.value[ chunk_faces3[ f ] ];
  14323. v1 = value[ 0 ];
  14324. v2 = value[ 1 ];
  14325. v3 = value[ 2 ];
  14326. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14327. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14328. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14329. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14330. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14331. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14332. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14333. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14334. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14335. offset_custom += 9;
  14336. }
  14337. }
  14338. } else if ( customAttribute.size === 4 ) {
  14339. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14340. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14341. face = obj_faces[ chunk_faces3[ f ] ];
  14342. v1 = customAttribute.value[ face.a ];
  14343. v2 = customAttribute.value[ face.b ];
  14344. v3 = customAttribute.value[ face.c ];
  14345. customAttribute.array[ offset_custom ] = v1.x;
  14346. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14347. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14348. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14349. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14350. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14351. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14352. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14353. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14354. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14355. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14356. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14357. offset_custom += 12;
  14358. }
  14359. } else if ( customAttribute.boundTo === "faces" ) {
  14360. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14361. value = customAttribute.value[ chunk_faces3[ f ] ];
  14362. v1 = value;
  14363. v2 = value;
  14364. v3 = value;
  14365. customAttribute.array[ offset_custom ] = v1.x;
  14366. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14367. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14368. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14369. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14370. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14371. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14372. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14373. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14374. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14375. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14376. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14377. offset_custom += 12;
  14378. }
  14379. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14380. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14381. value = customAttribute.value[ chunk_faces3[ f ] ];
  14382. v1 = value[ 0 ];
  14383. v2 = value[ 1 ];
  14384. v3 = value[ 2 ];
  14385. customAttribute.array[ offset_custom ] = v1.x;
  14386. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14387. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14388. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14389. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14390. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14391. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14392. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14393. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14394. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14395. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14396. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14397. offset_custom += 12;
  14398. }
  14399. }
  14400. }
  14401. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  14402. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  14403. }
  14404. }
  14405. if ( dispose ) {
  14406. delete geometryGroup.__inittedArrays;
  14407. delete geometryGroup.__colorArray;
  14408. delete geometryGroup.__normalArray;
  14409. delete geometryGroup.__tangentArray;
  14410. delete geometryGroup.__uvArray;
  14411. delete geometryGroup.__uv2Array;
  14412. delete geometryGroup.__faceArray;
  14413. delete geometryGroup.__vertexArray;
  14414. delete geometryGroup.__lineArray;
  14415. delete geometryGroup.__skinIndexArray;
  14416. delete geometryGroup.__skinWeightArray;
  14417. }
  14418. };
  14419. function setDirectBuffers( geometry, hint ) {
  14420. var attributes = geometry.attributes;
  14421. var attributeName, attributeItem;
  14422. for ( attributeName in attributes ) {
  14423. attributeItem = attributes[ attributeName ];
  14424. if ( attributeItem.needsUpdate ) {
  14425. if ( attributeName === 'index' ) {
  14426. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  14427. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  14428. } else {
  14429. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  14430. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  14431. }
  14432. attributeItem.needsUpdate = false;
  14433. }
  14434. }
  14435. }
  14436. // Buffer rendering
  14437. this.renderBufferImmediate = function ( object, program, material ) {
  14438. initAttributes();
  14439. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  14440. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  14441. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  14442. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  14443. if ( object.hasPositions ) {
  14444. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  14445. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  14446. enableAttribute( program.attributes.position );
  14447. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14448. }
  14449. if ( object.hasNormals ) {
  14450. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  14451. if ( material.shading === THREE.FlatShading ) {
  14452. var nx, ny, nz,
  14453. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  14454. normalArray,
  14455. i, il = object.count * 3;
  14456. for( i = 0; i < il; i += 9 ) {
  14457. normalArray = object.normalArray;
  14458. nax = normalArray[ i ];
  14459. nay = normalArray[ i + 1 ];
  14460. naz = normalArray[ i + 2 ];
  14461. nbx = normalArray[ i + 3 ];
  14462. nby = normalArray[ i + 4 ];
  14463. nbz = normalArray[ i + 5 ];
  14464. ncx = normalArray[ i + 6 ];
  14465. ncy = normalArray[ i + 7 ];
  14466. ncz = normalArray[ i + 8 ];
  14467. nx = ( nax + nbx + ncx ) / 3;
  14468. ny = ( nay + nby + ncy ) / 3;
  14469. nz = ( naz + nbz + ncz ) / 3;
  14470. normalArray[ i ] = nx;
  14471. normalArray[ i + 1 ] = ny;
  14472. normalArray[ i + 2 ] = nz;
  14473. normalArray[ i + 3 ] = nx;
  14474. normalArray[ i + 4 ] = ny;
  14475. normalArray[ i + 5 ] = nz;
  14476. normalArray[ i + 6 ] = nx;
  14477. normalArray[ i + 7 ] = ny;
  14478. normalArray[ i + 8 ] = nz;
  14479. }
  14480. }
  14481. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  14482. enableAttribute( program.attributes.normal );
  14483. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14484. }
  14485. if ( object.hasUvs && material.map ) {
  14486. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  14487. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  14488. enableAttribute( program.attributes.uv );
  14489. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14490. }
  14491. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  14492. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  14493. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  14494. enableAttribute( program.attributes.color );
  14495. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14496. }
  14497. disableUnusedAttributes();
  14498. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  14499. object.count = 0;
  14500. };
  14501. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  14502. for ( var attributeName in programAttributes ) {
  14503. var attributePointer = programAttributes[ attributeName ];
  14504. var attributeItem = geometryAttributes[ attributeName ];
  14505. if ( attributePointer >= 0 ) {
  14506. if ( attributeItem ) {
  14507. var attributeSize = attributeItem.itemSize;
  14508. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  14509. enableAttribute( attributePointer );
  14510. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  14511. } else if ( material.defaultAttributeValues ) {
  14512. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  14513. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  14514. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  14515. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  14516. }
  14517. }
  14518. }
  14519. }
  14520. disableUnusedAttributes();
  14521. }
  14522. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  14523. if ( material.visible === false ) return;
  14524. var linewidth, a, attribute;
  14525. var attributeItem, attributeName, attributePointer, attributeSize;
  14526. var program = setProgram( camera, lights, fog, material, object );
  14527. var programAttributes = program.attributes;
  14528. var geometryAttributes = geometry.attributes;
  14529. var updateBuffers = false,
  14530. wireframeBit = material.wireframe ? 1 : 0,
  14531. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  14532. if ( geometryHash !== _currentGeometryGroupHash ) {
  14533. _currentGeometryGroupHash = geometryHash;
  14534. updateBuffers = true;
  14535. }
  14536. if ( updateBuffers ) {
  14537. initAttributes();
  14538. }
  14539. // render mesh
  14540. if ( object instanceof THREE.Mesh ) {
  14541. var index = geometryAttributes[ "index" ];
  14542. if ( index ) {
  14543. // indexed triangles
  14544. var type, size;
  14545. if ( index.array instanceof Uint32Array ) {
  14546. type = _gl.UNSIGNED_INT;
  14547. size = 4;
  14548. } else {
  14549. type = _gl.UNSIGNED_SHORT;
  14550. size = 2;
  14551. }
  14552. var offsets = geometry.offsets;
  14553. if ( offsets.length === 0 ) {
  14554. if ( updateBuffers ) {
  14555. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14556. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14557. }
  14558. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  14559. _this.info.render.calls ++;
  14560. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  14561. _this.info.render.faces += index.array.length / 3;
  14562. } else {
  14563. // if there is more than 1 chunk
  14564. // must set attribute pointers to use new offsets for each chunk
  14565. // even if geometry and materials didn't change
  14566. updateBuffers = true;
  14567. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  14568. var startIndex = offsets[ i ].index;
  14569. if ( updateBuffers ) {
  14570. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  14571. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14572. }
  14573. // render indexed triangles
  14574. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  14575. _this.info.render.calls ++;
  14576. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  14577. _this.info.render.faces += offsets[ i ].count / 3;
  14578. }
  14579. }
  14580. } else {
  14581. // non-indexed triangles
  14582. if ( updateBuffers ) {
  14583. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14584. }
  14585. var position = geometry.attributes[ "position" ];
  14586. // render non-indexed triangles
  14587. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  14588. _this.info.render.calls ++;
  14589. _this.info.render.vertices += position.array.length / 3;
  14590. _this.info.render.faces += position.array.length / 9;
  14591. }
  14592. } else if ( object instanceof THREE.ParticleSystem ) {
  14593. // render particles
  14594. if ( updateBuffers ) {
  14595. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14596. }
  14597. var position = geometryAttributes[ "position" ];
  14598. // render particles
  14599. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  14600. _this.info.render.calls ++;
  14601. _this.info.render.points += position.array.length / 3;
  14602. } else if ( object instanceof THREE.Line ) {
  14603. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14604. setLineWidth( material.linewidth );
  14605. var index = geometryAttributes[ "index" ];
  14606. if ( index ) {
  14607. // indexed lines
  14608. var type, size;
  14609. if ( index.array instanceof Uint32Array ){
  14610. type = _gl.UNSIGNED_INT;
  14611. size = 4;
  14612. } else {
  14613. type = _gl.UNSIGNED_SHORT;
  14614. size = 2;
  14615. }
  14616. var offsets = geometry.offsets;
  14617. if ( offsets.length === 0 ) {
  14618. if ( updateBuffers ) {
  14619. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14620. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14621. }
  14622. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  14623. _this.info.render.calls ++;
  14624. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  14625. } else {
  14626. // if there is more than 1 chunk
  14627. // must set attribute pointers to use new offsets for each chunk
  14628. // even if geometry and materials didn't change
  14629. if ( offsets.length > 1 ) updateBuffers = true;
  14630. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  14631. var startIndex = offsets[ i ].index;
  14632. if ( updateBuffers ) {
  14633. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  14634. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14635. }
  14636. // render indexed lines
  14637. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  14638. _this.info.render.calls ++;
  14639. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  14640. }
  14641. }
  14642. } else {
  14643. // non-indexed lines
  14644. if ( updateBuffers ) {
  14645. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14646. }
  14647. var position = geometryAttributes[ "position" ];
  14648. _gl.drawArrays( mode, 0, position.array.length / 3 );
  14649. _this.info.render.calls ++;
  14650. _this.info.render.points += position.array.length / 3;
  14651. }
  14652. }
  14653. };
  14654. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  14655. if ( material.visible === false ) return;
  14656. var linewidth, a, attribute, i, il;
  14657. var program = setProgram( camera, lights, fog, material, object );
  14658. var attributes = program.attributes;
  14659. var updateBuffers = false,
  14660. wireframeBit = material.wireframe ? 1 : 0,
  14661. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  14662. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  14663. _currentGeometryGroupHash = geometryGroupHash;
  14664. updateBuffers = true;
  14665. }
  14666. if ( updateBuffers ) {
  14667. initAttributes();
  14668. }
  14669. // vertices
  14670. if ( !material.morphTargets && attributes.position >= 0 ) {
  14671. if ( updateBuffers ) {
  14672. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14673. enableAttribute( attributes.position );
  14674. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14675. }
  14676. } else {
  14677. if ( object.morphTargetBase ) {
  14678. setupMorphTargets( material, geometryGroup, object );
  14679. }
  14680. }
  14681. if ( updateBuffers ) {
  14682. // custom attributes
  14683. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  14684. if ( geometryGroup.__webglCustomAttributesList ) {
  14685. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  14686. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  14687. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  14688. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  14689. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  14690. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  14691. }
  14692. }
  14693. }
  14694. // colors
  14695. if ( attributes.color >= 0 ) {
  14696. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  14697. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  14698. enableAttribute( attributes.color );
  14699. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14700. } else if ( material.defaultAttributeValues ) {
  14701. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  14702. }
  14703. }
  14704. // normals
  14705. if ( attributes.normal >= 0 ) {
  14706. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  14707. enableAttribute( attributes.normal );
  14708. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14709. }
  14710. // tangents
  14711. if ( attributes.tangent >= 0 ) {
  14712. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  14713. enableAttribute( attributes.tangent );
  14714. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  14715. }
  14716. // uvs
  14717. if ( attributes.uv >= 0 ) {
  14718. if ( object.geometry.faceVertexUvs[0] ) {
  14719. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  14720. enableAttribute( attributes.uv );
  14721. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14722. } else if ( material.defaultAttributeValues ) {
  14723. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  14724. }
  14725. }
  14726. if ( attributes.uv2 >= 0 ) {
  14727. if ( object.geometry.faceVertexUvs[1] ) {
  14728. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  14729. enableAttribute( attributes.uv2 );
  14730. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  14731. } else if ( material.defaultAttributeValues ) {
  14732. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  14733. }
  14734. }
  14735. if ( material.skinning &&
  14736. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  14737. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  14738. enableAttribute( attributes.skinIndex );
  14739. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  14740. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  14741. enableAttribute( attributes.skinWeight );
  14742. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  14743. }
  14744. // line distances
  14745. if ( attributes.lineDistance >= 0 ) {
  14746. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  14747. enableAttribute( attributes.lineDistance );
  14748. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  14749. }
  14750. }
  14751. disableUnusedAttributes();
  14752. // render mesh
  14753. if ( object instanceof THREE.Mesh ) {
  14754. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  14755. // wireframe
  14756. if ( material.wireframe ) {
  14757. setLineWidth( material.wireframeLinewidth );
  14758. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  14759. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  14760. // triangles
  14761. } else {
  14762. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  14763. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  14764. }
  14765. _this.info.render.calls ++;
  14766. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  14767. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  14768. // render lines
  14769. } else if ( object instanceof THREE.Line ) {
  14770. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14771. setLineWidth( material.linewidth );
  14772. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  14773. _this.info.render.calls ++;
  14774. // render particles
  14775. } else if ( object instanceof THREE.ParticleSystem ) {
  14776. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  14777. _this.info.render.calls ++;
  14778. _this.info.render.points += geometryGroup.__webglParticleCount;
  14779. }
  14780. };
  14781. function initAttributes() {
  14782. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  14783. _newAttributes[ i ] = 0;
  14784. }
  14785. }
  14786. function enableAttribute( attribute ) {
  14787. _newAttributes[ attribute ] = 1;
  14788. if ( _enabledAttributes[ attribute ] === 0 ) {
  14789. _gl.enableVertexAttribArray( attribute );
  14790. _enabledAttributes[ attribute ] = 1;
  14791. }
  14792. }
  14793. function disableUnusedAttributes() {
  14794. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  14795. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  14796. _gl.disableVertexAttribArray( i );
  14797. _enabledAttributes[ i ] = 0;
  14798. }
  14799. }
  14800. }
  14801. function setupMorphTargets ( material, geometryGroup, object ) {
  14802. // set base
  14803. var attributes = material.program.attributes;
  14804. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  14805. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  14806. enableAttribute( attributes.position );
  14807. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14808. } else if ( attributes.position >= 0 ) {
  14809. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14810. enableAttribute( attributes.position );
  14811. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14812. }
  14813. if ( object.morphTargetForcedOrder.length ) {
  14814. // set forced order
  14815. var m = 0;
  14816. var order = object.morphTargetForcedOrder;
  14817. var influences = object.morphTargetInfluences;
  14818. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  14819. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14820. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  14821. enableAttribute( attributes[ "morphTarget" + m ] );
  14822. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14823. }
  14824. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14825. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  14826. enableAttribute( attributes[ "morphNormal" + m ] );
  14827. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14828. }
  14829. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  14830. m ++;
  14831. }
  14832. } else {
  14833. // find the most influencing
  14834. var influence, activeInfluenceIndices = [];
  14835. var influences = object.morphTargetInfluences;
  14836. var i, il = influences.length;
  14837. for ( i = 0; i < il; i ++ ) {
  14838. influence = influences[ i ];
  14839. if ( influence > 0 ) {
  14840. activeInfluenceIndices.push( [ influence, i ] );
  14841. }
  14842. }
  14843. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  14844. activeInfluenceIndices.sort( numericalSort );
  14845. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  14846. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  14847. activeInfluenceIndices.sort( numericalSort );
  14848. } else if ( activeInfluenceIndices.length === 0 ) {
  14849. activeInfluenceIndices.push( [ 0, 0 ] );
  14850. };
  14851. var influenceIndex, m = 0;
  14852. while ( m < material.numSupportedMorphTargets ) {
  14853. if ( activeInfluenceIndices[ m ] ) {
  14854. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  14855. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14856. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  14857. enableAttribute( attributes[ "morphTarget" + m ] );
  14858. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14859. }
  14860. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14861. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  14862. enableAttribute( attributes[ "morphNormal" + m ] );
  14863. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14864. }
  14865. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  14866. } else {
  14867. /*
  14868. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14869. if ( material.morphNormals ) {
  14870. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14871. }
  14872. */
  14873. object.__webglMorphTargetInfluences[ m ] = 0;
  14874. }
  14875. m ++;
  14876. }
  14877. }
  14878. // load updated influences uniform
  14879. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  14880. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  14881. }
  14882. };
  14883. // Sorting
  14884. function painterSortStable ( a, b ) {
  14885. if ( a.z !== b.z ) {
  14886. return b.z - a.z;
  14887. } else {
  14888. return a.id - b.id;
  14889. }
  14890. };
  14891. function numericalSort ( a, b ) {
  14892. return b[ 0 ] - a[ 0 ];
  14893. };
  14894. // Rendering
  14895. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14896. if ( camera instanceof THREE.Camera === false ) {
  14897. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14898. return;
  14899. }
  14900. var i, il,
  14901. webglObject, object,
  14902. renderList,
  14903. lights = scene.__lights,
  14904. fog = scene.fog;
  14905. // reset caching for this frame
  14906. _currentMaterialId = -1;
  14907. _lightsNeedUpdate = true;
  14908. // update scene graph
  14909. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14910. // update camera matrices and frustum
  14911. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14912. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14913. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14914. _frustum.setFromMatrix( _projScreenMatrix );
  14915. // update WebGL objects
  14916. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14917. // custom render plugins (pre pass)
  14918. renderPlugins( this.renderPluginsPre, scene, camera );
  14919. //
  14920. _this.info.render.calls = 0;
  14921. _this.info.render.vertices = 0;
  14922. _this.info.render.faces = 0;
  14923. _this.info.render.points = 0;
  14924. this.setRenderTarget( renderTarget );
  14925. if ( this.autoClear || forceClear ) {
  14926. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14927. }
  14928. // set matrices for regular objects (frustum culled)
  14929. renderList = scene.__webglObjects;
  14930. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14931. webglObject = renderList[ i ];
  14932. object = webglObject.object;
  14933. webglObject.id = i;
  14934. webglObject.render = false;
  14935. if ( object.visible ) {
  14936. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14937. setupMatrices( object, camera );
  14938. unrollBufferMaterial( webglObject );
  14939. webglObject.render = true;
  14940. if ( this.sortObjects === true ) {
  14941. if ( object.renderDepth !== null ) {
  14942. webglObject.z = object.renderDepth;
  14943. } else {
  14944. _vector3.setFromMatrixPosition( object.matrixWorld );
  14945. _vector3.applyProjection( _projScreenMatrix );
  14946. webglObject.z = _vector3.z;
  14947. }
  14948. }
  14949. }
  14950. }
  14951. }
  14952. if ( this.sortObjects ) {
  14953. renderList.sort( painterSortStable );
  14954. }
  14955. // set matrices for immediate objects
  14956. renderList = scene.__webglObjectsImmediate;
  14957. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14958. webglObject = renderList[ i ];
  14959. object = webglObject.object;
  14960. if ( object.visible ) {
  14961. setupMatrices( object, camera );
  14962. unrollImmediateBufferMaterial( webglObject );
  14963. }
  14964. }
  14965. if ( scene.overrideMaterial ) {
  14966. var material = scene.overrideMaterial;
  14967. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14968. this.setDepthTest( material.depthTest );
  14969. this.setDepthWrite( material.depthWrite );
  14970. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14971. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14972. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14973. } else {
  14974. var material = null;
  14975. // opaque pass (front-to-back order)
  14976. this.setBlending( THREE.NoBlending );
  14977. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14978. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14979. // transparent pass (back-to-front order)
  14980. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14981. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14982. }
  14983. // custom render plugins (post pass)
  14984. renderPlugins( this.renderPluginsPost, scene, camera );
  14985. // Generate mipmap if we're using any kind of mipmap filtering
  14986. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14987. updateRenderTargetMipmap( renderTarget );
  14988. }
  14989. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14990. this.setDepthTest( true );
  14991. this.setDepthWrite( true );
  14992. // _gl.finish();
  14993. };
  14994. function renderPlugins( plugins, scene, camera ) {
  14995. if ( ! plugins.length ) return;
  14996. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14997. // reset state for plugin (to start from clean slate)
  14998. _currentProgram = null;
  14999. _currentCamera = null;
  15000. _oldBlending = -1;
  15001. _oldDepthTest = -1;
  15002. _oldDepthWrite = -1;
  15003. _oldDoubleSided = -1;
  15004. _oldFlipSided = -1;
  15005. _currentGeometryGroupHash = -1;
  15006. _currentMaterialId = -1;
  15007. _lightsNeedUpdate = true;
  15008. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  15009. // reset state after plugin (anything could have changed)
  15010. _currentProgram = null;
  15011. _currentCamera = null;
  15012. _oldBlending = -1;
  15013. _oldDepthTest = -1;
  15014. _oldDepthWrite = -1;
  15015. _oldDoubleSided = -1;
  15016. _oldFlipSided = -1;
  15017. _currentGeometryGroupHash = -1;
  15018. _currentMaterialId = -1;
  15019. _lightsNeedUpdate = true;
  15020. }
  15021. };
  15022. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  15023. var webglObject, object, buffer, material, start, end, delta;
  15024. if ( reverse ) {
  15025. start = renderList.length - 1;
  15026. end = -1;
  15027. delta = -1;
  15028. } else {
  15029. start = 0;
  15030. end = renderList.length;
  15031. delta = 1;
  15032. }
  15033. for ( var i = start; i !== end; i += delta ) {
  15034. webglObject = renderList[ i ];
  15035. if ( webglObject.render ) {
  15036. object = webglObject.object;
  15037. buffer = webglObject.buffer;
  15038. if ( overrideMaterial ) {
  15039. material = overrideMaterial;
  15040. } else {
  15041. material = webglObject[ materialType ];
  15042. if ( ! material ) continue;
  15043. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15044. _this.setDepthTest( material.depthTest );
  15045. _this.setDepthWrite( material.depthWrite );
  15046. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15047. }
  15048. _this.setMaterialFaces( material );
  15049. if ( buffer instanceof THREE.BufferGeometry ) {
  15050. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  15051. } else {
  15052. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  15053. }
  15054. }
  15055. }
  15056. };
  15057. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  15058. var webglObject, object, material, program;
  15059. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  15060. webglObject = renderList[ i ];
  15061. object = webglObject.object;
  15062. if ( object.visible ) {
  15063. if ( overrideMaterial ) {
  15064. material = overrideMaterial;
  15065. } else {
  15066. material = webglObject[ materialType ];
  15067. if ( ! material ) continue;
  15068. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15069. _this.setDepthTest( material.depthTest );
  15070. _this.setDepthWrite( material.depthWrite );
  15071. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15072. }
  15073. _this.renderImmediateObject( camera, lights, fog, material, object );
  15074. }
  15075. }
  15076. };
  15077. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  15078. var program = setProgram( camera, lights, fog, material, object );
  15079. _currentGeometryGroupHash = -1;
  15080. _this.setMaterialFaces( material );
  15081. if ( object.immediateRenderCallback ) {
  15082. object.immediateRenderCallback( program, _gl, _frustum );
  15083. } else {
  15084. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  15085. }
  15086. };
  15087. function unrollImmediateBufferMaterial ( globject ) {
  15088. var object = globject.object,
  15089. material = object.material;
  15090. if ( material.transparent ) {
  15091. globject.transparent = material;
  15092. globject.opaque = null;
  15093. } else {
  15094. globject.opaque = material;
  15095. globject.transparent = null;
  15096. }
  15097. };
  15098. function unrollBufferMaterial ( globject ) {
  15099. var object = globject.object;
  15100. var buffer = globject.buffer;
  15101. var geometry = object.geometry;
  15102. var material = object.material;
  15103. if ( material instanceof THREE.MeshFaceMaterial ) {
  15104. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  15105. material = material.materials[ materialIndex ];
  15106. if ( material.transparent ) {
  15107. globject.transparent = material;
  15108. globject.opaque = null;
  15109. } else {
  15110. globject.opaque = material;
  15111. globject.transparent = null;
  15112. }
  15113. } else {
  15114. if ( material ) {
  15115. if ( material.transparent ) {
  15116. globject.transparent = material;
  15117. globject.opaque = null;
  15118. } else {
  15119. globject.opaque = material;
  15120. globject.transparent = null;
  15121. }
  15122. }
  15123. }
  15124. };
  15125. // Objects refresh
  15126. this.initWebGLObjects = function ( scene ) {
  15127. if ( !scene.__webglObjects ) {
  15128. scene.__webglObjects = [];
  15129. scene.__webglObjectsImmediate = [];
  15130. scene.__webglSprites = [];
  15131. scene.__webglFlares = [];
  15132. }
  15133. while ( scene.__objectsAdded.length ) {
  15134. addObject( scene.__objectsAdded[ 0 ], scene );
  15135. scene.__objectsAdded.splice( 0, 1 );
  15136. }
  15137. while ( scene.__objectsRemoved.length ) {
  15138. removeObject( scene.__objectsRemoved[ 0 ], scene );
  15139. scene.__objectsRemoved.splice( 0, 1 );
  15140. }
  15141. // update must be called after objects adding / removal
  15142. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  15143. var object = scene.__webglObjects[ o ].object;
  15144. // TODO: Remove this hack (WebGLRenderer refactoring)
  15145. if ( object.__webglInit === undefined ) {
  15146. if ( object.__webglActive !== undefined ) {
  15147. removeObject( object, scene );
  15148. }
  15149. addObject( object, scene );
  15150. }
  15151. updateObject( object );
  15152. }
  15153. };
  15154. // Objects adding
  15155. function addObject( object, scene ) {
  15156. var g, geometry, material, geometryGroup;
  15157. if ( object.__webglInit === undefined ) {
  15158. object.__webglInit = true;
  15159. object._modelViewMatrix = new THREE.Matrix4();
  15160. object._normalMatrix = new THREE.Matrix3();
  15161. geometry = object.geometry;
  15162. if ( geometry === undefined ) {
  15163. // ImmediateRenderObject
  15164. } else if ( geometry.__webglInit === undefined ) {
  15165. geometry.__webglInit = true;
  15166. geometry.addEventListener( 'dispose', onGeometryDispose );
  15167. if ( geometry instanceof THREE.BufferGeometry ) {
  15168. initDirectBuffers( geometry );
  15169. } else if ( object instanceof THREE.Mesh ) {
  15170. material = object.material;
  15171. if ( geometry.geometryGroups === undefined ) {
  15172. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  15173. }
  15174. // create separate VBOs per geometry chunk
  15175. for ( g in geometry.geometryGroups ) {
  15176. geometryGroup = geometry.geometryGroups[ g ];
  15177. // initialise VBO on the first access
  15178. if ( ! geometryGroup.__webglVertexBuffer ) {
  15179. createMeshBuffers( geometryGroup );
  15180. initMeshBuffers( geometryGroup, object );
  15181. geometry.verticesNeedUpdate = true;
  15182. geometry.morphTargetsNeedUpdate = true;
  15183. geometry.elementsNeedUpdate = true;
  15184. geometry.uvsNeedUpdate = true;
  15185. geometry.normalsNeedUpdate = true;
  15186. geometry.tangentsNeedUpdate = true;
  15187. geometry.colorsNeedUpdate = true;
  15188. }
  15189. }
  15190. } else if ( object instanceof THREE.Line ) {
  15191. if ( ! geometry.__webglVertexBuffer ) {
  15192. createLineBuffers( geometry );
  15193. initLineBuffers( geometry, object );
  15194. geometry.verticesNeedUpdate = true;
  15195. geometry.colorsNeedUpdate = true;
  15196. geometry.lineDistancesNeedUpdate = true;
  15197. }
  15198. } else if ( object instanceof THREE.ParticleSystem ) {
  15199. if ( ! geometry.__webglVertexBuffer ) {
  15200. createParticleBuffers( geometry );
  15201. initParticleBuffers( geometry, object );
  15202. geometry.verticesNeedUpdate = true;
  15203. geometry.colorsNeedUpdate = true;
  15204. }
  15205. }
  15206. }
  15207. }
  15208. if ( object.__webglActive === undefined ) {
  15209. if ( object instanceof THREE.Mesh ) {
  15210. geometry = object.geometry;
  15211. if ( geometry instanceof THREE.BufferGeometry ) {
  15212. addBuffer( scene.__webglObjects, geometry, object );
  15213. } else if ( geometry instanceof THREE.Geometry ) {
  15214. for ( g in geometry.geometryGroups ) {
  15215. geometryGroup = geometry.geometryGroups[ g ];
  15216. addBuffer( scene.__webglObjects, geometryGroup, object );
  15217. }
  15218. }
  15219. } else if ( object instanceof THREE.Line ||
  15220. object instanceof THREE.ParticleSystem ) {
  15221. geometry = object.geometry;
  15222. addBuffer( scene.__webglObjects, geometry, object );
  15223. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  15224. addBufferImmediate( scene.__webglObjectsImmediate, object );
  15225. } else if ( object instanceof THREE.Sprite ) {
  15226. scene.__webglSprites.push( object );
  15227. } else if ( object instanceof THREE.LensFlare ) {
  15228. scene.__webglFlares.push( object );
  15229. }
  15230. object.__webglActive = true;
  15231. }
  15232. };
  15233. function addBuffer( objlist, buffer, object ) {
  15234. objlist.push(
  15235. {
  15236. id: null,
  15237. buffer: buffer,
  15238. object: object,
  15239. opaque: null,
  15240. transparent: null,
  15241. z: 0
  15242. }
  15243. );
  15244. };
  15245. function addBufferImmediate( objlist, object ) {
  15246. objlist.push(
  15247. {
  15248. id: null,
  15249. object: object,
  15250. opaque: null,
  15251. transparent: null,
  15252. z: 0
  15253. }
  15254. );
  15255. };
  15256. // Objects updates
  15257. function updateObject( object ) {
  15258. var geometry = object.geometry,
  15259. geometryGroup, customAttributesDirty, material;
  15260. if ( geometry instanceof THREE.BufferGeometry ) {
  15261. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  15262. } else if ( object instanceof THREE.Mesh ) {
  15263. // check all geometry groups
  15264. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  15265. geometryGroup = geometry.geometryGroupsList[ i ];
  15266. material = getBufferMaterial( object, geometryGroup );
  15267. if ( geometry.buffersNeedUpdate ) {
  15268. initMeshBuffers( geometryGroup, object );
  15269. }
  15270. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  15271. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  15272. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  15273. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  15274. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  15275. }
  15276. }
  15277. geometry.verticesNeedUpdate = false;
  15278. geometry.morphTargetsNeedUpdate = false;
  15279. geometry.elementsNeedUpdate = false;
  15280. geometry.uvsNeedUpdate = false;
  15281. geometry.normalsNeedUpdate = false;
  15282. geometry.colorsNeedUpdate = false;
  15283. geometry.tangentsNeedUpdate = false;
  15284. geometry.buffersNeedUpdate = false;
  15285. material.attributes && clearCustomAttributes( material );
  15286. } else if ( object instanceof THREE.Line ) {
  15287. material = getBufferMaterial( object, geometry );
  15288. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  15289. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  15290. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  15291. }
  15292. geometry.verticesNeedUpdate = false;
  15293. geometry.colorsNeedUpdate = false;
  15294. geometry.lineDistancesNeedUpdate = false;
  15295. material.attributes && clearCustomAttributes( material );
  15296. } else if ( object instanceof THREE.ParticleSystem ) {
  15297. material = getBufferMaterial( object, geometry );
  15298. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  15299. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  15300. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  15301. }
  15302. geometry.verticesNeedUpdate = false;
  15303. geometry.colorsNeedUpdate = false;
  15304. material.attributes && clearCustomAttributes( material );
  15305. }
  15306. };
  15307. // Objects updates - custom attributes check
  15308. function areCustomAttributesDirty( material ) {
  15309. for ( var a in material.attributes ) {
  15310. if ( material.attributes[ a ].needsUpdate ) return true;
  15311. }
  15312. return false;
  15313. };
  15314. function clearCustomAttributes( material ) {
  15315. for ( var a in material.attributes ) {
  15316. material.attributes[ a ].needsUpdate = false;
  15317. }
  15318. };
  15319. // Objects removal
  15320. function removeObject( object, scene ) {
  15321. if ( object instanceof THREE.Mesh ||
  15322. object instanceof THREE.ParticleSystem ||
  15323. object instanceof THREE.Line ) {
  15324. removeInstances( scene.__webglObjects, object );
  15325. } else if ( object instanceof THREE.Sprite ) {
  15326. removeInstancesDirect( scene.__webglSprites, object );
  15327. } else if ( object instanceof THREE.LensFlare ) {
  15328. removeInstancesDirect( scene.__webglFlares, object );
  15329. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  15330. removeInstances( scene.__webglObjectsImmediate, object );
  15331. }
  15332. delete object.__webglActive;
  15333. };
  15334. function removeInstances( objlist, object ) {
  15335. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  15336. if ( objlist[ o ].object === object ) {
  15337. objlist.splice( o, 1 );
  15338. }
  15339. }
  15340. };
  15341. function removeInstancesDirect( objlist, object ) {
  15342. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  15343. if ( objlist[ o ] === object ) {
  15344. objlist.splice( o, 1 );
  15345. }
  15346. }
  15347. };
  15348. // Materials
  15349. this.initMaterial = function ( material, lights, fog, object ) {
  15350. material.addEventListener( 'dispose', onMaterialDispose );
  15351. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  15352. if ( material instanceof THREE.MeshDepthMaterial ) {
  15353. shaderID = 'depth';
  15354. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15355. shaderID = 'normal';
  15356. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  15357. shaderID = 'basic';
  15358. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  15359. shaderID = 'lambert';
  15360. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15361. shaderID = 'phong';
  15362. } else if ( material instanceof THREE.LineBasicMaterial ) {
  15363. shaderID = 'basic';
  15364. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15365. shaderID = 'dashed';
  15366. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  15367. shaderID = 'particle_basic';
  15368. }
  15369. if ( shaderID ) {
  15370. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  15371. }
  15372. // heuristics to create shader parameters according to lights in the scene
  15373. // (not to blow over maxLights budget)
  15374. maxLightCount = allocateLights( lights );
  15375. maxShadows = allocateShadows( lights );
  15376. maxBones = allocateBones( object );
  15377. parameters = {
  15378. precision: _precision,
  15379. supportsVertexTextures: _supportsVertexTextures,
  15380. map: !!material.map,
  15381. envMap: !!material.envMap,
  15382. lightMap: !!material.lightMap,
  15383. bumpMap: !!material.bumpMap,
  15384. normalMap: !!material.normalMap,
  15385. specularMap: !!material.specularMap,
  15386. vertexColors: material.vertexColors,
  15387. fog: fog,
  15388. useFog: material.fog,
  15389. fogExp: fog instanceof THREE.FogExp2,
  15390. sizeAttenuation: material.sizeAttenuation,
  15391. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  15392. skinning: material.skinning,
  15393. maxBones: maxBones,
  15394. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  15395. morphTargets: material.morphTargets,
  15396. morphNormals: material.morphNormals,
  15397. maxMorphTargets: this.maxMorphTargets,
  15398. maxMorphNormals: this.maxMorphNormals,
  15399. maxDirLights: maxLightCount.directional,
  15400. maxPointLights: maxLightCount.point,
  15401. maxSpotLights: maxLightCount.spot,
  15402. maxHemiLights: maxLightCount.hemi,
  15403. maxShadows: maxShadows,
  15404. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  15405. shadowMapType: this.shadowMapType,
  15406. shadowMapDebug: this.shadowMapDebug,
  15407. shadowMapCascade: this.shadowMapCascade,
  15408. alphaTest: material.alphaTest,
  15409. metal: material.metal,
  15410. wrapAround: material.wrapAround,
  15411. doubleSided: material.side === THREE.DoubleSide,
  15412. flipSided: material.side === THREE.BackSide
  15413. };
  15414. // Generate code
  15415. var chunks = [];
  15416. if ( shaderID ) {
  15417. chunks.push( shaderID );
  15418. } else {
  15419. chunks.push( material.fragmentShader );
  15420. chunks.push( material.vertexShader );
  15421. }
  15422. for ( var d in material.defines ) {
  15423. chunks.push( d );
  15424. chunks.push( material.defines[ d ] );
  15425. }
  15426. for ( var p in parameters ) {
  15427. chunks.push( p );
  15428. chunks.push( parameters[ p ] );
  15429. }
  15430. var code = chunks.join();
  15431. var program;
  15432. // Check if code has been already compiled
  15433. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  15434. var programInfo = _programs[ p ];
  15435. if ( programInfo.code === code ) {
  15436. program = programInfo;
  15437. program.usedTimes ++;
  15438. break;
  15439. }
  15440. }
  15441. if ( program === undefined ) {
  15442. program = new THREE.WebGLProgram( this, code, material, parameters );
  15443. _programs.push( program );
  15444. _this.info.memory.programs = _programs.length;
  15445. }
  15446. material.program = program;
  15447. var attributes = material.program.attributes;
  15448. if ( material.morphTargets ) {
  15449. material.numSupportedMorphTargets = 0;
  15450. var id, base = "morphTarget";
  15451. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  15452. id = base + i;
  15453. if ( attributes[ id ] >= 0 ) {
  15454. material.numSupportedMorphTargets ++;
  15455. }
  15456. }
  15457. }
  15458. if ( material.morphNormals ) {
  15459. material.numSupportedMorphNormals = 0;
  15460. var id, base = "morphNormal";
  15461. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  15462. id = base + i;
  15463. if ( attributes[ id ] >= 0 ) {
  15464. material.numSupportedMorphNormals ++;
  15465. }
  15466. }
  15467. }
  15468. material.uniformsList = [];
  15469. for ( u in material.uniforms ) {
  15470. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  15471. }
  15472. };
  15473. function setMaterialShaders( material, shaders ) {
  15474. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  15475. material.vertexShader = shaders.vertexShader;
  15476. material.fragmentShader = shaders.fragmentShader;
  15477. };
  15478. function setProgram( camera, lights, fog, material, object ) {
  15479. _usedTextureUnits = 0;
  15480. if ( material.needsUpdate ) {
  15481. if ( material.program ) deallocateMaterial( material );
  15482. _this.initMaterial( material, lights, fog, object );
  15483. material.needsUpdate = false;
  15484. }
  15485. if ( material.morphTargets ) {
  15486. if ( ! object.__webglMorphTargetInfluences ) {
  15487. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  15488. }
  15489. }
  15490. var refreshMaterial = false;
  15491. var program = material.program,
  15492. p_uniforms = program.uniforms,
  15493. m_uniforms = material.uniforms;
  15494. if ( program.id !== _currentProgram ) {
  15495. _gl.useProgram( program.program );
  15496. _currentProgram = program.id;
  15497. refreshMaterial = true;
  15498. }
  15499. if ( material.id !== _currentMaterialId ) {
  15500. _currentMaterialId = material.id;
  15501. refreshMaterial = true;
  15502. }
  15503. if ( refreshMaterial || camera !== _currentCamera ) {
  15504. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15505. if ( _logarithmicDepthBuffer ) {
  15506. _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15507. }
  15508. if ( camera !== _currentCamera ) _currentCamera = camera;
  15509. }
  15510. // skinning uniforms must be set even if material didn't change
  15511. // auto-setting of texture unit for bone texture must go before other textures
  15512. // not sure why, but otherwise weird things happen
  15513. if ( material.skinning ) {
  15514. if ( _supportsBoneTextures && object.useVertexTexture ) {
  15515. if ( p_uniforms.boneTexture !== null ) {
  15516. var textureUnit = getTextureUnit();
  15517. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15518. _this.setTexture( object.boneTexture, textureUnit );
  15519. }
  15520. if ( p_uniforms.boneTextureWidth !== null ) {
  15521. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  15522. }
  15523. if ( p_uniforms.boneTextureHeight !== null ) {
  15524. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  15525. }
  15526. } else {
  15527. if ( p_uniforms.boneGlobalMatrices !== null ) {
  15528. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  15529. }
  15530. }
  15531. }
  15532. if ( refreshMaterial ) {
  15533. // refresh uniforms common to several materials
  15534. if ( fog && material.fog ) {
  15535. refreshUniformsFog( m_uniforms, fog );
  15536. }
  15537. if ( material instanceof THREE.MeshPhongMaterial ||
  15538. material instanceof THREE.MeshLambertMaterial ||
  15539. material.lights ) {
  15540. if ( _lightsNeedUpdate ) {
  15541. setupLights( program, lights );
  15542. _lightsNeedUpdate = false;
  15543. }
  15544. refreshUniformsLights( m_uniforms, _lights );
  15545. }
  15546. if ( material instanceof THREE.MeshBasicMaterial ||
  15547. material instanceof THREE.MeshLambertMaterial ||
  15548. material instanceof THREE.MeshPhongMaterial ) {
  15549. refreshUniformsCommon( m_uniforms, material );
  15550. }
  15551. // refresh single material specific uniforms
  15552. if ( material instanceof THREE.LineBasicMaterial ) {
  15553. refreshUniformsLine( m_uniforms, material );
  15554. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15555. refreshUniformsLine( m_uniforms, material );
  15556. refreshUniformsDash( m_uniforms, material );
  15557. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  15558. refreshUniformsParticle( m_uniforms, material );
  15559. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15560. refreshUniformsPhong( m_uniforms, material );
  15561. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  15562. refreshUniformsLambert( m_uniforms, material );
  15563. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15564. m_uniforms.mNear.value = camera.near;
  15565. m_uniforms.mFar.value = camera.far;
  15566. m_uniforms.opacity.value = material.opacity;
  15567. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15568. m_uniforms.opacity.value = material.opacity;
  15569. }
  15570. if ( object.receiveShadow && ! material._shadowPass ) {
  15571. refreshUniformsShadow( m_uniforms, lights );
  15572. }
  15573. // load common uniforms
  15574. loadUniformsGeneric( program, material.uniformsList );
  15575. // load material specific uniforms
  15576. // (shader material also gets them for the sake of genericity)
  15577. if ( material instanceof THREE.ShaderMaterial ||
  15578. material instanceof THREE.MeshPhongMaterial ||
  15579. material.envMap ) {
  15580. if ( p_uniforms.cameraPosition !== null ) {
  15581. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15582. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15583. }
  15584. }
  15585. if ( material instanceof THREE.MeshPhongMaterial ||
  15586. material instanceof THREE.MeshLambertMaterial ||
  15587. material instanceof THREE.ShaderMaterial ||
  15588. material.skinning ) {
  15589. if ( p_uniforms.viewMatrix !== null ) {
  15590. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15591. }
  15592. }
  15593. }
  15594. loadUniformsMatrices( p_uniforms, object );
  15595. if ( p_uniforms.modelMatrix !== null ) {
  15596. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15597. }
  15598. return program;
  15599. };
  15600. // Uniforms (refresh uniforms objects)
  15601. function refreshUniformsCommon ( uniforms, material ) {
  15602. uniforms.opacity.value = material.opacity;
  15603. if ( _this.gammaInput ) {
  15604. uniforms.diffuse.value.copyGammaToLinear( material.color );
  15605. } else {
  15606. uniforms.diffuse.value = material.color;
  15607. }
  15608. uniforms.map.value = material.map;
  15609. uniforms.lightMap.value = material.lightMap;
  15610. uniforms.specularMap.value = material.specularMap;
  15611. if ( material.bumpMap ) {
  15612. uniforms.bumpMap.value = material.bumpMap;
  15613. uniforms.bumpScale.value = material.bumpScale;
  15614. }
  15615. if ( material.normalMap ) {
  15616. uniforms.normalMap.value = material.normalMap;
  15617. uniforms.normalScale.value.copy( material.normalScale );
  15618. }
  15619. // uv repeat and offset setting priorities
  15620. // 1. color map
  15621. // 2. specular map
  15622. // 3. normal map
  15623. // 4. bump map
  15624. var uvScaleMap;
  15625. if ( material.map ) {
  15626. uvScaleMap = material.map;
  15627. } else if ( material.specularMap ) {
  15628. uvScaleMap = material.specularMap;
  15629. } else if ( material.normalMap ) {
  15630. uvScaleMap = material.normalMap;
  15631. } else if ( material.bumpMap ) {
  15632. uvScaleMap = material.bumpMap;
  15633. }
  15634. if ( uvScaleMap !== undefined ) {
  15635. var offset = uvScaleMap.offset;
  15636. var repeat = uvScaleMap.repeat;
  15637. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15638. }
  15639. uniforms.envMap.value = material.envMap;
  15640. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  15641. if ( _this.gammaInput ) {
  15642. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  15643. uniforms.reflectivity.value = material.reflectivity;
  15644. } else {
  15645. uniforms.reflectivity.value = material.reflectivity;
  15646. }
  15647. uniforms.refractionRatio.value = material.refractionRatio;
  15648. uniforms.combine.value = material.combine;
  15649. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  15650. };
  15651. function refreshUniformsLine ( uniforms, material ) {
  15652. uniforms.diffuse.value = material.color;
  15653. uniforms.opacity.value = material.opacity;
  15654. };
  15655. function refreshUniformsDash ( uniforms, material ) {
  15656. uniforms.dashSize.value = material.dashSize;
  15657. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15658. uniforms.scale.value = material.scale;
  15659. };
  15660. function refreshUniformsParticle ( uniforms, material ) {
  15661. uniforms.psColor.value = material.color;
  15662. uniforms.opacity.value = material.opacity;
  15663. uniforms.size.value = material.size;
  15664. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15665. uniforms.map.value = material.map;
  15666. };
  15667. function refreshUniformsFog ( uniforms, fog ) {
  15668. uniforms.fogColor.value = fog.color;
  15669. if ( fog instanceof THREE.Fog ) {
  15670. uniforms.fogNear.value = fog.near;
  15671. uniforms.fogFar.value = fog.far;
  15672. } else if ( fog instanceof THREE.FogExp2 ) {
  15673. uniforms.fogDensity.value = fog.density;
  15674. }
  15675. };
  15676. function refreshUniformsPhong ( uniforms, material ) {
  15677. uniforms.shininess.value = material.shininess;
  15678. if ( _this.gammaInput ) {
  15679. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15680. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15681. uniforms.specular.value.copyGammaToLinear( material.specular );
  15682. } else {
  15683. uniforms.ambient.value = material.ambient;
  15684. uniforms.emissive.value = material.emissive;
  15685. uniforms.specular.value = material.specular;
  15686. }
  15687. if ( material.wrapAround ) {
  15688. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15689. }
  15690. };
  15691. function refreshUniformsLambert ( uniforms, material ) {
  15692. if ( _this.gammaInput ) {
  15693. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15694. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15695. } else {
  15696. uniforms.ambient.value = material.ambient;
  15697. uniforms.emissive.value = material.emissive;
  15698. }
  15699. if ( material.wrapAround ) {
  15700. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15701. }
  15702. };
  15703. function refreshUniformsLights ( uniforms, lights ) {
  15704. uniforms.ambientLightColor.value = lights.ambient;
  15705. uniforms.directionalLightColor.value = lights.directional.colors;
  15706. uniforms.directionalLightDirection.value = lights.directional.positions;
  15707. uniforms.pointLightColor.value = lights.point.colors;
  15708. uniforms.pointLightPosition.value = lights.point.positions;
  15709. uniforms.pointLightDistance.value = lights.point.distances;
  15710. uniforms.spotLightColor.value = lights.spot.colors;
  15711. uniforms.spotLightPosition.value = lights.spot.positions;
  15712. uniforms.spotLightDistance.value = lights.spot.distances;
  15713. uniforms.spotLightDirection.value = lights.spot.directions;
  15714. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  15715. uniforms.spotLightExponent.value = lights.spot.exponents;
  15716. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  15717. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  15718. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  15719. };
  15720. function refreshUniformsShadow ( uniforms, lights ) {
  15721. if ( uniforms.shadowMatrix ) {
  15722. var j = 0;
  15723. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  15724. var light = lights[ i ];
  15725. if ( ! light.castShadow ) continue;
  15726. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  15727. uniforms.shadowMap.value[ j ] = light.shadowMap;
  15728. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  15729. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  15730. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  15731. uniforms.shadowBias.value[ j ] = light.shadowBias;
  15732. j ++;
  15733. }
  15734. }
  15735. }
  15736. };
  15737. // Uniforms (load to GPU)
  15738. function loadUniformsMatrices ( uniforms, object ) {
  15739. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  15740. if ( uniforms.normalMatrix ) {
  15741. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  15742. }
  15743. };
  15744. function getTextureUnit() {
  15745. var textureUnit = _usedTextureUnits;
  15746. if ( textureUnit >= _maxTextures ) {
  15747. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  15748. }
  15749. _usedTextureUnits += 1;
  15750. return textureUnit;
  15751. };
  15752. function loadUniformsGeneric ( program, uniforms ) {
  15753. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  15754. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15755. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  15756. if ( !location ) continue;
  15757. uniform = uniforms[ j ][ 0 ];
  15758. type = uniform.type;
  15759. value = uniform.value;
  15760. if ( type === "i" ) { // single integer
  15761. _gl.uniform1i( location, value );
  15762. } else if ( type === "f" ) { // single float
  15763. _gl.uniform1f( location, value );
  15764. } else if ( type === "v2" ) { // single THREE.Vector2
  15765. _gl.uniform2f( location, value.x, value.y );
  15766. } else if ( type === "v3" ) { // single THREE.Vector3
  15767. _gl.uniform3f( location, value.x, value.y, value.z );
  15768. } else if ( type === "v4" ) { // single THREE.Vector4
  15769. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15770. } else if ( type === "c" ) { // single THREE.Color
  15771. _gl.uniform3f( location, value.r, value.g, value.b );
  15772. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  15773. _gl.uniform1iv( location, value );
  15774. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  15775. _gl.uniform3iv( location, value );
  15776. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  15777. _gl.uniform1fv( location, value );
  15778. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  15779. _gl.uniform3fv( location, value );
  15780. } else if ( type === "v2v" ) { // array of THREE.Vector2
  15781. if ( uniform._array === undefined ) {
  15782. uniform._array = new Float32Array( 2 * value.length );
  15783. }
  15784. for ( i = 0, il = value.length; i < il; i ++ ) {
  15785. offset = i * 2;
  15786. uniform._array[ offset ] = value[ i ].x;
  15787. uniform._array[ offset + 1 ] = value[ i ].y;
  15788. }
  15789. _gl.uniform2fv( location, uniform._array );
  15790. } else if ( type === "v3v" ) { // array of THREE.Vector3
  15791. if ( uniform._array === undefined ) {
  15792. uniform._array = new Float32Array( 3 * value.length );
  15793. }
  15794. for ( i = 0, il = value.length; i < il; i ++ ) {
  15795. offset = i * 3;
  15796. uniform._array[ offset ] = value[ i ].x;
  15797. uniform._array[ offset + 1 ] = value[ i ].y;
  15798. uniform._array[ offset + 2 ] = value[ i ].z;
  15799. }
  15800. _gl.uniform3fv( location, uniform._array );
  15801. } else if ( type === "v4v" ) { // array of THREE.Vector4
  15802. if ( uniform._array === undefined ) {
  15803. uniform._array = new Float32Array( 4 * value.length );
  15804. }
  15805. for ( i = 0, il = value.length; i < il; i ++ ) {
  15806. offset = i * 4;
  15807. uniform._array[ offset ] = value[ i ].x;
  15808. uniform._array[ offset + 1 ] = value[ i ].y;
  15809. uniform._array[ offset + 2 ] = value[ i ].z;
  15810. uniform._array[ offset + 3 ] = value[ i ].w;
  15811. }
  15812. _gl.uniform4fv( location, uniform._array );
  15813. } else if ( type === "m3") { // single THREE.Matrix3
  15814. _gl.uniformMatrix3fv( location, false, value.elements );
  15815. } else if ( type === "m3v" ) { // array of THREE.Matrix3
  15816. if ( uniform._array === undefined ) {
  15817. uniform._array = new Float32Array( 9 * value.length );
  15818. }
  15819. for ( i = 0, il = value.length; i < il; i ++ ) {
  15820. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  15821. }
  15822. _gl.uniformMatrix3fv( location, false, uniform._array );
  15823. } else if ( type === "m4") { // single THREE.Matrix4
  15824. _gl.uniformMatrix4fv( location, false, value.elements );
  15825. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  15826. if ( uniform._array === undefined ) {
  15827. uniform._array = new Float32Array( 16 * value.length );
  15828. }
  15829. for ( i = 0, il = value.length; i < il; i ++ ) {
  15830. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  15831. }
  15832. _gl.uniformMatrix4fv( location, false, uniform._array );
  15833. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  15834. texture = value;
  15835. textureUnit = getTextureUnit();
  15836. _gl.uniform1i( location, textureUnit );
  15837. if ( !texture ) continue;
  15838. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  15839. setCubeTexture( texture, textureUnit );
  15840. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15841. setCubeTextureDynamic( texture, textureUnit );
  15842. } else {
  15843. _this.setTexture( texture, textureUnit );
  15844. }
  15845. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  15846. if ( uniform._array === undefined ) {
  15847. uniform._array = [];
  15848. }
  15849. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15850. uniform._array[ i ] = getTextureUnit();
  15851. }
  15852. _gl.uniform1iv( location, uniform._array );
  15853. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15854. texture = uniform.value[ i ];
  15855. textureUnit = uniform._array[ i ];
  15856. if ( !texture ) continue;
  15857. _this.setTexture( texture, textureUnit );
  15858. }
  15859. } else {
  15860. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  15861. }
  15862. }
  15863. };
  15864. function setupMatrices ( object, camera ) {
  15865. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15866. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  15867. };
  15868. //
  15869. function setColorGamma( array, offset, color, intensitySq ) {
  15870. array[ offset ] = color.r * color.r * intensitySq;
  15871. array[ offset + 1 ] = color.g * color.g * intensitySq;
  15872. array[ offset + 2 ] = color.b * color.b * intensitySq;
  15873. };
  15874. function setColorLinear( array, offset, color, intensity ) {
  15875. array[ offset ] = color.r * intensity;
  15876. array[ offset + 1 ] = color.g * intensity;
  15877. array[ offset + 2 ] = color.b * intensity;
  15878. };
  15879. function setupLights ( program, lights ) {
  15880. var l, ll, light, n,
  15881. r = 0, g = 0, b = 0,
  15882. color, skyColor, groundColor,
  15883. intensity, intensitySq,
  15884. position,
  15885. distance,
  15886. zlights = _lights,
  15887. dirColors = zlights.directional.colors,
  15888. dirPositions = zlights.directional.positions,
  15889. pointColors = zlights.point.colors,
  15890. pointPositions = zlights.point.positions,
  15891. pointDistances = zlights.point.distances,
  15892. spotColors = zlights.spot.colors,
  15893. spotPositions = zlights.spot.positions,
  15894. spotDistances = zlights.spot.distances,
  15895. spotDirections = zlights.spot.directions,
  15896. spotAnglesCos = zlights.spot.anglesCos,
  15897. spotExponents = zlights.spot.exponents,
  15898. hemiSkyColors = zlights.hemi.skyColors,
  15899. hemiGroundColors = zlights.hemi.groundColors,
  15900. hemiPositions = zlights.hemi.positions,
  15901. dirLength = 0,
  15902. pointLength = 0,
  15903. spotLength = 0,
  15904. hemiLength = 0,
  15905. dirCount = 0,
  15906. pointCount = 0,
  15907. spotCount = 0,
  15908. hemiCount = 0,
  15909. dirOffset = 0,
  15910. pointOffset = 0,
  15911. spotOffset = 0,
  15912. hemiOffset = 0;
  15913. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15914. light = lights[ l ];
  15915. if ( light.onlyShadow ) continue;
  15916. color = light.color;
  15917. intensity = light.intensity;
  15918. distance = light.distance;
  15919. if ( light instanceof THREE.AmbientLight ) {
  15920. if ( ! light.visible ) continue;
  15921. if ( _this.gammaInput ) {
  15922. r += color.r * color.r;
  15923. g += color.g * color.g;
  15924. b += color.b * color.b;
  15925. } else {
  15926. r += color.r;
  15927. g += color.g;
  15928. b += color.b;
  15929. }
  15930. } else if ( light instanceof THREE.DirectionalLight ) {
  15931. dirCount += 1;
  15932. if ( ! light.visible ) continue;
  15933. _direction.setFromMatrixPosition( light.matrixWorld );
  15934. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15935. _direction.sub( _vector3 );
  15936. _direction.normalize();
  15937. // skip lights with undefined direction
  15938. // these create troubles in OpenGL (making pixel black)
  15939. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15940. dirOffset = dirLength * 3;
  15941. dirPositions[ dirOffset ] = _direction.x;
  15942. dirPositions[ dirOffset + 1 ] = _direction.y;
  15943. dirPositions[ dirOffset + 2 ] = _direction.z;
  15944. if ( _this.gammaInput ) {
  15945. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15946. } else {
  15947. setColorLinear( dirColors, dirOffset, color, intensity );
  15948. }
  15949. dirLength += 1;
  15950. } else if ( light instanceof THREE.PointLight ) {
  15951. pointCount += 1;
  15952. if ( ! light.visible ) continue;
  15953. pointOffset = pointLength * 3;
  15954. if ( _this.gammaInput ) {
  15955. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15956. } else {
  15957. setColorLinear( pointColors, pointOffset, color, intensity );
  15958. }
  15959. _vector3.setFromMatrixPosition( light.matrixWorld );
  15960. pointPositions[ pointOffset ] = _vector3.x;
  15961. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15962. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15963. pointDistances[ pointLength ] = distance;
  15964. pointLength += 1;
  15965. } else if ( light instanceof THREE.SpotLight ) {
  15966. spotCount += 1;
  15967. if ( ! light.visible ) continue;
  15968. spotOffset = spotLength * 3;
  15969. if ( _this.gammaInput ) {
  15970. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15971. } else {
  15972. setColorLinear( spotColors, spotOffset, color, intensity );
  15973. }
  15974. _vector3.setFromMatrixPosition( light.matrixWorld );
  15975. spotPositions[ spotOffset ] = _vector3.x;
  15976. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15977. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15978. spotDistances[ spotLength ] = distance;
  15979. _direction.copy( _vector3 );
  15980. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15981. _direction.sub( _vector3 );
  15982. _direction.normalize();
  15983. spotDirections[ spotOffset ] = _direction.x;
  15984. spotDirections[ spotOffset + 1 ] = _direction.y;
  15985. spotDirections[ spotOffset + 2 ] = _direction.z;
  15986. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15987. spotExponents[ spotLength ] = light.exponent;
  15988. spotLength += 1;
  15989. } else if ( light instanceof THREE.HemisphereLight ) {
  15990. hemiCount += 1;
  15991. if ( ! light.visible ) continue;
  15992. _direction.setFromMatrixPosition( light.matrixWorld );
  15993. _direction.normalize();
  15994. // skip lights with undefined direction
  15995. // these create troubles in OpenGL (making pixel black)
  15996. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15997. hemiOffset = hemiLength * 3;
  15998. hemiPositions[ hemiOffset ] = _direction.x;
  15999. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  16000. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  16001. skyColor = light.color;
  16002. groundColor = light.groundColor;
  16003. if ( _this.gammaInput ) {
  16004. intensitySq = intensity * intensity;
  16005. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  16006. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  16007. } else {
  16008. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  16009. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  16010. }
  16011. hemiLength += 1;
  16012. }
  16013. }
  16014. // null eventual remains from removed lights
  16015. // (this is to avoid if in shader)
  16016. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  16017. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  16018. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  16019. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  16020. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  16021. zlights.directional.length = dirLength;
  16022. zlights.point.length = pointLength;
  16023. zlights.spot.length = spotLength;
  16024. zlights.hemi.length = hemiLength;
  16025. zlights.ambient[ 0 ] = r;
  16026. zlights.ambient[ 1 ] = g;
  16027. zlights.ambient[ 2 ] = b;
  16028. };
  16029. // GL state setting
  16030. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16031. if ( cullFace === THREE.CullFaceNone ) {
  16032. _gl.disable( _gl.CULL_FACE );
  16033. } else {
  16034. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16035. _gl.frontFace( _gl.CW );
  16036. } else {
  16037. _gl.frontFace( _gl.CCW );
  16038. }
  16039. if ( cullFace === THREE.CullFaceBack ) {
  16040. _gl.cullFace( _gl.BACK );
  16041. } else if ( cullFace === THREE.CullFaceFront ) {
  16042. _gl.cullFace( _gl.FRONT );
  16043. } else {
  16044. _gl.cullFace( _gl.FRONT_AND_BACK );
  16045. }
  16046. _gl.enable( _gl.CULL_FACE );
  16047. }
  16048. };
  16049. this.setMaterialFaces = function ( material ) {
  16050. var doubleSided = material.side === THREE.DoubleSide;
  16051. var flipSided = material.side === THREE.BackSide;
  16052. if ( _oldDoubleSided !== doubleSided ) {
  16053. if ( doubleSided ) {
  16054. _gl.disable( _gl.CULL_FACE );
  16055. } else {
  16056. _gl.enable( _gl.CULL_FACE );
  16057. }
  16058. _oldDoubleSided = doubleSided;
  16059. }
  16060. if ( _oldFlipSided !== flipSided ) {
  16061. if ( flipSided ) {
  16062. _gl.frontFace( _gl.CW );
  16063. } else {
  16064. _gl.frontFace( _gl.CCW );
  16065. }
  16066. _oldFlipSided = flipSided;
  16067. }
  16068. };
  16069. this.setDepthTest = function ( depthTest ) {
  16070. if ( _oldDepthTest !== depthTest ) {
  16071. if ( depthTest ) {
  16072. _gl.enable( _gl.DEPTH_TEST );
  16073. } else {
  16074. _gl.disable( _gl.DEPTH_TEST );
  16075. }
  16076. _oldDepthTest = depthTest;
  16077. }
  16078. };
  16079. this.setDepthWrite = function ( depthWrite ) {
  16080. if ( _oldDepthWrite !== depthWrite ) {
  16081. _gl.depthMask( depthWrite );
  16082. _oldDepthWrite = depthWrite;
  16083. }
  16084. };
  16085. function setLineWidth ( width ) {
  16086. if ( width !== _oldLineWidth ) {
  16087. _gl.lineWidth( width );
  16088. _oldLineWidth = width;
  16089. }
  16090. };
  16091. function setPolygonOffset ( polygonoffset, factor, units ) {
  16092. if ( _oldPolygonOffset !== polygonoffset ) {
  16093. if ( polygonoffset ) {
  16094. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  16095. } else {
  16096. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  16097. }
  16098. _oldPolygonOffset = polygonoffset;
  16099. }
  16100. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  16101. _gl.polygonOffset( factor, units );
  16102. _oldPolygonOffsetFactor = factor;
  16103. _oldPolygonOffsetUnits = units;
  16104. }
  16105. };
  16106. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  16107. if ( blending !== _oldBlending ) {
  16108. if ( blending === THREE.NoBlending ) {
  16109. _gl.disable( _gl.BLEND );
  16110. } else if ( blending === THREE.AdditiveBlending ) {
  16111. _gl.enable( _gl.BLEND );
  16112. _gl.blendEquation( _gl.FUNC_ADD );
  16113. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  16114. } else if ( blending === THREE.SubtractiveBlending ) {
  16115. // TODO: Find blendFuncSeparate() combination
  16116. _gl.enable( _gl.BLEND );
  16117. _gl.blendEquation( _gl.FUNC_ADD );
  16118. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  16119. } else if ( blending === THREE.MultiplyBlending ) {
  16120. // TODO: Find blendFuncSeparate() combination
  16121. _gl.enable( _gl.BLEND );
  16122. _gl.blendEquation( _gl.FUNC_ADD );
  16123. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  16124. } else if ( blending === THREE.CustomBlending ) {
  16125. _gl.enable( _gl.BLEND );
  16126. } else {
  16127. _gl.enable( _gl.BLEND );
  16128. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  16129. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  16130. }
  16131. _oldBlending = blending;
  16132. }
  16133. if ( blending === THREE.CustomBlending ) {
  16134. if ( blendEquation !== _oldBlendEquation ) {
  16135. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  16136. _oldBlendEquation = blendEquation;
  16137. }
  16138. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  16139. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  16140. _oldBlendSrc = blendSrc;
  16141. _oldBlendDst = blendDst;
  16142. }
  16143. } else {
  16144. _oldBlendEquation = null;
  16145. _oldBlendSrc = null;
  16146. _oldBlendDst = null;
  16147. }
  16148. };
  16149. // Textures
  16150. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  16151. if ( isImagePowerOfTwo ) {
  16152. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16153. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16154. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16155. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16156. } else {
  16157. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16158. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16159. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16160. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16161. }
  16162. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  16163. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  16164. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  16165. texture.__oldAnisotropy = texture.anisotropy;
  16166. }
  16167. }
  16168. };
  16169. this.setTexture = function ( texture, slot ) {
  16170. if ( texture.needsUpdate ) {
  16171. if ( ! texture.__webglInit ) {
  16172. texture.__webglInit = true;
  16173. texture.addEventListener( 'dispose', onTextureDispose );
  16174. texture.__webglTexture = _gl.createTexture();
  16175. _this.info.memory.textures ++;
  16176. }
  16177. _gl.activeTexture( _gl.TEXTURE0 + slot );
  16178. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  16179. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16180. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16181. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16182. var image = texture.image,
  16183. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  16184. glFormat = paramThreeToGL( texture.format ),
  16185. glType = paramThreeToGL( texture.type );
  16186. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  16187. var mipmap, mipmaps = texture.mipmaps;
  16188. if ( texture instanceof THREE.DataTexture ) {
  16189. // use manually created mipmaps if available
  16190. // if there are no manual mipmaps
  16191. // set 0 level mipmap and then use GL to generate other mipmap levels
  16192. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16193. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16194. mipmap = mipmaps[ i ];
  16195. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16196. }
  16197. texture.generateMipmaps = false;
  16198. } else {
  16199. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16200. }
  16201. } else if ( texture instanceof THREE.CompressedTexture ) {
  16202. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16203. mipmap = mipmaps[ i ];
  16204. if ( texture.format!==THREE.RGBAFormat ) {
  16205. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16206. } else {
  16207. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16208. }
  16209. }
  16210. } else { // regular Texture (image, video, canvas)
  16211. // use manually created mipmaps if available
  16212. // if there are no manual mipmaps
  16213. // set 0 level mipmap and then use GL to generate other mipmap levels
  16214. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16215. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16216. mipmap = mipmaps[ i ];
  16217. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16218. }
  16219. texture.generateMipmaps = false;
  16220. } else {
  16221. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  16222. }
  16223. }
  16224. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16225. texture.needsUpdate = false;
  16226. if ( texture.onUpdate ) texture.onUpdate();
  16227. } else {
  16228. _gl.activeTexture( _gl.TEXTURE0 + slot );
  16229. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  16230. }
  16231. };
  16232. function clampToMaxSize ( image, maxSize ) {
  16233. if ( image.width <= maxSize && image.height <= maxSize ) {
  16234. return image;
  16235. }
  16236. // Warning: Scaling through the canvas will only work with images that use
  16237. // premultiplied alpha.
  16238. var maxDimension = Math.max( image.width, image.height );
  16239. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  16240. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  16241. var canvas = document.createElement( 'canvas' );
  16242. canvas.width = newWidth;
  16243. canvas.height = newHeight;
  16244. var ctx = canvas.getContext( "2d" );
  16245. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  16246. return canvas;
  16247. }
  16248. function setCubeTexture ( texture, slot ) {
  16249. if ( texture.image.length === 6 ) {
  16250. if ( texture.needsUpdate ) {
  16251. if ( ! texture.image.__webglTextureCube ) {
  16252. texture.addEventListener( 'dispose', onTextureDispose );
  16253. texture.image.__webglTextureCube = _gl.createTexture();
  16254. _this.info.memory.textures ++;
  16255. }
  16256. _gl.activeTexture( _gl.TEXTURE0 + slot );
  16257. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  16258. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16259. var isCompressed = texture instanceof THREE.CompressedTexture;
  16260. var cubeImage = [];
  16261. for ( var i = 0; i < 6; i ++ ) {
  16262. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  16263. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  16264. } else {
  16265. cubeImage[ i ] = texture.image[ i ];
  16266. }
  16267. }
  16268. var image = cubeImage[ 0 ],
  16269. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  16270. glFormat = paramThreeToGL( texture.format ),
  16271. glType = paramThreeToGL( texture.type );
  16272. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  16273. for ( var i = 0; i < 6; i ++ ) {
  16274. if( !isCompressed ) {
  16275. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16276. } else {
  16277. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16278. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16279. mipmap = mipmaps[ j ];
  16280. if ( texture.format!==THREE.RGBAFormat ) {
  16281. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16282. } else {
  16283. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16284. }
  16285. }
  16286. }
  16287. }
  16288. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  16289. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16290. }
  16291. texture.needsUpdate = false;
  16292. if ( texture.onUpdate ) texture.onUpdate();
  16293. } else {
  16294. _gl.activeTexture( _gl.TEXTURE0 + slot );
  16295. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  16296. }
  16297. }
  16298. };
  16299. function setCubeTextureDynamic ( texture, slot ) {
  16300. _gl.activeTexture( _gl.TEXTURE0 + slot );
  16301. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  16302. };
  16303. // Render targets
  16304. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  16305. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16306. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  16307. };
  16308. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  16309. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16310. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16311. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16312. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16313. /* For some reason this is not working. Defaulting to RGBA4.
  16314. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16315. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  16316. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16317. */
  16318. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16319. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16320. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16321. } else {
  16322. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16323. }
  16324. };
  16325. this.setRenderTarget = function ( renderTarget ) {
  16326. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16327. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  16328. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  16329. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  16330. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16331. renderTarget.__webglTexture = _gl.createTexture();
  16332. _this.info.memory.textures ++;
  16333. // Setup texture, create render and frame buffers
  16334. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  16335. glFormat = paramThreeToGL( renderTarget.format ),
  16336. glType = paramThreeToGL( renderTarget.type );
  16337. if ( isCube ) {
  16338. renderTarget.__webglFramebuffer = [];
  16339. renderTarget.__webglRenderbuffer = [];
  16340. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  16341. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  16342. for ( var i = 0; i < 6; i ++ ) {
  16343. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16344. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  16345. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16346. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16347. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  16348. }
  16349. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16350. } else {
  16351. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  16352. if ( renderTarget.shareDepthFrom ) {
  16353. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  16354. } else {
  16355. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  16356. }
  16357. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  16358. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  16359. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16360. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  16361. if ( renderTarget.shareDepthFrom ) {
  16362. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16363. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  16364. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16365. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  16366. }
  16367. } else {
  16368. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  16369. }
  16370. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16371. }
  16372. // Release everything
  16373. if ( isCube ) {
  16374. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16375. } else {
  16376. _gl.bindTexture( _gl.TEXTURE_2D, null );
  16377. }
  16378. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16379. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16380. }
  16381. var framebuffer, width, height, vx, vy;
  16382. if ( renderTarget ) {
  16383. if ( isCube ) {
  16384. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16385. } else {
  16386. framebuffer = renderTarget.__webglFramebuffer;
  16387. }
  16388. width = renderTarget.width;
  16389. height = renderTarget.height;
  16390. vx = 0;
  16391. vy = 0;
  16392. } else {
  16393. framebuffer = null;
  16394. width = _viewportWidth;
  16395. height = _viewportHeight;
  16396. vx = _viewportX;
  16397. vy = _viewportY;
  16398. }
  16399. if ( framebuffer !== _currentFramebuffer ) {
  16400. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16401. _gl.viewport( vx, vy, width, height );
  16402. _currentFramebuffer = framebuffer;
  16403. }
  16404. _currentWidth = width;
  16405. _currentHeight = height;
  16406. };
  16407. function updateRenderTargetMipmap ( renderTarget ) {
  16408. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  16409. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  16410. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16411. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16412. } else {
  16413. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  16414. _gl.generateMipmap( _gl.TEXTURE_2D );
  16415. _gl.bindTexture( _gl.TEXTURE_2D, null );
  16416. }
  16417. };
  16418. // Fallback filters for non-power-of-2 textures
  16419. function filterFallback ( f ) {
  16420. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16421. return _gl.NEAREST;
  16422. }
  16423. return _gl.LINEAR;
  16424. };
  16425. // Map three.js constants to WebGL constants
  16426. function paramThreeToGL ( p ) {
  16427. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16428. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16429. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16430. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16431. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16432. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16433. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16434. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16435. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16436. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16437. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16438. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16439. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16440. if ( p === THREE.ByteType ) return _gl.BYTE;
  16441. if ( p === THREE.ShortType ) return _gl.SHORT;
  16442. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16443. if ( p === THREE.IntType ) return _gl.INT;
  16444. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16445. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16446. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16447. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16448. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16449. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16450. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16451. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16452. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16453. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16454. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16455. if ( p === THREE.OneFactor ) return _gl.ONE;
  16456. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16457. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16458. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16459. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16460. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16461. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16462. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16463. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16464. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16465. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  16466. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16467. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16468. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16469. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16470. }
  16471. return 0;
  16472. };
  16473. // Allocations
  16474. function allocateBones ( object ) {
  16475. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  16476. return 1024;
  16477. } else {
  16478. // default for when object is not specified
  16479. // ( for example when prebuilding shader
  16480. // to be used with multiple objects )
  16481. //
  16482. // - leave some extra space for other uniforms
  16483. // - limit here is ANGLE's 254 max uniform vectors
  16484. // (up to 54 should be safe)
  16485. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  16486. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  16487. var maxBones = nVertexMatrices;
  16488. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  16489. maxBones = Math.min( object.bones.length, maxBones );
  16490. if ( maxBones < object.bones.length ) {
  16491. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  16492. }
  16493. }
  16494. return maxBones;
  16495. }
  16496. };
  16497. function allocateLights( lights ) {
  16498. var dirLights = 0;
  16499. var pointLights = 0;
  16500. var spotLights = 0;
  16501. var hemiLights = 0;
  16502. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  16503. var light = lights[ l ];
  16504. if ( light.onlyShadow || light.visible === false ) continue;
  16505. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  16506. if ( light instanceof THREE.PointLight ) pointLights ++;
  16507. if ( light instanceof THREE.SpotLight ) spotLights ++;
  16508. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  16509. }
  16510. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  16511. };
  16512. function allocateShadows( lights ) {
  16513. var maxShadows = 0;
  16514. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  16515. var light = lights[ l ];
  16516. if ( ! light.castShadow ) continue;
  16517. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  16518. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  16519. }
  16520. return maxShadows;
  16521. };
  16522. // Initialization
  16523. function initGL() {
  16524. try {
  16525. var attributes = {
  16526. alpha: _alpha,
  16527. depth: _depth,
  16528. stencil: _stencil,
  16529. antialias: _antialias,
  16530. premultipliedAlpha: _premultipliedAlpha,
  16531. preserveDrawingBuffer: _preserveDrawingBuffer
  16532. };
  16533. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  16534. if ( _gl === null ) {
  16535. throw 'Error creating WebGL context.';
  16536. }
  16537. } catch ( error ) {
  16538. console.error( error );
  16539. }
  16540. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  16541. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  16542. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  16543. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16544. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16545. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  16546. if ( _glExtensionTextureFloat === null ) {
  16547. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  16548. }
  16549. if ( _glExtensionStandardDerivatives === null ) {
  16550. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  16551. }
  16552. if ( _glExtensionTextureFilterAnisotropic === null ) {
  16553. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  16554. }
  16555. if ( _glExtensionCompressedTextureS3TC === null ) {
  16556. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  16557. }
  16558. if ( _glExtensionElementIndexUint === null ) {
  16559. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  16560. }
  16561. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16562. _gl.getShaderPrecisionFormat = function() {
  16563. return {
  16564. "rangeMin" : 1,
  16565. "rangeMax" : 1,
  16566. "precision" : 1
  16567. };
  16568. }
  16569. }
  16570. if ( _logarithmicDepthBuffer ) {
  16571. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  16572. }
  16573. };
  16574. function setDefaultGLState () {
  16575. _gl.clearColor( 0, 0, 0, 1 );
  16576. _gl.clearDepth( 1 );
  16577. _gl.clearStencil( 0 );
  16578. _gl.enable( _gl.DEPTH_TEST );
  16579. _gl.depthFunc( _gl.LEQUAL );
  16580. _gl.frontFace( _gl.CCW );
  16581. _gl.cullFace( _gl.BACK );
  16582. _gl.enable( _gl.CULL_FACE );
  16583. _gl.enable( _gl.BLEND );
  16584. _gl.blendEquation( _gl.FUNC_ADD );
  16585. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  16586. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  16587. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  16588. };
  16589. // default plugins (order is important)
  16590. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  16591. this.addPrePlugin( this.shadowMapPlugin );
  16592. this.addPostPlugin( new THREE.SpritePlugin() );
  16593. this.addPostPlugin( new THREE.LensFlarePlugin() );
  16594. };
  16595. /**
  16596. * @author szimek / https://github.com/szimek/
  16597. * @author alteredq / http://alteredqualia.com/
  16598. */
  16599. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16600. this.width = width;
  16601. this.height = height;
  16602. options = options || {};
  16603. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  16604. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  16605. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  16606. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  16607. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  16608. this.offset = new THREE.Vector2( 0, 0 );
  16609. this.repeat = new THREE.Vector2( 1, 1 );
  16610. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  16611. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  16612. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16613. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16614. this.generateMipmaps = true;
  16615. this.shareDepthFrom = null;
  16616. };
  16617. THREE.WebGLRenderTarget.prototype = {
  16618. constructor: THREE.WebGLRenderTarget,
  16619. setSize: function ( width, height ) {
  16620. this.width = width;
  16621. this.height = height;
  16622. },
  16623. clone: function () {
  16624. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  16625. tmp.wrapS = this.wrapS;
  16626. tmp.wrapT = this.wrapT;
  16627. tmp.magFilter = this.magFilter;
  16628. tmp.minFilter = this.minFilter;
  16629. tmp.anisotropy = this.anisotropy;
  16630. tmp.offset.copy( this.offset );
  16631. tmp.repeat.copy( this.repeat );
  16632. tmp.format = this.format;
  16633. tmp.type = this.type;
  16634. tmp.depthBuffer = this.depthBuffer;
  16635. tmp.stencilBuffer = this.stencilBuffer;
  16636. tmp.generateMipmaps = this.generateMipmaps;
  16637. tmp.shareDepthFrom = this.shareDepthFrom;
  16638. return tmp;
  16639. },
  16640. dispose: function () {
  16641. this.dispatchEvent( { type: 'dispose' } );
  16642. }
  16643. };
  16644. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16645. /**
  16646. * @author alteredq / http://alteredqualia.com
  16647. */
  16648. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16649. THREE.WebGLRenderTarget.call( this, width, height, options );
  16650. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16651. };
  16652. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16653. THREE.WebGLProgram = ( function () {
  16654. var programIdCount = 0;
  16655. var generateDefines = function ( defines ) {
  16656. var value, chunk, chunks = [];
  16657. for ( var d in defines ) {
  16658. value = defines[ d ];
  16659. if ( value === false ) continue;
  16660. chunk = "#define " + d + " " + value;
  16661. chunks.push( chunk );
  16662. }
  16663. return chunks.join( "\n" );
  16664. };
  16665. var cacheUniformLocations = function ( gl, program, identifiers ) {
  16666. var uniforms = {};
  16667. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16668. var id = identifiers[ i ];
  16669. uniforms[ id ] = gl.getUniformLocation( program, id );
  16670. }
  16671. return uniforms;
  16672. };
  16673. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  16674. var attributes = {};
  16675. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16676. var id = identifiers[ i ];
  16677. attributes[ id ] = gl.getAttribLocation( program, id );
  16678. }
  16679. return attributes;
  16680. };
  16681. return function ( renderer, code, material, parameters ) {
  16682. var _this = renderer;
  16683. var _gl = _this.context;
  16684. var fragmentShader = material.fragmentShader;
  16685. var vertexShader = material.vertexShader;
  16686. var uniforms = material.uniforms;
  16687. var attributes = material.attributes;
  16688. var defines = material.defines;
  16689. var index0AttributeName = material.index0AttributeName;
  16690. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  16691. // programs with morphTargets displace position out of attribute 0
  16692. index0AttributeName = 'position';
  16693. }
  16694. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  16695. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  16696. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  16697. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  16698. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  16699. }
  16700. // console.log( "building new program " );
  16701. //
  16702. var customDefines = generateDefines( defines );
  16703. //
  16704. var program = _gl.createProgram();
  16705. var prefix_vertex, prefix_fragment;
  16706. if ( material instanceof THREE.RawShaderMaterial ) {
  16707. prefix_vertex = '';
  16708. prefix_fragment = '';
  16709. } else {
  16710. prefix_vertex = [
  16711. "precision " + parameters.precision + " float;",
  16712. "precision " + parameters.precision + " int;",
  16713. customDefines,
  16714. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  16715. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16716. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16717. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16718. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16719. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16720. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16721. "#define MAX_SHADOWS " + parameters.maxShadows,
  16722. "#define MAX_BONES " + parameters.maxBones,
  16723. parameters.map ? "#define USE_MAP" : "",
  16724. parameters.envMap ? "#define USE_ENVMAP" : "",
  16725. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16726. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16727. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16728. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16729. parameters.vertexColors ? "#define USE_COLOR" : "",
  16730. parameters.skinning ? "#define USE_SKINNING" : "",
  16731. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  16732. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  16733. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  16734. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16735. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16736. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16737. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16738. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16739. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16740. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16741. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  16742. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16743. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16744. "uniform mat4 modelMatrix;",
  16745. "uniform mat4 modelViewMatrix;",
  16746. "uniform mat4 projectionMatrix;",
  16747. "uniform mat4 viewMatrix;",
  16748. "uniform mat3 normalMatrix;",
  16749. "uniform vec3 cameraPosition;",
  16750. "attribute vec3 position;",
  16751. "attribute vec3 normal;",
  16752. "attribute vec2 uv;",
  16753. "attribute vec2 uv2;",
  16754. "#ifdef USE_COLOR",
  16755. " attribute vec3 color;",
  16756. "#endif",
  16757. "#ifdef USE_MORPHTARGETS",
  16758. " attribute vec3 morphTarget0;",
  16759. " attribute vec3 morphTarget1;",
  16760. " attribute vec3 morphTarget2;",
  16761. " attribute vec3 morphTarget3;",
  16762. " #ifdef USE_MORPHNORMALS",
  16763. " attribute vec3 morphNormal0;",
  16764. " attribute vec3 morphNormal1;",
  16765. " attribute vec3 morphNormal2;",
  16766. " attribute vec3 morphNormal3;",
  16767. " #else",
  16768. " attribute vec3 morphTarget4;",
  16769. " attribute vec3 morphTarget5;",
  16770. " attribute vec3 morphTarget6;",
  16771. " attribute vec3 morphTarget7;",
  16772. " #endif",
  16773. "#endif",
  16774. "#ifdef USE_SKINNING",
  16775. " attribute vec4 skinIndex;",
  16776. " attribute vec4 skinWeight;",
  16777. "#endif",
  16778. ""
  16779. ].join( '\n' );
  16780. prefix_fragment = [
  16781. "precision " + parameters.precision + " float;",
  16782. "precision " + parameters.precision + " int;",
  16783. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  16784. customDefines,
  16785. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16786. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16787. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16788. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16789. "#define MAX_SHADOWS " + parameters.maxShadows,
  16790. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  16791. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16792. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16793. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  16794. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  16795. parameters.map ? "#define USE_MAP" : "",
  16796. parameters.envMap ? "#define USE_ENVMAP" : "",
  16797. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16798. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16799. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16800. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16801. parameters.vertexColors ? "#define USE_COLOR" : "",
  16802. parameters.metal ? "#define METAL" : "",
  16803. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16804. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16805. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16806. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16807. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16808. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16809. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16810. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16811. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16812. "uniform mat4 viewMatrix;",
  16813. "uniform vec3 cameraPosition;",
  16814. ""
  16815. ].join( '\n' );
  16816. }
  16817. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  16818. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  16819. _gl.attachShader( program, glVertexShader );
  16820. _gl.attachShader( program, glFragmentShader );
  16821. if ( index0AttributeName !== undefined ) {
  16822. // Force a particular attribute to index 0.
  16823. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  16824. // And, color, for example is often automatically bound to index 0 so disabling it
  16825. _gl.bindAttribLocation( program, 0, index0AttributeName );
  16826. }
  16827. _gl.linkProgram( program );
  16828. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  16829. console.error( 'Could not initialise shader' );
  16830. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  16831. console.error( 'gl.getError()', _gl.getError() );
  16832. }
  16833. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  16834. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  16835. }
  16836. // clean up
  16837. _gl.deleteShader( glVertexShader );
  16838. _gl.deleteShader( glFragmentShader );
  16839. // cache uniform locations
  16840. var identifiers = [
  16841. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  16842. 'morphTargetInfluences'
  16843. ];
  16844. if ( parameters.useVertexTexture ) {
  16845. identifiers.push( 'boneTexture' );
  16846. identifiers.push( 'boneTextureWidth' );
  16847. identifiers.push( 'boneTextureHeight' );
  16848. } else {
  16849. identifiers.push( 'boneGlobalMatrices' );
  16850. }
  16851. if ( parameters.logarithmicDepthBuffer ) {
  16852. identifiers.push('logDepthBufFC');
  16853. }
  16854. for ( var u in uniforms ) {
  16855. identifiers.push( u );
  16856. }
  16857. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  16858. // cache attributes locations
  16859. identifiers = [
  16860. "position", "normal", "uv", "uv2", "tangent", "color",
  16861. "skinIndex", "skinWeight", "lineDistance"
  16862. ];
  16863. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  16864. identifiers.push( "morphTarget" + i );
  16865. }
  16866. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  16867. identifiers.push( "morphNormal" + i );
  16868. }
  16869. for ( var a in attributes ) {
  16870. identifiers.push( a );
  16871. }
  16872. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  16873. //
  16874. this.id = programIdCount ++;
  16875. this.code = code;
  16876. this.usedTimes = 1;
  16877. this.program = program;
  16878. this.vertexShader = glVertexShader;
  16879. this.fragmentShader = glFragmentShader;
  16880. return this;
  16881. };
  16882. } )();
  16883. THREE.WebGLShader = ( function () {
  16884. var addLineNumbers = function ( string ) {
  16885. var lines = string.split( '\n' );
  16886. for ( var i = 0; i < lines.length; i ++ ) {
  16887. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16888. }
  16889. return lines.join( '\n' );
  16890. };
  16891. return function ( gl, type, string ) {
  16892. var shader = gl.createShader( type );
  16893. gl.shaderSource( shader, string );
  16894. gl.compileShader( shader );
  16895. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  16896. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  16897. }
  16898. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  16899. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  16900. console.error( addLineNumbers( string ) );
  16901. }
  16902. return shader;
  16903. };
  16904. } )();
  16905. /**
  16906. * @author mrdoob / http://mrdoob.com/
  16907. */
  16908. THREE.RenderableVertex = function () {
  16909. this.position = new THREE.Vector3();
  16910. this.positionWorld = new THREE.Vector3();
  16911. this.positionScreen = new THREE.Vector4();
  16912. this.visible = true;
  16913. };
  16914. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16915. this.positionWorld.copy( vertex.positionWorld );
  16916. this.positionScreen.copy( vertex.positionScreen );
  16917. };
  16918. /**
  16919. * @author mrdoob / http://mrdoob.com/
  16920. */
  16921. THREE.RenderableFace = function () {
  16922. this.id = 0;
  16923. this.v1 = new THREE.RenderableVertex();
  16924. this.v2 = new THREE.RenderableVertex();
  16925. this.v3 = new THREE.RenderableVertex();
  16926. this.normalModel = new THREE.Vector3();
  16927. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16928. this.vertexNormalsLength = 0;
  16929. this.color = null;
  16930. this.material = null;
  16931. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  16932. this.z = 0;
  16933. };
  16934. /**
  16935. * @author mrdoob / http://mrdoob.com/
  16936. */
  16937. THREE.RenderableObject = function () {
  16938. this.id = 0;
  16939. this.object = null;
  16940. this.z = 0;
  16941. };
  16942. /**
  16943. * @author mrdoob / http://mrdoob.com/
  16944. */
  16945. THREE.RenderableSprite = function () {
  16946. this.id = 0;
  16947. this.object = null;
  16948. this.x = 0;
  16949. this.y = 0;
  16950. this.z = 0;
  16951. this.rotation = 0;
  16952. this.scale = new THREE.Vector2();
  16953. this.material = null;
  16954. };
  16955. /**
  16956. * @author mrdoob / http://mrdoob.com/
  16957. */
  16958. THREE.RenderableLine = function () {
  16959. this.id = 0;
  16960. this.v1 = new THREE.RenderableVertex();
  16961. this.v2 = new THREE.RenderableVertex();
  16962. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16963. this.material = null;
  16964. this.z = 0;
  16965. };
  16966. /**
  16967. * @author mrdoob / http://mrdoob.com/
  16968. * @author alteredq / http://alteredqualia.com/
  16969. */
  16970. THREE.GeometryUtils = {
  16971. // Merge two geometries or geometry and geometry from object (using object's transform)
  16972. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  16973. console.warn( 'DEPRECATED: GeometryUtils\'s .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  16974. var matrix;
  16975. if ( geometry2 instanceof THREE.Mesh ) {
  16976. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  16977. matrix = geometry2.matrix;
  16978. geometry2 = geometry2.geometry;
  16979. }
  16980. geometry1.merge( geometry2, matrix, materialIndexOffset );
  16981. },
  16982. // Get random point in triangle (via barycentric coordinates)
  16983. // (uniform distribution)
  16984. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16985. randomPointInTriangle: function () {
  16986. var vector = new THREE.Vector3();
  16987. return function ( vectorA, vectorB, vectorC ) {
  16988. var point = new THREE.Vector3();
  16989. var a = THREE.Math.random16();
  16990. var b = THREE.Math.random16();
  16991. if ( ( a + b ) > 1 ) {
  16992. a = 1 - a;
  16993. b = 1 - b;
  16994. }
  16995. var c = 1 - a - b;
  16996. point.copy( vectorA );
  16997. point.multiplyScalar( a );
  16998. vector.copy( vectorB );
  16999. vector.multiplyScalar( b );
  17000. point.add( vector );
  17001. vector.copy( vectorC );
  17002. vector.multiplyScalar( c );
  17003. point.add( vector );
  17004. return point;
  17005. };
  17006. }(),
  17007. // Get random point in face (triangle / quad)
  17008. // (uniform distribution)
  17009. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  17010. var vA, vB, vC, vD;
  17011. vA = geometry.vertices[ face.a ];
  17012. vB = geometry.vertices[ face.b ];
  17013. vC = geometry.vertices[ face.c ];
  17014. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  17015. },
  17016. // Get uniformly distributed random points in mesh
  17017. // - create array with cumulative sums of face areas
  17018. // - pick random number from 0 to total area
  17019. // - find corresponding place in area array by binary search
  17020. // - get random point in face
  17021. randomPointsInGeometry: function ( geometry, n ) {
  17022. var face, i,
  17023. faces = geometry.faces,
  17024. vertices = geometry.vertices,
  17025. il = faces.length,
  17026. totalArea = 0,
  17027. cumulativeAreas = [],
  17028. vA, vB, vC, vD;
  17029. // precompute face areas
  17030. for ( i = 0; i < il; i ++ ) {
  17031. face = faces[ i ];
  17032. vA = vertices[ face.a ];
  17033. vB = vertices[ face.b ];
  17034. vC = vertices[ face.c ];
  17035. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  17036. totalArea += face._area;
  17037. cumulativeAreas[ i ] = totalArea;
  17038. }
  17039. // binary search cumulative areas array
  17040. function binarySearchIndices( value ) {
  17041. function binarySearch( start, end ) {
  17042. // return closest larger index
  17043. // if exact number is not found
  17044. if ( end < start )
  17045. return start;
  17046. var mid = start + Math.floor( ( end - start ) / 2 );
  17047. if ( cumulativeAreas[ mid ] > value ) {
  17048. return binarySearch( start, mid - 1 );
  17049. } else if ( cumulativeAreas[ mid ] < value ) {
  17050. return binarySearch( mid + 1, end );
  17051. } else {
  17052. return mid;
  17053. }
  17054. }
  17055. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  17056. return result;
  17057. }
  17058. // pick random face weighted by face area
  17059. var r, index,
  17060. result = [];
  17061. var stats = {};
  17062. for ( i = 0; i < n; i ++ ) {
  17063. r = THREE.Math.random16() * totalArea;
  17064. index = binarySearchIndices( r );
  17065. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  17066. if ( ! stats[ index ] ) {
  17067. stats[ index ] = 1;
  17068. } else {
  17069. stats[ index ] += 1;
  17070. }
  17071. }
  17072. return result;
  17073. },
  17074. // Get triangle area (half of parallelogram)
  17075. // http://mathworld.wolfram.com/TriangleArea.html
  17076. triangleArea: function () {
  17077. var vector1 = new THREE.Vector3();
  17078. var vector2 = new THREE.Vector3();
  17079. return function ( vectorA, vectorB, vectorC ) {
  17080. vector1.subVectors( vectorB, vectorA );
  17081. vector2.subVectors( vectorC, vectorA );
  17082. vector1.cross( vector2 );
  17083. return 0.5 * vector1.length();
  17084. };
  17085. }(),
  17086. // Center geometry so that 0,0,0 is in center of bounding box
  17087. center: function ( geometry ) {
  17088. geometry.computeBoundingBox();
  17089. var bb = geometry.boundingBox;
  17090. var offset = new THREE.Vector3();
  17091. offset.addVectors( bb.min, bb.max );
  17092. offset.multiplyScalar( -0.5 );
  17093. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  17094. geometry.computeBoundingBox();
  17095. return offset;
  17096. }
  17097. };
  17098. /**
  17099. * @author alteredq / http://alteredqualia.com/
  17100. * @author mrdoob / http://mrdoob.com/
  17101. */
  17102. THREE.ImageUtils = {
  17103. crossOrigin: undefined,
  17104. loadTexture: function ( url, mapping, onLoad, onError ) {
  17105. var loader = new THREE.ImageLoader();
  17106. loader.crossOrigin = this.crossOrigin;
  17107. var texture = new THREE.Texture( undefined, mapping );
  17108. var image = loader.load( url, function () {
  17109. texture.needsUpdate = true;
  17110. if ( onLoad ) onLoad( texture );
  17111. }, undefined, function ( event ) {
  17112. if ( onError ) onError( event );
  17113. } );
  17114. texture.image = image;
  17115. texture.sourceFile = url;
  17116. return texture;
  17117. },
  17118. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  17119. var texture = new THREE.CompressedTexture();
  17120. texture.mapping = mapping;
  17121. var request = new XMLHttpRequest();
  17122. request.onload = function () {
  17123. var buffer = request.response;
  17124. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  17125. texture.format = dds.format;
  17126. texture.mipmaps = dds.mipmaps;
  17127. texture.image.width = dds.width;
  17128. texture.image.height = dds.height;
  17129. // gl.generateMipmap fails for compressed textures
  17130. // mipmaps must be embedded in the DDS file
  17131. // or texture filters must not use mipmapping
  17132. texture.generateMipmaps = false;
  17133. texture.needsUpdate = true;
  17134. if ( onLoad ) onLoad( texture );
  17135. }
  17136. request.onerror = onError;
  17137. request.open( 'GET', url, true );
  17138. request.responseType = "arraybuffer";
  17139. request.send( null );
  17140. return texture;
  17141. },
  17142. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  17143. var images = [];
  17144. images.loadCount = 0;
  17145. var texture = new THREE.Texture();
  17146. texture.image = images;
  17147. if ( mapping !== undefined ) texture.mapping = mapping;
  17148. // no flipping needed for cube textures
  17149. texture.flipY = false;
  17150. for ( var i = 0, il = array.length; i < il; ++ i ) {
  17151. var cubeImage = new Image();
  17152. images[ i ] = cubeImage;
  17153. cubeImage.onload = function () {
  17154. images.loadCount += 1;
  17155. if ( images.loadCount === 6 ) {
  17156. texture.needsUpdate = true;
  17157. if ( onLoad ) onLoad( texture );
  17158. }
  17159. };
  17160. cubeImage.onerror = onError;
  17161. cubeImage.crossOrigin = this.crossOrigin;
  17162. cubeImage.src = array[ i ];
  17163. }
  17164. return texture;
  17165. },
  17166. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  17167. var images = [];
  17168. images.loadCount = 0;
  17169. var texture = new THREE.CompressedTexture();
  17170. texture.image = images;
  17171. if ( mapping !== undefined ) texture.mapping = mapping;
  17172. // no flipping for cube textures
  17173. // (also flipping doesn't work for compressed textures )
  17174. texture.flipY = false;
  17175. // can't generate mipmaps for compressed textures
  17176. // mips must be embedded in DDS files
  17177. texture.generateMipmaps = false;
  17178. var generateCubeFaceCallback = function ( rq, img ) {
  17179. return function () {
  17180. var buffer = rq.response;
  17181. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  17182. img.format = dds.format;
  17183. img.mipmaps = dds.mipmaps;
  17184. img.width = dds.width;
  17185. img.height = dds.height;
  17186. images.loadCount += 1;
  17187. if ( images.loadCount === 6 ) {
  17188. texture.format = dds.format;
  17189. texture.needsUpdate = true;
  17190. if ( onLoad ) onLoad( texture );
  17191. }
  17192. }
  17193. }
  17194. // compressed cubemap textures as 6 separate DDS files
  17195. if ( array instanceof Array ) {
  17196. for ( var i = 0, il = array.length; i < il; ++ i ) {
  17197. var cubeImage = {};
  17198. images[ i ] = cubeImage;
  17199. var request = new XMLHttpRequest();
  17200. request.onload = generateCubeFaceCallback( request, cubeImage );
  17201. request.onerror = onError;
  17202. var url = array[ i ];
  17203. request.open( 'GET', url, true );
  17204. request.responseType = "arraybuffer";
  17205. request.send( null );
  17206. }
  17207. // compressed cubemap texture stored in a single DDS file
  17208. } else {
  17209. var url = array;
  17210. var request = new XMLHttpRequest();
  17211. request.onload = function( ) {
  17212. var buffer = request.response;
  17213. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  17214. if ( dds.isCubemap ) {
  17215. var faces = dds.mipmaps.length / dds.mipmapCount;
  17216. for ( var f = 0; f < faces; f ++ ) {
  17217. images[ f ] = { mipmaps : [] };
  17218. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  17219. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  17220. images[ f ].format = dds.format;
  17221. images[ f ].width = dds.width;
  17222. images[ f ].height = dds.height;
  17223. }
  17224. }
  17225. texture.format = dds.format;
  17226. texture.needsUpdate = true;
  17227. if ( onLoad ) onLoad( texture );
  17228. }
  17229. }
  17230. request.onerror = onError;
  17231. request.open( 'GET', url, true );
  17232. request.responseType = "arraybuffer";
  17233. request.send( null );
  17234. }
  17235. return texture;
  17236. },
  17237. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  17238. var images = [];
  17239. images.loadCount = 0;
  17240. var texture = new THREE.CompressedTexture();
  17241. texture.image = images;
  17242. if ( mapping !== undefined ) texture.mapping = mapping;
  17243. // no flipping for cube textures
  17244. // (also flipping doesn't work for compressed textures )
  17245. texture.flipY = false;
  17246. // can't generate mipmaps for compressed textures
  17247. // mips must be embedded in DDS files
  17248. texture.generateMipmaps = false;
  17249. {
  17250. var request = new XMLHttpRequest();
  17251. request.onload = function( ) {
  17252. var buffer = request.response;
  17253. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  17254. if ( dds.isCubemap ) {
  17255. var faces = dds.mipmaps.length / dds.mipmapCount;
  17256. for ( var f = 0; f < faces; f ++ ) {
  17257. images[ f ] = { mipmaps : [] };
  17258. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  17259. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  17260. images[ f ].format = dds.format;
  17261. images[ f ].width = dds.width;
  17262. images[ f ].height = dds.height;
  17263. }
  17264. }
  17265. } else {
  17266. texture.image.width = dds.width;
  17267. texture.image.height = dds.height;
  17268. texture.mipmaps = dds.mipmaps;
  17269. }
  17270. texture.format = dds.format;
  17271. texture.needsUpdate = true;
  17272. if ( onLoad ) onLoad( texture );
  17273. }
  17274. request.onerror = onError;
  17275. request.open( 'GET', url, true );
  17276. request.responseType = "arraybuffer";
  17277. request.send( null );
  17278. }
  17279. return texture;
  17280. },
  17281. parseDDS: function ( buffer, loadMipmaps ) {
  17282. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  17283. // Adapted from @toji's DDS utils
  17284. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  17285. // All values and structures referenced from:
  17286. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  17287. var DDS_MAGIC = 0x20534444;
  17288. var DDSD_CAPS = 0x1,
  17289. DDSD_HEIGHT = 0x2,
  17290. DDSD_WIDTH = 0x4,
  17291. DDSD_PITCH = 0x8,
  17292. DDSD_PIXELFORMAT = 0x1000,
  17293. DDSD_MIPMAPCOUNT = 0x20000,
  17294. DDSD_LINEARSIZE = 0x80000,
  17295. DDSD_DEPTH = 0x800000;
  17296. var DDSCAPS_COMPLEX = 0x8,
  17297. DDSCAPS_MIPMAP = 0x400000,
  17298. DDSCAPS_TEXTURE = 0x1000;
  17299. var DDSCAPS2_CUBEMAP = 0x200,
  17300. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  17301. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  17302. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  17303. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  17304. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  17305. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  17306. DDSCAPS2_VOLUME = 0x200000;
  17307. var DDPF_ALPHAPIXELS = 0x1,
  17308. DDPF_ALPHA = 0x2,
  17309. DDPF_FOURCC = 0x4,
  17310. DDPF_RGB = 0x40,
  17311. DDPF_YUV = 0x200,
  17312. DDPF_LUMINANCE = 0x20000;
  17313. function fourCCToInt32( value ) {
  17314. return value.charCodeAt(0) +
  17315. (value.charCodeAt(1) << 8) +
  17316. (value.charCodeAt(2) << 16) +
  17317. (value.charCodeAt(3) << 24);
  17318. }
  17319. function int32ToFourCC( value ) {
  17320. return String.fromCharCode(
  17321. value & 0xff,
  17322. (value >> 8) & 0xff,
  17323. (value >> 16) & 0xff,
  17324. (value >> 24) & 0xff
  17325. );
  17326. }
  17327. function loadARGBMip( buffer, dataOffset, width, height ) {
  17328. var dataLength = width*height*4;
  17329. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  17330. var byteArray = new Uint8Array( dataLength );
  17331. var dst = 0;
  17332. var src = 0;
  17333. for ( var y = 0; y < height; y++ ) {
  17334. for ( var x = 0; x < width; x++ ) {
  17335. var b = srcBuffer[src]; src++;
  17336. var g = srcBuffer[src]; src++;
  17337. var r = srcBuffer[src]; src++;
  17338. var a = srcBuffer[src]; src++;
  17339. byteArray[dst] = r; dst++; //r
  17340. byteArray[dst] = g; dst++; //g
  17341. byteArray[dst] = b; dst++; //b
  17342. byteArray[dst] = a; dst++; //a
  17343. }
  17344. }
  17345. return byteArray;
  17346. }
  17347. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  17348. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  17349. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  17350. var headerLengthInt = 31; // The header length in 32 bit ints
  17351. // Offsets into the header array
  17352. var off_magic = 0;
  17353. var off_size = 1;
  17354. var off_flags = 2;
  17355. var off_height = 3;
  17356. var off_width = 4;
  17357. var off_mipmapCount = 7;
  17358. var off_pfFlags = 20;
  17359. var off_pfFourCC = 21;
  17360. var off_RGBBitCount = 22;
  17361. var off_RBitMask = 23;
  17362. var off_GBitMask = 24;
  17363. var off_BBitMask = 25;
  17364. var off_ABitMask = 26;
  17365. var off_caps = 27;
  17366. var off_caps2 = 28;
  17367. var off_caps3 = 29;
  17368. var off_caps4 = 30;
  17369. // Parse header
  17370. var header = new Int32Array( buffer, 0, headerLengthInt );
  17371. if ( header[ off_magic ] !== DDS_MAGIC ) {
  17372. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  17373. return dds;
  17374. }
  17375. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  17376. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  17377. return dds;
  17378. }
  17379. var blockBytes;
  17380. var fourCC = header[ off_pfFourCC ];
  17381. var isRGBAUncompressed = false;
  17382. switch ( fourCC ) {
  17383. case FOURCC_DXT1:
  17384. blockBytes = 8;
  17385. dds.format = THREE.RGB_S3TC_DXT1_Format;
  17386. break;
  17387. case FOURCC_DXT3:
  17388. blockBytes = 16;
  17389. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  17390. break;
  17391. case FOURCC_DXT5:
  17392. blockBytes = 16;
  17393. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  17394. break;
  17395. default:
  17396. if( header[off_RGBBitCount] ==32
  17397. && header[off_RBitMask]&0xff0000
  17398. && header[off_GBitMask]&0xff00
  17399. && header[off_BBitMask]&0xff
  17400. && header[off_ABitMask]&0xff000000 ) {
  17401. isRGBAUncompressed = true;
  17402. blockBytes = 64;
  17403. dds.format = THREE.RGBAFormat;
  17404. } else {
  17405. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  17406. return dds;
  17407. }
  17408. }
  17409. dds.mipmapCount = 1;
  17410. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  17411. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  17412. }
  17413. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  17414. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  17415. dds.width = header[ off_width ];
  17416. dds.height = header[ off_height ];
  17417. var dataOffset = header[ off_size ] + 4;
  17418. // Extract mipmaps buffers
  17419. var width = dds.width;
  17420. var height = dds.height;
  17421. var faces = dds.isCubemap ? 6 : 1;
  17422. for ( var face = 0; face < faces; face ++ ) {
  17423. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  17424. if( isRGBAUncompressed ) {
  17425. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  17426. var dataLength = byteArray.length;
  17427. } else {
  17428. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  17429. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  17430. }
  17431. var mipmap = { "data": byteArray, "width": width, "height": height };
  17432. dds.mipmaps.push( mipmap );
  17433. dataOffset += dataLength;
  17434. width = Math.max( width * 0.5, 1 );
  17435. height = Math.max( height * 0.5, 1 );
  17436. }
  17437. width = dds.width;
  17438. height = dds.height;
  17439. }
  17440. return dds;
  17441. },
  17442. getNormalMap: function ( image, depth ) {
  17443. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  17444. var cross = function ( a, b ) {
  17445. 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 ] ];
  17446. }
  17447. var subtract = function ( a, b ) {
  17448. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  17449. }
  17450. var normalize = function ( a ) {
  17451. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  17452. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  17453. }
  17454. depth = depth | 1;
  17455. var width = image.width;
  17456. var height = image.height;
  17457. var canvas = document.createElement( 'canvas' );
  17458. canvas.width = width;
  17459. canvas.height = height;
  17460. var context = canvas.getContext( '2d' );
  17461. context.drawImage( image, 0, 0 );
  17462. var data = context.getImageData( 0, 0, width, height ).data;
  17463. var imageData = context.createImageData( width, height );
  17464. var output = imageData.data;
  17465. for ( var x = 0; x < width; x ++ ) {
  17466. for ( var y = 0; y < height; y ++ ) {
  17467. var ly = y - 1 < 0 ? 0 : y - 1;
  17468. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  17469. var lx = x - 1 < 0 ? 0 : x - 1;
  17470. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  17471. var points = [];
  17472. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  17473. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  17474. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  17475. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  17476. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  17477. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  17478. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  17479. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  17480. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  17481. var normals = [];
  17482. var num_points = points.length;
  17483. for ( var i = 0; i < num_points; i ++ ) {
  17484. var v1 = points[ i ];
  17485. var v2 = points[ ( i + 1 ) % num_points ];
  17486. v1 = subtract( v1, origin );
  17487. v2 = subtract( v2, origin );
  17488. normals.push( normalize( cross( v1, v2 ) ) );
  17489. }
  17490. var normal = [ 0, 0, 0 ];
  17491. for ( var i = 0; i < normals.length; i ++ ) {
  17492. normal[ 0 ] += normals[ i ][ 0 ];
  17493. normal[ 1 ] += normals[ i ][ 1 ];
  17494. normal[ 2 ] += normals[ i ][ 2 ];
  17495. }
  17496. normal[ 0 ] /= normals.length;
  17497. normal[ 1 ] /= normals.length;
  17498. normal[ 2 ] /= normals.length;
  17499. var idx = ( y * width + x ) * 4;
  17500. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  17501. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  17502. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  17503. output[ idx + 3 ] = 255;
  17504. }
  17505. }
  17506. context.putImageData( imageData, 0, 0 );
  17507. return canvas;
  17508. },
  17509. generateDataTexture: function ( width, height, color ) {
  17510. var size = width * height;
  17511. var data = new Uint8Array( 3 * size );
  17512. var r = Math.floor( color.r * 255 );
  17513. var g = Math.floor( color.g * 255 );
  17514. var b = Math.floor( color.b * 255 );
  17515. for ( var i = 0; i < size; i ++ ) {
  17516. data[ i * 3 ] = r;
  17517. data[ i * 3 + 1 ] = g;
  17518. data[ i * 3 + 2 ] = b;
  17519. }
  17520. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  17521. texture.needsUpdate = true;
  17522. return texture;
  17523. }
  17524. };
  17525. /**
  17526. * @author alteredq / http://alteredqualia.com/
  17527. */
  17528. THREE.SceneUtils = {
  17529. createMultiMaterialObject: function ( geometry, materials ) {
  17530. var group = new THREE.Object3D();
  17531. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  17532. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  17533. }
  17534. return group;
  17535. },
  17536. detach : function ( child, parent, scene ) {
  17537. child.applyMatrix( parent.matrixWorld );
  17538. parent.remove( child );
  17539. scene.add( child );
  17540. },
  17541. attach: function ( child, scene, parent ) {
  17542. var matrixWorldInverse = new THREE.Matrix4();
  17543. matrixWorldInverse.getInverse( parent.matrixWorld );
  17544. child.applyMatrix( matrixWorldInverse );
  17545. scene.remove( child );
  17546. parent.add( child );
  17547. }
  17548. };
  17549. /**
  17550. * @author zz85 / http://www.lab4games.net/zz85/blog
  17551. * @author alteredq / http://alteredqualia.com/
  17552. *
  17553. * For Text operations in three.js (See TextGeometry)
  17554. *
  17555. * It uses techniques used in:
  17556. *
  17557. * typeface.js and canvastext
  17558. * For converting fonts and rendering with javascript
  17559. * http://typeface.neocracy.org
  17560. *
  17561. * Triangulation ported from AS3
  17562. * Simple Polygon Triangulation
  17563. * http://actionsnippet.com/?p=1462
  17564. *
  17565. * A Method to triangulate shapes with holes
  17566. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  17567. *
  17568. */
  17569. THREE.FontUtils = {
  17570. faces : {},
  17571. // Just for now. face[weight][style]
  17572. face : "helvetiker",
  17573. weight: "normal",
  17574. style : "normal",
  17575. size : 150,
  17576. divisions : 10,
  17577. getFace : function() {
  17578. return this.faces[ this.face ][ this.weight ][ this.style ];
  17579. },
  17580. loadFace : function( data ) {
  17581. var family = data.familyName.toLowerCase();
  17582. var ThreeFont = this;
  17583. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  17584. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  17585. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17586. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17587. return data;
  17588. },
  17589. drawText : function( text ) {
  17590. var characterPts = [], allPts = [];
  17591. // RenderText
  17592. var i, p,
  17593. face = this.getFace(),
  17594. scale = this.size / face.resolution,
  17595. offset = 0,
  17596. chars = String( text ).split( '' ),
  17597. length = chars.length;
  17598. var fontPaths = [];
  17599. for ( i = 0; i < length; i ++ ) {
  17600. var path = new THREE.Path();
  17601. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  17602. offset += ret.offset;
  17603. fontPaths.push( ret.path );
  17604. }
  17605. // get the width
  17606. var width = offset / 2;
  17607. //
  17608. // for ( p = 0; p < allPts.length; p++ ) {
  17609. //
  17610. // allPts[ p ].x -= width;
  17611. //
  17612. // }
  17613. //var extract = this.extractPoints( allPts, characterPts );
  17614. //extract.contour = allPts;
  17615. //extract.paths = fontPaths;
  17616. //extract.offset = width;
  17617. return { paths : fontPaths, offset : width };
  17618. },
  17619. extractGlyphPoints : function( c, face, scale, offset, path ) {
  17620. var pts = [];
  17621. var i, i2, divisions,
  17622. outline, action, length,
  17623. scaleX, scaleY,
  17624. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  17625. laste,
  17626. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  17627. if ( !glyph ) return;
  17628. if ( glyph.o ) {
  17629. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  17630. length = outline.length;
  17631. scaleX = scale;
  17632. scaleY = scale;
  17633. for ( i = 0; i < length; ) {
  17634. action = outline[ i ++ ];
  17635. //console.log( action );
  17636. switch( action ) {
  17637. case 'm':
  17638. // Move To
  17639. x = outline[ i++ ] * scaleX + offset;
  17640. y = outline[ i++ ] * scaleY;
  17641. path.moveTo( x, y );
  17642. break;
  17643. case 'l':
  17644. // Line To
  17645. x = outline[ i++ ] * scaleX + offset;
  17646. y = outline[ i++ ] * scaleY;
  17647. path.lineTo(x,y);
  17648. break;
  17649. case 'q':
  17650. // QuadraticCurveTo
  17651. cpx = outline[ i++ ] * scaleX + offset;
  17652. cpy = outline[ i++ ] * scaleY;
  17653. cpx1 = outline[ i++ ] * scaleX + offset;
  17654. cpy1 = outline[ i++ ] * scaleY;
  17655. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  17656. laste = pts[ pts.length - 1 ];
  17657. if ( laste ) {
  17658. cpx0 = laste.x;
  17659. cpy0 = laste.y;
  17660. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17661. var t = i2 / divisions;
  17662. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17663. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17664. }
  17665. }
  17666. break;
  17667. case 'b':
  17668. // Cubic Bezier Curve
  17669. cpx = outline[ i++ ] * scaleX + offset;
  17670. cpy = outline[ i++ ] * scaleY;
  17671. cpx1 = outline[ i++ ] * scaleX + offset;
  17672. cpy1 = outline[ i++ ] * -scaleY;
  17673. cpx2 = outline[ i++ ] * scaleX + offset;
  17674. cpy2 = outline[ i++ ] * -scaleY;
  17675. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  17676. laste = pts[ pts.length - 1 ];
  17677. if ( laste ) {
  17678. cpx0 = laste.x;
  17679. cpy0 = laste.y;
  17680. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17681. var t = i2 / divisions;
  17682. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17683. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17684. }
  17685. }
  17686. break;
  17687. }
  17688. }
  17689. }
  17690. return { offset: glyph.ha*scale, path:path};
  17691. }
  17692. };
  17693. THREE.FontUtils.generateShapes = function( text, parameters ) {
  17694. // Parameters
  17695. parameters = parameters || {};
  17696. var size = parameters.size !== undefined ? parameters.size : 100;
  17697. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  17698. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  17699. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  17700. var style = parameters.style !== undefined ? parameters.style : "normal";
  17701. THREE.FontUtils.size = size;
  17702. THREE.FontUtils.divisions = curveSegments;
  17703. THREE.FontUtils.face = font;
  17704. THREE.FontUtils.weight = weight;
  17705. THREE.FontUtils.style = style;
  17706. // Get a Font data json object
  17707. var data = THREE.FontUtils.drawText( text );
  17708. var paths = data.paths;
  17709. var shapes = [];
  17710. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  17711. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  17712. }
  17713. return shapes;
  17714. };
  17715. /**
  17716. * This code is a quick port of code written in C++ which was submitted to
  17717. * flipcode.com by John W. Ratcliff // July 22, 2000
  17718. * See original code and more information here:
  17719. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17720. *
  17721. * ported to actionscript by Zevan Rosser
  17722. * www.actionsnippet.com
  17723. *
  17724. * ported to javascript by Joshua Koo
  17725. * http://www.lab4games.net/zz85/blog
  17726. *
  17727. */
  17728. ( function( namespace ) {
  17729. var EPSILON = 0.0000000001;
  17730. // takes in an contour array and returns
  17731. var process = function( contour, indices ) {
  17732. var n = contour.length;
  17733. if ( n < 3 ) return null;
  17734. var result = [],
  17735. verts = [],
  17736. vertIndices = [];
  17737. /* we want a counter-clockwise polygon in verts */
  17738. var u, v, w;
  17739. if ( area( contour ) > 0.0 ) {
  17740. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  17741. } else {
  17742. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  17743. }
  17744. var nv = n;
  17745. /* remove nv - 2 vertices, creating 1 triangle every time */
  17746. var count = 2 * nv; /* error detection */
  17747. for( v = nv - 1; nv > 2; ) {
  17748. /* if we loop, it is probably a non-simple polygon */
  17749. if ( ( count-- ) <= 0 ) {
  17750. //** Triangulate: ERROR - probable bad polygon!
  17751. //throw ( "Warning, unable to triangulate polygon!" );
  17752. //return null;
  17753. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17754. console.log( "Warning, unable to triangulate polygon!" );
  17755. if ( indices ) return vertIndices;
  17756. return result;
  17757. }
  17758. /* three consecutive vertices in current polygon, <u,v,w> */
  17759. u = v; if ( nv <= u ) u = 0; /* previous */
  17760. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17761. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17762. if ( snip( contour, u, v, w, nv, verts ) ) {
  17763. var a, b, c, s, t;
  17764. /* true names of the vertices */
  17765. a = verts[ u ];
  17766. b = verts[ v ];
  17767. c = verts[ w ];
  17768. /* output Triangle */
  17769. result.push( [ contour[ a ],
  17770. contour[ b ],
  17771. contour[ c ] ] );
  17772. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17773. /* remove v from the remaining polygon */
  17774. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  17775. verts[ s ] = verts[ t ];
  17776. }
  17777. nv--;
  17778. /* reset error detection counter */
  17779. count = 2 * nv;
  17780. }
  17781. }
  17782. if ( indices ) return vertIndices;
  17783. return result;
  17784. };
  17785. // calculate area of the contour polygon
  17786. var area = function ( contour ) {
  17787. var n = contour.length;
  17788. var a = 0.0;
  17789. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  17790. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17791. }
  17792. return a * 0.5;
  17793. };
  17794. var snip = function ( contour, u, v, w, n, verts ) {
  17795. var p;
  17796. var ax, ay, bx, by;
  17797. var cx, cy, px, py;
  17798. ax = contour[ verts[ u ] ].x;
  17799. ay = contour[ verts[ u ] ].y;
  17800. bx = contour[ verts[ v ] ].x;
  17801. by = contour[ verts[ v ] ].y;
  17802. cx = contour[ verts[ w ] ].x;
  17803. cy = contour[ verts[ w ] ].y;
  17804. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  17805. var aX, aY, bX, bY, cX, cY;
  17806. var apx, apy, bpx, bpy, cpx, cpy;
  17807. var cCROSSap, bCROSScp, aCROSSbp;
  17808. aX = cx - bx; aY = cy - by;
  17809. bX = ax - cx; bY = ay - cy;
  17810. cX = bx - ax; cY = by - ay;
  17811. for ( p = 0; p < n; p++ ) {
  17812. px = contour[ verts[ p ] ].x
  17813. py = contour[ verts[ p ] ].y
  17814. if ( ( (px === ax) && (py === ay) ) ||
  17815. ( (px === bx) && (py === by) ) ||
  17816. ( (px === cx) && (py === cy) ) ) continue;
  17817. apx = px - ax; apy = py - ay;
  17818. bpx = px - bx; bpy = py - by;
  17819. cpx = px - cx; cpy = py - cy;
  17820. // see if p is inside triangle abc
  17821. aCROSSbp = aX*bpy - aY*bpx;
  17822. cCROSSap = cX*apy - cY*apx;
  17823. bCROSScp = bX*cpy - bY*cpx;
  17824. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  17825. }
  17826. return true;
  17827. };
  17828. namespace.Triangulate = process;
  17829. namespace.Triangulate.area = area;
  17830. return namespace;
  17831. })(THREE.FontUtils);
  17832. // To use the typeface.js face files, hook up the API
  17833. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  17834. THREE.typeface_js = self._typeface_js;
  17835. /**
  17836. * @author zz85 / http://www.lab4games.net/zz85/blog
  17837. * Extensible curve object
  17838. *
  17839. * Some common of Curve methods
  17840. * .getPoint(t), getTangent(t)
  17841. * .getPointAt(u), getTagentAt(u)
  17842. * .getPoints(), .getSpacedPoints()
  17843. * .getLength()
  17844. * .updateArcLengths()
  17845. *
  17846. * This following classes subclasses THREE.Curve:
  17847. *
  17848. * -- 2d classes --
  17849. * THREE.LineCurve
  17850. * THREE.QuadraticBezierCurve
  17851. * THREE.CubicBezierCurve
  17852. * THREE.SplineCurve
  17853. * THREE.ArcCurve
  17854. * THREE.EllipseCurve
  17855. *
  17856. * -- 3d classes --
  17857. * THREE.LineCurve3
  17858. * THREE.QuadraticBezierCurve3
  17859. * THREE.CubicBezierCurve3
  17860. * THREE.SplineCurve3
  17861. * THREE.ClosedSplineCurve3
  17862. *
  17863. * A series of curves can be represented as a THREE.CurvePath
  17864. *
  17865. **/
  17866. /**************************************************************
  17867. * Abstract Curve base class
  17868. **************************************************************/
  17869. THREE.Curve = function () {
  17870. };
  17871. // Virtual base class method to overwrite and implement in subclasses
  17872. // - t [0 .. 1]
  17873. THREE.Curve.prototype.getPoint = function ( t ) {
  17874. console.log( "Warning, getPoint() not implemented!" );
  17875. return null;
  17876. };
  17877. // Get point at relative position in curve according to arc length
  17878. // - u [0 .. 1]
  17879. THREE.Curve.prototype.getPointAt = function ( u ) {
  17880. var t = this.getUtoTmapping( u );
  17881. return this.getPoint( t );
  17882. };
  17883. // Get sequence of points using getPoint( t )
  17884. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17885. if ( !divisions ) divisions = 5;
  17886. var d, pts = [];
  17887. for ( d = 0; d <= divisions; d ++ ) {
  17888. pts.push( this.getPoint( d / divisions ) );
  17889. }
  17890. return pts;
  17891. };
  17892. // Get sequence of points using getPointAt( u )
  17893. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17894. if ( !divisions ) divisions = 5;
  17895. var d, pts = [];
  17896. for ( d = 0; d <= divisions; d ++ ) {
  17897. pts.push( this.getPointAt( d / divisions ) );
  17898. }
  17899. return pts;
  17900. };
  17901. // Get total curve arc length
  17902. THREE.Curve.prototype.getLength = function () {
  17903. var lengths = this.getLengths();
  17904. return lengths[ lengths.length - 1 ];
  17905. };
  17906. // Get list of cumulative segment lengths
  17907. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17908. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17909. if ( this.cacheArcLengths
  17910. && ( this.cacheArcLengths.length == divisions + 1 )
  17911. && !this.needsUpdate) {
  17912. //console.log( "cached", this.cacheArcLengths );
  17913. return this.cacheArcLengths;
  17914. }
  17915. this.needsUpdate = false;
  17916. var cache = [];
  17917. var current, last = this.getPoint( 0 );
  17918. var p, sum = 0;
  17919. cache.push( 0 );
  17920. for ( p = 1; p <= divisions; p ++ ) {
  17921. current = this.getPoint ( p / divisions );
  17922. sum += current.distanceTo( last );
  17923. cache.push( sum );
  17924. last = current;
  17925. }
  17926. this.cacheArcLengths = cache;
  17927. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17928. };
  17929. THREE.Curve.prototype.updateArcLengths = function() {
  17930. this.needsUpdate = true;
  17931. this.getLengths();
  17932. };
  17933. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17934. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17935. var arcLengths = this.getLengths();
  17936. var i = 0, il = arcLengths.length;
  17937. var targetArcLength; // The targeted u distance value to get
  17938. if ( distance ) {
  17939. targetArcLength = distance;
  17940. } else {
  17941. targetArcLength = u * arcLengths[ il - 1 ];
  17942. }
  17943. //var time = Date.now();
  17944. // binary search for the index with largest value smaller than target u distance
  17945. var low = 0, high = il - 1, comparison;
  17946. while ( low <= high ) {
  17947. 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
  17948. comparison = arcLengths[ i ] - targetArcLength;
  17949. if ( comparison < 0 ) {
  17950. low = i + 1;
  17951. continue;
  17952. } else if ( comparison > 0 ) {
  17953. high = i - 1;
  17954. continue;
  17955. } else {
  17956. high = i;
  17957. break;
  17958. // DONE
  17959. }
  17960. }
  17961. i = high;
  17962. //console.log('b' , i, low, high, Date.now()- time);
  17963. if ( arcLengths[ i ] == targetArcLength ) {
  17964. var t = i / ( il - 1 );
  17965. return t;
  17966. }
  17967. // we could get finer grain at lengths, or use simple interpolatation between two points
  17968. var lengthBefore = arcLengths[ i ];
  17969. var lengthAfter = arcLengths[ i + 1 ];
  17970. var segmentLength = lengthAfter - lengthBefore;
  17971. // determine where we are between the 'before' and 'after' points
  17972. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17973. // add that fractional amount to t
  17974. var t = ( i + segmentFraction ) / ( il -1 );
  17975. return t;
  17976. };
  17977. // Returns a unit vector tangent at t
  17978. // In case any sub curve does not implement its tangent derivation,
  17979. // 2 points a small delta apart will be used to find its gradient
  17980. // which seems to give a reasonable approximation
  17981. THREE.Curve.prototype.getTangent = function( t ) {
  17982. var delta = 0.0001;
  17983. var t1 = t - delta;
  17984. var t2 = t + delta;
  17985. // Capping in case of danger
  17986. if ( t1 < 0 ) t1 = 0;
  17987. if ( t2 > 1 ) t2 = 1;
  17988. var pt1 = this.getPoint( t1 );
  17989. var pt2 = this.getPoint( t2 );
  17990. var vec = pt2.clone().sub(pt1);
  17991. return vec.normalize();
  17992. };
  17993. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17994. var t = this.getUtoTmapping( u );
  17995. return this.getTangent( t );
  17996. };
  17997. /**************************************************************
  17998. * Utils
  17999. **************************************************************/
  18000. THREE.Curve.Utils = {
  18001. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  18002. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  18003. },
  18004. // Puay Bing, thanks for helping with this derivative!
  18005. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  18006. return -3 * p0 * (1 - t) * (1 - t) +
  18007. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  18008. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  18009. 3 * t * t * p3;
  18010. },
  18011. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  18012. // To check if my formulas are correct
  18013. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  18014. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  18015. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  18016. var h11 = 3 * t * t - 2 * t; // t3 − t2
  18017. return h00 + h10 + h01 + h11;
  18018. },
  18019. // Catmull-Rom
  18020. interpolate: function( p0, p1, p2, p3, t ) {
  18021. var v0 = ( p2 - p0 ) * 0.5;
  18022. var v1 = ( p3 - p1 ) * 0.5;
  18023. var t2 = t * t;
  18024. var t3 = t * t2;
  18025. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18026. }
  18027. };
  18028. // TODO: Transformation for Curves?
  18029. /**************************************************************
  18030. * 3D Curves
  18031. **************************************************************/
  18032. // A Factory method for creating new curve subclasses
  18033. THREE.Curve.create = function ( constructor, getPointFunc ) {
  18034. constructor.prototype = Object.create( THREE.Curve.prototype );
  18035. constructor.prototype.getPoint = getPointFunc;
  18036. return constructor;
  18037. };
  18038. /**
  18039. * @author zz85 / http://www.lab4games.net/zz85/blog
  18040. *
  18041. **/
  18042. /**************************************************************
  18043. * Curved Path - a curve path is simply a array of connected
  18044. * curves, but retains the api of a curve
  18045. **************************************************************/
  18046. THREE.CurvePath = function () {
  18047. this.curves = [];
  18048. this.bends = [];
  18049. this.autoClose = false; // Automatically closes the path
  18050. };
  18051. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  18052. THREE.CurvePath.prototype.add = function ( curve ) {
  18053. this.curves.push( curve );
  18054. };
  18055. THREE.CurvePath.prototype.checkConnection = function() {
  18056. // TODO
  18057. // If the ending of curve is not connected to the starting
  18058. // or the next curve, then, this is not a real path
  18059. };
  18060. THREE.CurvePath.prototype.closePath = function() {
  18061. // TODO Test
  18062. // and verify for vector3 (needs to implement equals)
  18063. // Add a line curve if start and end of lines are not connected
  18064. var startPoint = this.curves[0].getPoint(0);
  18065. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  18066. if (!startPoint.equals(endPoint)) {
  18067. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  18068. }
  18069. };
  18070. // To get accurate point with reference to
  18071. // entire path distance at time t,
  18072. // following has to be done:
  18073. // 1. Length of each sub path have to be known
  18074. // 2. Locate and identify type of curve
  18075. // 3. Get t for the curve
  18076. // 4. Return curve.getPointAt(t')
  18077. THREE.CurvePath.prototype.getPoint = function( t ) {
  18078. var d = t * this.getLength();
  18079. var curveLengths = this.getCurveLengths();
  18080. var i = 0, diff, curve;
  18081. // To think about boundaries points.
  18082. while ( i < curveLengths.length ) {
  18083. if ( curveLengths[ i ] >= d ) {
  18084. diff = curveLengths[ i ] - d;
  18085. curve = this.curves[ i ];
  18086. var u = 1 - diff / curve.getLength();
  18087. return curve.getPointAt( u );
  18088. break;
  18089. }
  18090. i ++;
  18091. }
  18092. return null;
  18093. // loop where sum != 0, sum > d , sum+1 <d
  18094. };
  18095. /*
  18096. THREE.CurvePath.prototype.getTangent = function( t ) {
  18097. };*/
  18098. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18099. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18100. // getPoint() depends on getLength
  18101. THREE.CurvePath.prototype.getLength = function() {
  18102. var lens = this.getCurveLengths();
  18103. return lens[ lens.length - 1 ];
  18104. };
  18105. // Compute lengths and cache them
  18106. // We cannot overwrite getLengths() because UtoT mapping uses it.
  18107. THREE.CurvePath.prototype.getCurveLengths = function() {
  18108. // We use cache values if curves and cache array are same length
  18109. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  18110. return this.cacheLengths;
  18111. };
  18112. // Get length of subsurve
  18113. // Push sums into cached array
  18114. var lengths = [], sums = 0;
  18115. var i, il = this.curves.length;
  18116. for ( i = 0; i < il; i ++ ) {
  18117. sums += this.curves[ i ].getLength();
  18118. lengths.push( sums );
  18119. }
  18120. this.cacheLengths = lengths;
  18121. return lengths;
  18122. };
  18123. // Returns min and max coordinates
  18124. THREE.CurvePath.prototype.getBoundingBox = function () {
  18125. var points = this.getPoints();
  18126. var maxX, maxY, maxZ;
  18127. var minX, minY, minZ;
  18128. maxX = maxY = Number.NEGATIVE_INFINITY;
  18129. minX = minY = Number.POSITIVE_INFINITY;
  18130. var p, i, il, sum;
  18131. var v3 = points[0] instanceof THREE.Vector3;
  18132. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  18133. for ( i = 0, il = points.length; i < il; i ++ ) {
  18134. p = points[ i ];
  18135. if ( p.x > maxX ) maxX = p.x;
  18136. else if ( p.x < minX ) minX = p.x;
  18137. if ( p.y > maxY ) maxY = p.y;
  18138. else if ( p.y < minY ) minY = p.y;
  18139. if ( v3 ) {
  18140. if ( p.z > maxZ ) maxZ = p.z;
  18141. else if ( p.z < minZ ) minZ = p.z;
  18142. }
  18143. sum.add( p );
  18144. }
  18145. var ret = {
  18146. minX: minX,
  18147. minY: minY,
  18148. maxX: maxX,
  18149. maxY: maxY
  18150. };
  18151. if ( v3 ) {
  18152. ret.maxZ = maxZ;
  18153. ret.minZ = minZ;
  18154. }
  18155. return ret;
  18156. };
  18157. /**************************************************************
  18158. * Create Geometries Helpers
  18159. **************************************************************/
  18160. /// Generate geometry from path points (for Line or ParticleSystem objects)
  18161. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  18162. var pts = this.getPoints( divisions, true );
  18163. return this.createGeometry( pts );
  18164. };
  18165. // Generate geometry from equidistance sampling along the path
  18166. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  18167. var pts = this.getSpacedPoints( divisions, true );
  18168. return this.createGeometry( pts );
  18169. };
  18170. THREE.CurvePath.prototype.createGeometry = function( points ) {
  18171. var geometry = new THREE.Geometry();
  18172. for ( var i = 0; i < points.length; i ++ ) {
  18173. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  18174. }
  18175. return geometry;
  18176. };
  18177. /**************************************************************
  18178. * Bend / Wrap Helper Methods
  18179. **************************************************************/
  18180. // Wrap path / Bend modifiers?
  18181. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  18182. this.bends.push( bendpath );
  18183. };
  18184. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  18185. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  18186. var i, il;
  18187. if ( !bends ) {
  18188. bends = this.bends;
  18189. }
  18190. for ( i = 0, il = bends.length; i < il; i ++ ) {
  18191. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  18192. }
  18193. return oldPts;
  18194. };
  18195. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  18196. var oldPts = this.getSpacedPoints( segments );
  18197. var i, il;
  18198. if ( !bends ) {
  18199. bends = this.bends;
  18200. }
  18201. for ( i = 0, il = bends.length; i < il; i ++ ) {
  18202. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  18203. }
  18204. return oldPts;
  18205. };
  18206. // This returns getPoints() bend/wrapped around the contour of a path.
  18207. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  18208. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  18209. var bounds = this.getBoundingBox();
  18210. var i, il, p, oldX, oldY, xNorm;
  18211. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  18212. p = oldPts[ i ];
  18213. oldX = p.x;
  18214. oldY = p.y;
  18215. xNorm = oldX / bounds.maxX;
  18216. // If using actual distance, for length > path, requires line extrusions
  18217. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  18218. xNorm = path.getUtoTmapping( xNorm, oldX );
  18219. // check for out of bounds?
  18220. var pathPt = path.getPoint( xNorm );
  18221. var normal = path.getTangent( xNorm );
  18222. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  18223. p.x = pathPt.x + normal.x;
  18224. p.y = pathPt.y + normal.y;
  18225. }
  18226. return oldPts;
  18227. };
  18228. /**
  18229. * @author alteredq / http://alteredqualia.com/
  18230. */
  18231. THREE.Gyroscope = function () {
  18232. THREE.Object3D.call( this );
  18233. };
  18234. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  18235. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  18236. this.matrixAutoUpdate && this.updateMatrix();
  18237. // update matrixWorld
  18238. if ( this.matrixWorldNeedsUpdate || force ) {
  18239. if ( this.parent ) {
  18240. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  18241. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  18242. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  18243. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  18244. } else {
  18245. this.matrixWorld.copy( this.matrix );
  18246. }
  18247. this.matrixWorldNeedsUpdate = false;
  18248. force = true;
  18249. }
  18250. // update children
  18251. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  18252. this.children[ i ].updateMatrixWorld( force );
  18253. }
  18254. };
  18255. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  18256. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  18257. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  18258. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  18259. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  18260. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  18261. /**
  18262. * @author zz85 / http://www.lab4games.net/zz85/blog
  18263. * Creates free form 2d path using series of points, lines or curves.
  18264. *
  18265. **/
  18266. THREE.Path = function ( points ) {
  18267. THREE.CurvePath.call(this);
  18268. this.actions = [];
  18269. if ( points ) {
  18270. this.fromPoints( points );
  18271. }
  18272. };
  18273. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  18274. THREE.PathActions = {
  18275. MOVE_TO: 'moveTo',
  18276. LINE_TO: 'lineTo',
  18277. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  18278. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  18279. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  18280. ARC: 'arc', // Circle
  18281. ELLIPSE: 'ellipse'
  18282. };
  18283. // TODO Clean up PATH API
  18284. // Create path using straight lines to connect all points
  18285. // - vectors: array of Vector2
  18286. THREE.Path.prototype.fromPoints = function ( vectors ) {
  18287. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  18288. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  18289. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  18290. };
  18291. };
  18292. // startPath() endPath()?
  18293. THREE.Path.prototype.moveTo = function ( x, y ) {
  18294. var args = Array.prototype.slice.call( arguments );
  18295. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  18296. };
  18297. THREE.Path.prototype.lineTo = function ( x, y ) {
  18298. var args = Array.prototype.slice.call( arguments );
  18299. var lastargs = this.actions[ this.actions.length - 1 ].args;
  18300. var x0 = lastargs[ lastargs.length - 2 ];
  18301. var y0 = lastargs[ lastargs.length - 1 ];
  18302. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  18303. this.curves.push( curve );
  18304. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  18305. };
  18306. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  18307. var args = Array.prototype.slice.call( arguments );
  18308. var lastargs = this.actions[ this.actions.length - 1 ].args;
  18309. var x0 = lastargs[ lastargs.length - 2 ];
  18310. var y0 = lastargs[ lastargs.length - 1 ];
  18311. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  18312. new THREE.Vector2( aCPx, aCPy ),
  18313. new THREE.Vector2( aX, aY ) );
  18314. this.curves.push( curve );
  18315. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  18316. };
  18317. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  18318. aCP2x, aCP2y,
  18319. aX, aY ) {
  18320. var args = Array.prototype.slice.call( arguments );
  18321. var lastargs = this.actions[ this.actions.length - 1 ].args;
  18322. var x0 = lastargs[ lastargs.length - 2 ];
  18323. var y0 = lastargs[ lastargs.length - 1 ];
  18324. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  18325. new THREE.Vector2( aCP1x, aCP1y ),
  18326. new THREE.Vector2( aCP2x, aCP2y ),
  18327. new THREE.Vector2( aX, aY ) );
  18328. this.curves.push( curve );
  18329. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  18330. };
  18331. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  18332. var args = Array.prototype.slice.call( arguments );
  18333. var lastargs = this.actions[ this.actions.length - 1 ].args;
  18334. var x0 = lastargs[ lastargs.length - 2 ];
  18335. var y0 = lastargs[ lastargs.length - 1 ];
  18336. //---
  18337. var npts = [ new THREE.Vector2( x0, y0 ) ];
  18338. Array.prototype.push.apply( npts, pts );
  18339. var curve = new THREE.SplineCurve( npts );
  18340. this.curves.push( curve );
  18341. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  18342. };
  18343. // FUTURE: Change the API or follow canvas API?
  18344. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  18345. aStartAngle, aEndAngle, aClockwise ) {
  18346. var lastargs = this.actions[ this.actions.length - 1].args;
  18347. var x0 = lastargs[ lastargs.length - 2 ];
  18348. var y0 = lastargs[ lastargs.length - 1 ];
  18349. this.absarc(aX + x0, aY + y0, aRadius,
  18350. aStartAngle, aEndAngle, aClockwise );
  18351. };
  18352. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  18353. aStartAngle, aEndAngle, aClockwise ) {
  18354. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18355. };
  18356. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  18357. aStartAngle, aEndAngle, aClockwise ) {
  18358. var lastargs = this.actions[ this.actions.length - 1].args;
  18359. var x0 = lastargs[ lastargs.length - 2 ];
  18360. var y0 = lastargs[ lastargs.length - 1 ];
  18361. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  18362. aStartAngle, aEndAngle, aClockwise );
  18363. };
  18364. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  18365. aStartAngle, aEndAngle, aClockwise ) {
  18366. var args = Array.prototype.slice.call( arguments );
  18367. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  18368. aStartAngle, aEndAngle, aClockwise );
  18369. this.curves.push( curve );
  18370. var lastPoint = curve.getPoint(1);
  18371. args.push(lastPoint.x);
  18372. args.push(lastPoint.y);
  18373. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  18374. };
  18375. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  18376. if ( ! divisions ) divisions = 40;
  18377. var points = [];
  18378. for ( var i = 0; i < divisions; i ++ ) {
  18379. points.push( this.getPoint( i / divisions ) );
  18380. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  18381. }
  18382. // if ( closedPath ) {
  18383. //
  18384. // points.push( points[ 0 ] );
  18385. //
  18386. // }
  18387. return points;
  18388. };
  18389. /* Return an array of vectors based on contour of the path */
  18390. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  18391. if (this.useSpacedPoints) {
  18392. console.log('tata');
  18393. return this.getSpacedPoints( divisions, closedPath );
  18394. }
  18395. divisions = divisions || 12;
  18396. var points = [];
  18397. var i, il, item, action, args;
  18398. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  18399. laste, j,
  18400. t, tx, ty;
  18401. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  18402. item = this.actions[ i ];
  18403. action = item.action;
  18404. args = item.args;
  18405. switch( action ) {
  18406. case THREE.PathActions.MOVE_TO:
  18407. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  18408. break;
  18409. case THREE.PathActions.LINE_TO:
  18410. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  18411. break;
  18412. case THREE.PathActions.QUADRATIC_CURVE_TO:
  18413. cpx = args[ 2 ];
  18414. cpy = args[ 3 ];
  18415. cpx1 = args[ 0 ];
  18416. cpy1 = args[ 1 ];
  18417. if ( points.length > 0 ) {
  18418. laste = points[ points.length - 1 ];
  18419. cpx0 = laste.x;
  18420. cpy0 = laste.y;
  18421. } else {
  18422. laste = this.actions[ i - 1 ].args;
  18423. cpx0 = laste[ laste.length - 2 ];
  18424. cpy0 = laste[ laste.length - 1 ];
  18425. }
  18426. for ( j = 1; j <= divisions; j ++ ) {
  18427. t = j / divisions;
  18428. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  18429. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  18430. points.push( new THREE.Vector2( tx, ty ) );
  18431. }
  18432. break;
  18433. case THREE.PathActions.BEZIER_CURVE_TO:
  18434. cpx = args[ 4 ];
  18435. cpy = args[ 5 ];
  18436. cpx1 = args[ 0 ];
  18437. cpy1 = args[ 1 ];
  18438. cpx2 = args[ 2 ];
  18439. cpy2 = args[ 3 ];
  18440. if ( points.length > 0 ) {
  18441. laste = points[ points.length - 1 ];
  18442. cpx0 = laste.x;
  18443. cpy0 = laste.y;
  18444. } else {
  18445. laste = this.actions[ i - 1 ].args;
  18446. cpx0 = laste[ laste.length - 2 ];
  18447. cpy0 = laste[ laste.length - 1 ];
  18448. }
  18449. for ( j = 1; j <= divisions; j ++ ) {
  18450. t = j / divisions;
  18451. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  18452. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  18453. points.push( new THREE.Vector2( tx, ty ) );
  18454. }
  18455. break;
  18456. case THREE.PathActions.CSPLINE_THRU:
  18457. laste = this.actions[ i - 1 ].args;
  18458. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  18459. var spts = [ last ];
  18460. var n = divisions * args[ 0 ].length;
  18461. spts = spts.concat( args[ 0 ] );
  18462. var spline = new THREE.SplineCurve( spts );
  18463. for ( j = 1; j <= n; j ++ ) {
  18464. points.push( spline.getPointAt( j / n ) ) ;
  18465. }
  18466. break;
  18467. case THREE.PathActions.ARC:
  18468. var aX = args[ 0 ], aY = args[ 1 ],
  18469. aRadius = args[ 2 ],
  18470. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  18471. aClockwise = !!args[ 5 ];
  18472. var deltaAngle = aEndAngle - aStartAngle;
  18473. var angle;
  18474. var tdivisions = divisions * 2;
  18475. for ( j = 1; j <= tdivisions; j ++ ) {
  18476. t = j / tdivisions;
  18477. if ( ! aClockwise ) {
  18478. t = 1 - t;
  18479. }
  18480. angle = aStartAngle + t * deltaAngle;
  18481. tx = aX + aRadius * Math.cos( angle );
  18482. ty = aY + aRadius * Math.sin( angle );
  18483. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18484. points.push( new THREE.Vector2( tx, ty ) );
  18485. }
  18486. //console.log(points);
  18487. break;
  18488. case THREE.PathActions.ELLIPSE:
  18489. var aX = args[ 0 ], aY = args[ 1 ],
  18490. xRadius = args[ 2 ],
  18491. yRadius = args[ 3 ],
  18492. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  18493. aClockwise = !!args[ 6 ];
  18494. var deltaAngle = aEndAngle - aStartAngle;
  18495. var angle;
  18496. var tdivisions = divisions * 2;
  18497. for ( j = 1; j <= tdivisions; j ++ ) {
  18498. t = j / tdivisions;
  18499. if ( ! aClockwise ) {
  18500. t = 1 - t;
  18501. }
  18502. angle = aStartAngle + t * deltaAngle;
  18503. tx = aX + xRadius * Math.cos( angle );
  18504. ty = aY + yRadius * Math.sin( angle );
  18505. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18506. points.push( new THREE.Vector2( tx, ty ) );
  18507. }
  18508. //console.log(points);
  18509. break;
  18510. } // end switch
  18511. }
  18512. // Normalize to remove the closing point by default.
  18513. var lastPoint = points[ points.length - 1];
  18514. var EPSILON = 0.0000000001;
  18515. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  18516. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  18517. points.splice( points.length - 1, 1);
  18518. if ( closedPath ) {
  18519. points.push( points[ 0 ] );
  18520. }
  18521. return points;
  18522. };
  18523. //
  18524. // Breaks path into shapes
  18525. //
  18526. // Assumptions (if parameter isCCW==true the opposite holds):
  18527. // - solid shapes are defined clockwise (CW)
  18528. // - holes are defined counterclockwise (CCW)
  18529. //
  18530. // If parameter noHoles==true:
  18531. // - all subPaths are regarded as solid shapes
  18532. // - definition order CW/CCW has no relevance
  18533. //
  18534. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  18535. function extractSubpaths( inActions ) {
  18536. var i, il, item, action, args;
  18537. var subPaths = [], lastPath = new THREE.Path();
  18538. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  18539. item = inActions[ i ];
  18540. args = item.args;
  18541. action = item.action;
  18542. if ( action == THREE.PathActions.MOVE_TO ) {
  18543. if ( lastPath.actions.length != 0 ) {
  18544. subPaths.push( lastPath );
  18545. lastPath = new THREE.Path();
  18546. }
  18547. }
  18548. lastPath[ action ].apply( lastPath, args );
  18549. }
  18550. if ( lastPath.actions.length != 0 ) {
  18551. subPaths.push( lastPath );
  18552. }
  18553. // console.log(subPaths);
  18554. return subPaths;
  18555. }
  18556. function toShapesNoHoles( inSubpaths ) {
  18557. var shapes = [];
  18558. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  18559. var tmpPath = inSubpaths[ i ];
  18560. var tmpShape = new THREE.Shape();
  18561. tmpShape.actions = tmpPath.actions;
  18562. tmpShape.curves = tmpPath.curves;
  18563. shapes.push( tmpShape );
  18564. }
  18565. //console.log("shape", shapes);
  18566. return shapes;
  18567. };
  18568. function isPointInsidePolygon( inPt, inPolygon ) {
  18569. var EPSILON = 0.0000000001;
  18570. var polyLen = inPolygon.length;
  18571. // inPt on polygon contour => immediate success or
  18572. // toggling of inside/outside at every single! intersection point of an edge
  18573. // with the horizontal line through inPt, left of inPt
  18574. // not counting lowerY endpoints of edges and whole edges on that line
  18575. var inside = false;
  18576. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  18577. var edgeLowPt = inPolygon[ p ];
  18578. var edgeHighPt = inPolygon[ q ];
  18579. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  18580. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  18581. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  18582. if ( edgeDy < 0 ) {
  18583. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  18584. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  18585. }
  18586. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  18587. if ( inPt.y == edgeLowPt.y ) {
  18588. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  18589. // continue; // no intersection or edgeLowPt => doesn't count !!!
  18590. } else {
  18591. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  18592. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  18593. if ( perpEdge < 0 ) continue;
  18594. inside = !inside; // true intersection left of inPt
  18595. }
  18596. } else { // parallel or colinear
  18597. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  18598. // egde lies on the same horizontal line as inPt
  18599. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  18600. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  18601. // continue;
  18602. }
  18603. }
  18604. return inside;
  18605. }
  18606. var subPaths = extractSubpaths( this.actions );
  18607. if ( subPaths.length == 0 ) return [];
  18608. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  18609. var solid, tmpPath, tmpShape, shapes = [];
  18610. if ( subPaths.length == 1) {
  18611. tmpPath = subPaths[0];
  18612. tmpShape = new THREE.Shape();
  18613. tmpShape.actions = tmpPath.actions;
  18614. tmpShape.curves = tmpPath.curves;
  18615. shapes.push( tmpShape );
  18616. return shapes;
  18617. }
  18618. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  18619. holesFirst = isCCW ? !holesFirst : holesFirst;
  18620. // console.log("Holes first", holesFirst);
  18621. var betterShapeHoles = [];
  18622. var newShapes = [];
  18623. var newShapeHoles = [];
  18624. var mainIdx = 0;
  18625. var tmpPoints;
  18626. newShapes[mainIdx] = undefined;
  18627. newShapeHoles[mainIdx] = [];
  18628. var i, il;
  18629. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  18630. tmpPath = subPaths[ i ];
  18631. tmpPoints = tmpPath.getPoints();
  18632. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  18633. solid = isCCW ? !solid : solid;
  18634. if ( solid ) {
  18635. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  18636. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  18637. newShapes[mainIdx].s.actions = tmpPath.actions;
  18638. newShapes[mainIdx].s.curves = tmpPath.curves;
  18639. if ( holesFirst ) mainIdx++;
  18640. newShapeHoles[mainIdx] = [];
  18641. //console.log('cw', i);
  18642. } else {
  18643. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  18644. //console.log('ccw', i);
  18645. }
  18646. }
  18647. // only Holes? -> probably all Shapes with wrong orientation
  18648. if ( !newShapes[0] ) return toShapesNoHoles( subPaths );
  18649. if ( newShapes.length > 1 ) {
  18650. var ambigious = false;
  18651. var toChange = [];
  18652. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18653. betterShapeHoles[sIdx] = [];
  18654. }
  18655. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18656. var sh = newShapes[sIdx];
  18657. var sho = newShapeHoles[sIdx];
  18658. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  18659. var ho = sho[hIdx];
  18660. var hole_unassigned = true;
  18661. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  18662. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  18663. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  18664. if ( hole_unassigned ) {
  18665. hole_unassigned = false;
  18666. betterShapeHoles[s2Idx].push( ho );
  18667. } else {
  18668. ambigious = true;
  18669. }
  18670. }
  18671. }
  18672. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  18673. }
  18674. }
  18675. // console.log("ambigious: ", ambigious);
  18676. if ( toChange.length > 0 ) {
  18677. // console.log("to change: ", toChange);
  18678. if (! ambigious) newShapeHoles = betterShapeHoles;
  18679. }
  18680. }
  18681. var tmpHoles, j, jl;
  18682. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  18683. tmpShape = newShapes[i].s;
  18684. shapes.push( tmpShape );
  18685. tmpHoles = newShapeHoles[i];
  18686. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  18687. tmpShape.holes.push( tmpHoles[j].h );
  18688. }
  18689. }
  18690. //console.log("shape", shapes);
  18691. return shapes;
  18692. };
  18693. /**
  18694. * @author zz85 / http://www.lab4games.net/zz85/blog
  18695. * Defines a 2d shape plane using paths.
  18696. **/
  18697. // STEP 1 Create a path.
  18698. // STEP 2 Turn path into shape.
  18699. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18700. // STEP 3a - Extract points from each shape, turn to vertices
  18701. // STEP 3b - Triangulate each shape, add faces.
  18702. THREE.Shape = function () {
  18703. THREE.Path.apply( this, arguments );
  18704. this.holes = [];
  18705. };
  18706. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  18707. // Convenience method to return ExtrudeGeometry
  18708. THREE.Shape.prototype.extrude = function ( options ) {
  18709. var extruded = new THREE.ExtrudeGeometry( this, options );
  18710. return extruded;
  18711. };
  18712. // Convenience method to return ShapeGeometry
  18713. THREE.Shape.prototype.makeGeometry = function ( options ) {
  18714. var geometry = new THREE.ShapeGeometry( this, options );
  18715. return geometry;
  18716. };
  18717. // Get points of holes
  18718. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  18719. var i, il = this.holes.length, holesPts = [];
  18720. for ( i = 0; i < il; i ++ ) {
  18721. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  18722. }
  18723. return holesPts;
  18724. };
  18725. // Get points of holes (spaced by regular distance)
  18726. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  18727. var i, il = this.holes.length, holesPts = [];
  18728. for ( i = 0; i < il; i ++ ) {
  18729. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  18730. }
  18731. return holesPts;
  18732. };
  18733. // Get points of shape and holes (keypoints based on segments parameter)
  18734. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  18735. return {
  18736. shape: this.getTransformedPoints( divisions ),
  18737. holes: this.getPointsHoles( divisions )
  18738. };
  18739. };
  18740. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  18741. if (this.useSpacedPoints) {
  18742. return this.extractAllSpacedPoints(divisions);
  18743. }
  18744. return this.extractAllPoints(divisions);
  18745. };
  18746. //
  18747. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  18748. //
  18749. // return {
  18750. //
  18751. // shape: this.transform( bend, divisions ),
  18752. // holes: this.getPointsHoles( divisions, bend )
  18753. //
  18754. // };
  18755. //
  18756. // };
  18757. // Get points of shape and holes (spaced by regular distance)
  18758. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  18759. return {
  18760. shape: this.getTransformedSpacedPoints( divisions ),
  18761. holes: this.getSpacedPointsHoles( divisions )
  18762. };
  18763. };
  18764. /**************************************************************
  18765. * Utils
  18766. **************************************************************/
  18767. THREE.Shape.Utils = {
  18768. triangulateShape: function ( contour, holes ) {
  18769. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  18770. // inOtherPt needs to be colinear to the inSegment
  18771. if ( inSegPt1.x != inSegPt2.x ) {
  18772. if ( inSegPt1.x < inSegPt2.x ) {
  18773. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  18774. } else {
  18775. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  18776. }
  18777. } else {
  18778. if ( inSegPt1.y < inSegPt2.y ) {
  18779. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  18780. } else {
  18781. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  18782. }
  18783. }
  18784. }
  18785. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  18786. var EPSILON = 0.0000000001;
  18787. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  18788. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  18789. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  18790. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  18791. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  18792. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  18793. if ( Math.abs(limit) > EPSILON ) { // not parallel
  18794. var perpSeg2;
  18795. if ( limit > 0 ) {
  18796. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  18797. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18798. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  18799. } else {
  18800. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  18801. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18802. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  18803. }
  18804. // i.e. to reduce rounding errors
  18805. // intersection at endpoint of segment#1?
  18806. if ( perpSeg2 == 0 ) {
  18807. if ( ( inExcludeAdjacentSegs ) &&
  18808. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18809. return [ inSeg1Pt1 ];
  18810. }
  18811. if ( perpSeg2 == limit ) {
  18812. if ( ( inExcludeAdjacentSegs ) &&
  18813. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18814. return [ inSeg1Pt2 ];
  18815. }
  18816. // intersection at endpoint of segment#2?
  18817. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  18818. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  18819. // return real intersection point
  18820. var factorSeg1 = perpSeg2 / limit;
  18821. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  18822. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  18823. } else { // parallel or colinear
  18824. if ( ( perpSeg1 != 0 ) ||
  18825. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  18826. // they are collinear or degenerate
  18827. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  18828. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  18829. // both segments are points
  18830. if ( seg1Pt && seg2Pt ) {
  18831. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  18832. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  18833. return [ inSeg1Pt1 ]; // they are the same point
  18834. }
  18835. // segment#1 is a single point
  18836. if ( seg1Pt ) {
  18837. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  18838. return [ inSeg1Pt1 ];
  18839. }
  18840. // segment#2 is a single point
  18841. if ( seg2Pt ) {
  18842. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  18843. return [ inSeg2Pt1 ];
  18844. }
  18845. // they are collinear segments, which might overlap
  18846. var seg1min, seg1max, seg1minVal, seg1maxVal;
  18847. var seg2min, seg2max, seg2minVal, seg2maxVal;
  18848. if (seg1dx != 0) { // the segments are NOT on a vertical line
  18849. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  18850. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  18851. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  18852. } else {
  18853. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  18854. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  18855. }
  18856. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  18857. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  18858. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  18859. } else {
  18860. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  18861. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  18862. }
  18863. } else { // the segments are on a vertical line
  18864. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  18865. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  18866. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  18867. } else {
  18868. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  18869. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  18870. }
  18871. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  18872. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  18873. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  18874. } else {
  18875. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  18876. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  18877. }
  18878. }
  18879. if ( seg1minVal <= seg2minVal ) {
  18880. if ( seg1maxVal < seg2minVal ) return [];
  18881. if ( seg1maxVal == seg2minVal ) {
  18882. if ( inExcludeAdjacentSegs ) return [];
  18883. return [ seg2min ];
  18884. }
  18885. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18886. return [ seg2min, seg2max ];
  18887. } else {
  18888. if ( seg1minVal > seg2maxVal ) return [];
  18889. if ( seg1minVal == seg2maxVal ) {
  18890. if ( inExcludeAdjacentSegs ) return [];
  18891. return [ seg1min ];
  18892. }
  18893. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18894. return [ seg1min, seg2max ];
  18895. }
  18896. }
  18897. }
  18898. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18899. // The order of legs is important
  18900. var EPSILON = 0.0000000001;
  18901. // translation of all points, so that Vertex is at (0,0)
  18902. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18903. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18904. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18905. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18906. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18907. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18908. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  18909. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18910. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18911. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  18912. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18913. } else { // main angle > 180 deg.
  18914. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18915. }
  18916. } else { // angle == 180 deg.
  18917. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18918. return ( from2otherAngle > 0 );
  18919. }
  18920. }
  18921. function removeHoles( contour, holes ) {
  18922. var shape = contour.concat(); // work on this shape
  18923. var hole;
  18924. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18925. // Check if hole point lies within angle around shape point
  18926. var lastShapeIdx = shape.length - 1;
  18927. var prevShapeIdx = inShapeIdx - 1;
  18928. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18929. var nextShapeIdx = inShapeIdx + 1;
  18930. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18931. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  18932. if (! insideAngle ) {
  18933. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18934. return false;
  18935. }
  18936. // Check if shape point lies within angle around hole point
  18937. var lastHoleIdx = hole.length - 1;
  18938. var prevHoleIdx = inHoleIdx - 1;
  18939. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18940. var nextHoleIdx = inHoleIdx + 1;
  18941. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18942. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  18943. if (! insideAngle ) {
  18944. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18945. return false;
  18946. }
  18947. return true;
  18948. }
  18949. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18950. // checks for intersections with shape edges
  18951. var sIdx, nextIdx, intersection;
  18952. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  18953. nextIdx = sIdx+1; nextIdx %= shape.length;
  18954. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  18955. if ( intersection.length > 0 ) return true;
  18956. }
  18957. return false;
  18958. }
  18959. var indepHoles = [];
  18960. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18961. // checks for intersections with hole edges
  18962. var ihIdx, chkHole,
  18963. hIdx, nextIdx, intersection;
  18964. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  18965. chkHole = holes[indepHoles[ihIdx]];
  18966. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  18967. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  18968. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  18969. if ( intersection.length > 0 ) return true;
  18970. }
  18971. }
  18972. return false;
  18973. }
  18974. var holeIndex, shapeIndex,
  18975. shapePt, holePt,
  18976. holeIdx, cutKey, failedCuts = [],
  18977. tmpShape1, tmpShape2,
  18978. tmpHole1, tmpHole2;
  18979. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18980. indepHoles.push( h );
  18981. }
  18982. var minShapeIndex = 0;
  18983. var counter = indepHoles.length * 2;
  18984. while ( indepHoles.length > 0 ) {
  18985. counter --;
  18986. if ( counter < 0 ) {
  18987. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18988. break;
  18989. }
  18990. // search for shape-vertex and hole-vertex,
  18991. // which can be connected without intersections
  18992. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex++ ) {
  18993. shapePt = shape[ shapeIndex ];
  18994. holeIndex = -1;
  18995. // search for hole which can be reached without intersections
  18996. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18997. holeIdx = indepHoles[h];
  18998. // prevent multiple checks
  18999. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19000. if ( failedCuts[cutKey] !== undefined ) continue;
  19001. hole = holes[holeIdx];
  19002. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19003. holePt = hole[ h2 ];
  19004. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19005. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19006. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19007. holeIndex = h2;
  19008. indepHoles.splice(h,1);
  19009. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  19010. tmpShape2 = shape.slice( shapeIndex );
  19011. tmpHole1 = hole.slice( holeIndex );
  19012. tmpHole2 = hole.slice( 0, holeIndex+1 );
  19013. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19014. minShapeIndex = shapeIndex;
  19015. // Debug only, to show the selected cuts
  19016. // glob_CutLines.push( [ shapePt, holePt ] );
  19017. break;
  19018. }
  19019. if ( holeIndex >= 0 ) break; // hole-vertex found
  19020. failedCuts[cutKey] = true; // remember failure
  19021. }
  19022. if ( holeIndex >= 0 ) break; // hole-vertex found
  19023. }
  19024. }
  19025. return shape; /* shape with no holes */
  19026. }
  19027. var i, il, f, face,
  19028. key, index,
  19029. allPointsMap = {};
  19030. // 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.
  19031. var allpoints = contour.concat();
  19032. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19033. Array.prototype.push.apply( allpoints, holes[h] );
  19034. }
  19035. //console.log( "allpoints",allpoints, allpoints.length );
  19036. // prepare all points map
  19037. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19038. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19039. if ( allPointsMap[ key ] !== undefined ) {
  19040. console.log( "Duplicate point", key );
  19041. }
  19042. allPointsMap[ key ] = i;
  19043. }
  19044. // remove holes by cutting paths to holes and adding them to the shape
  19045. var shapeWithoutHoles = removeHoles( contour, holes );
  19046. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19047. //console.log( "triangles",triangles, triangles.length );
  19048. // check all face vertices against all points map
  19049. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19050. face = triangles[ i ];
  19051. for ( f = 0; f < 3; f ++ ) {
  19052. key = face[ f ].x + ":" + face[ f ].y;
  19053. index = allPointsMap[ key ];
  19054. if ( index !== undefined ) {
  19055. face[ f ] = index;
  19056. }
  19057. }
  19058. }
  19059. return triangles.concat();
  19060. },
  19061. isClockWise: function ( pts ) {
  19062. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  19063. },
  19064. // Bezier Curves formulas obtained from
  19065. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19066. // Quad Bezier Functions
  19067. b2p0: function ( t, p ) {
  19068. var k = 1 - t;
  19069. return k * k * p;
  19070. },
  19071. b2p1: function ( t, p ) {
  19072. return 2 * ( 1 - t ) * t * p;
  19073. },
  19074. b2p2: function ( t, p ) {
  19075. return t * t * p;
  19076. },
  19077. b2: function ( t, p0, p1, p2 ) {
  19078. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  19079. },
  19080. // Cubic Bezier Functions
  19081. b3p0: function ( t, p ) {
  19082. var k = 1 - t;
  19083. return k * k * k * p;
  19084. },
  19085. b3p1: function ( t, p ) {
  19086. var k = 1 - t;
  19087. return 3 * k * k * t * p;
  19088. },
  19089. b3p2: function ( t, p ) {
  19090. var k = 1 - t;
  19091. return 3 * k * t * t * p;
  19092. },
  19093. b3p3: function ( t, p ) {
  19094. return t * t * t * p;
  19095. },
  19096. b3: function ( t, p0, p1, p2, p3 ) {
  19097. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  19098. }
  19099. };
  19100. /**************************************************************
  19101. * Line
  19102. **************************************************************/
  19103. THREE.LineCurve = function ( v1, v2 ) {
  19104. this.v1 = v1;
  19105. this.v2 = v2;
  19106. };
  19107. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  19108. THREE.LineCurve.prototype.getPoint = function ( t ) {
  19109. var point = this.v2.clone().sub(this.v1);
  19110. point.multiplyScalar( t ).add( this.v1 );
  19111. return point;
  19112. };
  19113. // Line curve is linear, so we can overwrite default getPointAt
  19114. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  19115. return this.getPoint( u );
  19116. };
  19117. THREE.LineCurve.prototype.getTangent = function( t ) {
  19118. var tangent = this.v2.clone().sub(this.v1);
  19119. return tangent.normalize();
  19120. };
  19121. /**************************************************************
  19122. * Quadratic Bezier curve
  19123. **************************************************************/
  19124. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  19125. this.v0 = v0;
  19126. this.v1 = v1;
  19127. this.v2 = v2;
  19128. };
  19129. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  19130. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  19131. var tx, ty;
  19132. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  19133. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  19134. return new THREE.Vector2( tx, ty );
  19135. };
  19136. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  19137. var tx, ty;
  19138. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  19139. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  19140. // returns unit vector
  19141. var tangent = new THREE.Vector2( tx, ty );
  19142. tangent.normalize();
  19143. return tangent;
  19144. };
  19145. /**************************************************************
  19146. * Cubic Bezier curve
  19147. **************************************************************/
  19148. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  19149. this.v0 = v0;
  19150. this.v1 = v1;
  19151. this.v2 = v2;
  19152. this.v3 = v3;
  19153. };
  19154. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  19155. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  19156. var tx, ty;
  19157. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  19158. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  19159. return new THREE.Vector2( tx, ty );
  19160. };
  19161. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  19162. var tx, ty;
  19163. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  19164. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  19165. var tangent = new THREE.Vector2( tx, ty );
  19166. tangent.normalize();
  19167. return tangent;
  19168. };
  19169. /**************************************************************
  19170. * Spline curve
  19171. **************************************************************/
  19172. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  19173. this.points = (points == undefined) ? [] : points;
  19174. };
  19175. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  19176. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  19177. var v = new THREE.Vector2();
  19178. var c = [];
  19179. var points = this.points, point, intPoint, weight;
  19180. point = ( points.length - 1 ) * t;
  19181. intPoint = Math.floor( point );
  19182. weight = point - intPoint;
  19183. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  19184. c[ 1 ] = intPoint;
  19185. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  19186. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  19187. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  19188. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  19189. return v;
  19190. };
  19191. /**************************************************************
  19192. * Ellipse curve
  19193. **************************************************************/
  19194. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  19195. this.aX = aX;
  19196. this.aY = aY;
  19197. this.xRadius = xRadius;
  19198. this.yRadius = yRadius;
  19199. this.aStartAngle = aStartAngle;
  19200. this.aEndAngle = aEndAngle;
  19201. this.aClockwise = aClockwise;
  19202. };
  19203. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  19204. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  19205. var angle;
  19206. var deltaAngle = this.aEndAngle - this.aStartAngle;
  19207. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  19208. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  19209. if ( this.aClockwise === true ) {
  19210. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  19211. } else {
  19212. angle = this.aStartAngle + t * deltaAngle;
  19213. }
  19214. var tx = this.aX + this.xRadius * Math.cos( angle );
  19215. var ty = this.aY + this.yRadius * Math.sin( angle );
  19216. return new THREE.Vector2( tx, ty );
  19217. };
  19218. /**************************************************************
  19219. * Arc curve
  19220. **************************************************************/
  19221. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19222. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19223. };
  19224. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  19225. /**************************************************************
  19226. * Line3D
  19227. **************************************************************/
  19228. THREE.LineCurve3 = THREE.Curve.create(
  19229. function ( v1, v2 ) {
  19230. this.v1 = v1;
  19231. this.v2 = v2;
  19232. },
  19233. function ( t ) {
  19234. var r = new THREE.Vector3();
  19235. r.subVectors( this.v2, this.v1 ); // diff
  19236. r.multiplyScalar( t );
  19237. r.add( this.v1 );
  19238. return r;
  19239. }
  19240. );
  19241. /**************************************************************
  19242. * Quadratic Bezier 3D curve
  19243. **************************************************************/
  19244. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  19245. function ( v0, v1, v2 ) {
  19246. this.v0 = v0;
  19247. this.v1 = v1;
  19248. this.v2 = v2;
  19249. },
  19250. function ( t ) {
  19251. var tx, ty, tz;
  19252. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  19253. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  19254. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  19255. return new THREE.Vector3( tx, ty, tz );
  19256. }
  19257. );
  19258. /**************************************************************
  19259. * Cubic Bezier 3D curve
  19260. **************************************************************/
  19261. THREE.CubicBezierCurve3 = THREE.Curve.create(
  19262. function ( v0, v1, v2, v3 ) {
  19263. this.v0 = v0;
  19264. this.v1 = v1;
  19265. this.v2 = v2;
  19266. this.v3 = v3;
  19267. },
  19268. function ( t ) {
  19269. var tx, ty, tz;
  19270. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  19271. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  19272. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  19273. return new THREE.Vector3( tx, ty, tz );
  19274. }
  19275. );
  19276. /**************************************************************
  19277. * Spline 3D curve
  19278. **************************************************************/
  19279. THREE.SplineCurve3 = THREE.Curve.create(
  19280. function ( points /* array of Vector3 */) {
  19281. this.points = (points == undefined) ? [] : points;
  19282. },
  19283. function ( t ) {
  19284. var v = new THREE.Vector3();
  19285. var c = [];
  19286. var points = this.points, point, intPoint, weight;
  19287. point = ( points.length - 1 ) * t;
  19288. intPoint = Math.floor( point );
  19289. weight = point - intPoint;
  19290. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  19291. c[ 1 ] = intPoint;
  19292. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  19293. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  19294. var pt0 = points[ c[0] ],
  19295. pt1 = points[ c[1] ],
  19296. pt2 = points[ c[2] ],
  19297. pt3 = points[ c[3] ];
  19298. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  19299. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  19300. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  19301. return v;
  19302. }
  19303. );
  19304. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  19305. // var v = new THREE.Vector3();
  19306. // var c = [];
  19307. // var points = this.points, point, intPoint, weight;
  19308. // point = ( points.length - 1 ) * t;
  19309. // intPoint = Math.floor( point );
  19310. // weight = point - intPoint;
  19311. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  19312. // c[ 1 ] = intPoint;
  19313. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  19314. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  19315. // var pt0 = points[ c[0] ],
  19316. // pt1 = points[ c[1] ],
  19317. // pt2 = points[ c[2] ],
  19318. // pt3 = points[ c[3] ];
  19319. // // t = weight;
  19320. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  19321. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  19322. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  19323. // return v;
  19324. // }
  19325. /**************************************************************
  19326. * Closed Spline 3D curve
  19327. **************************************************************/
  19328. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  19329. function ( points /* array of Vector3 */) {
  19330. this.points = (points == undefined) ? [] : points;
  19331. },
  19332. function ( t ) {
  19333. var v = new THREE.Vector3();
  19334. var c = [];
  19335. var points = this.points, point, intPoint, weight;
  19336. point = ( points.length - 0 ) * t;
  19337. // This needs to be from 0-length +1
  19338. intPoint = Math.floor( point );
  19339. weight = point - intPoint;
  19340. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  19341. c[ 0 ] = ( intPoint - 1 ) % points.length;
  19342. c[ 1 ] = ( intPoint ) % points.length;
  19343. c[ 2 ] = ( intPoint + 1 ) % points.length;
  19344. c[ 3 ] = ( intPoint + 2 ) % points.length;
  19345. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  19346. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  19347. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  19348. return v;
  19349. }
  19350. );
  19351. /**
  19352. * @author mikael emtinger / http://gomo.se/
  19353. */
  19354. THREE.AnimationHandler = ( function () {
  19355. var playing = [];
  19356. var library = {};
  19357. var that = {};
  19358. that.update = function ( deltaTimeMS ) {
  19359. for ( var i = 0; i < playing.length; i ++ ) {
  19360. playing[ i ].update( deltaTimeMS );
  19361. }
  19362. };
  19363. that.addToUpdate = function ( animation ) {
  19364. if ( playing.indexOf( animation ) === -1 ) {
  19365. playing.push( animation );
  19366. }
  19367. };
  19368. that.removeFromUpdate = function ( animation ) {
  19369. var index = playing.indexOf( animation );
  19370. if ( index !== -1 ) {
  19371. playing.splice( index, 1 );
  19372. }
  19373. };
  19374. that.add = function ( data ) {
  19375. if ( library[ data.name ] !== undefined ) {
  19376. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  19377. }
  19378. library[ data.name ] = data;
  19379. initData( data );
  19380. };
  19381. that.remove = function ( name ) {
  19382. if ( library[ name ] === undefined ) {
  19383. console.log( "THREE.AnimationHandler.add: Warning! " + name + " doesn't exists in library. Doing nothing." );
  19384. }
  19385. library[ name ] = undefined;
  19386. };
  19387. that.get = function ( name ) {
  19388. if ( typeof name === "string" ) {
  19389. if ( library[ name ] ) {
  19390. return library[ name ];
  19391. } else {
  19392. return null;
  19393. }
  19394. } else {
  19395. // todo: add simple tween library
  19396. }
  19397. };
  19398. that.parse = function ( root ) {
  19399. // setup hierarchy
  19400. var hierarchy = [];
  19401. if ( root instanceof THREE.SkinnedMesh ) {
  19402. for ( var b = 0; b < root.bones.length; b++ ) {
  19403. hierarchy.push( root.bones[ b ] );
  19404. }
  19405. } else {
  19406. parseRecurseHierarchy( root, hierarchy );
  19407. }
  19408. return hierarchy;
  19409. };
  19410. var parseRecurseHierarchy = function ( root, hierarchy ) {
  19411. hierarchy.push( root );
  19412. for ( var c = 0; c < root.children.length; c++ )
  19413. parseRecurseHierarchy( root.children[ c ], hierarchy );
  19414. }
  19415. var initData = function ( data ) {
  19416. if ( data.initialized === true )
  19417. return;
  19418. // loop through all keys
  19419. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  19420. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  19421. // remove minus times
  19422. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  19423. data.hierarchy[ h ].keys[ k ].time = 0;
  19424. }
  19425. // create quaternions
  19426. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  19427. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  19428. var quat = data.hierarchy[ h ].keys[ k ].rot;
  19429. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  19430. }
  19431. }
  19432. // prepare morph target keys
  19433. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  19434. // get all used
  19435. var usedMorphTargets = {};
  19436. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  19437. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  19438. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  19439. usedMorphTargets[ morphTargetName ] = -1;
  19440. }
  19441. }
  19442. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  19443. // set all used on all frames
  19444. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  19445. var influences = {};
  19446. for ( var morphTargetName in usedMorphTargets ) {
  19447. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  19448. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  19449. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  19450. break;
  19451. }
  19452. }
  19453. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  19454. influences[ morphTargetName ] = 0;
  19455. }
  19456. }
  19457. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  19458. }
  19459. }
  19460. // remove all keys that are on the same time
  19461. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  19462. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  19463. data.hierarchy[ h ].keys.splice( k, 1 );
  19464. k --;
  19465. }
  19466. }
  19467. // set index
  19468. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  19469. data.hierarchy[ h ].keys[ k ].index = k;
  19470. }
  19471. }
  19472. data.initialized = true;
  19473. };
  19474. // interpolation types
  19475. that.LINEAR = 0;
  19476. that.CATMULLROM = 1;
  19477. that.CATMULLROM_FORWARD = 2;
  19478. return that;
  19479. }() );
  19480. /**
  19481. * @author mikael emtinger / http://gomo.se/
  19482. * @author mrdoob / http://mrdoob.com/
  19483. * @author alteredq / http://alteredqualia.com/
  19484. */
  19485. THREE.Animation = function ( root, name ) {
  19486. this.root = root;
  19487. this.data = THREE.AnimationHandler.get( name );
  19488. this.hierarchy = THREE.AnimationHandler.parse( root );
  19489. this.currentTime = 0;
  19490. this.timeScale = 1;
  19491. this.isPlaying = false;
  19492. this.isPaused = true;
  19493. this.loop = true;
  19494. this.interpolationType = THREE.AnimationHandler.LINEAR;
  19495. };
  19496. THREE.Animation.prototype.play = function ( startTime ) {
  19497. this.currentTime = startTime !== undefined ? startTime : 0;
  19498. if ( this.isPlaying === false ) {
  19499. this.isPlaying = true;
  19500. this.reset();
  19501. this.update( 0 );
  19502. }
  19503. this.isPaused = false;
  19504. THREE.AnimationHandler.addToUpdate( this );
  19505. };
  19506. THREE.Animation.prototype.pause = function() {
  19507. if ( this.isPaused === true ) {
  19508. THREE.AnimationHandler.addToUpdate( this );
  19509. } else {
  19510. THREE.AnimationHandler.removeFromUpdate( this );
  19511. }
  19512. this.isPaused = !this.isPaused;
  19513. };
  19514. THREE.Animation.prototype.stop = function() {
  19515. this.isPlaying = false;
  19516. this.isPaused = false;
  19517. THREE.AnimationHandler.removeFromUpdate( this );
  19518. };
  19519. THREE.Animation.prototype.reset = function () {
  19520. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19521. var object = this.hierarchy[ h ];
  19522. object.matrixAutoUpdate = true;
  19523. if ( object.animationCache === undefined ) {
  19524. object.animationCache = {};
  19525. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  19526. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  19527. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  19528. }
  19529. var prevKey = object.animationCache.prevKey;
  19530. var nextKey = object.animationCache.nextKey;
  19531. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  19532. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  19533. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  19534. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  19535. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  19536. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  19537. }
  19538. };
  19539. THREE.Animation.prototype.update = (function(){
  19540. var points = [];
  19541. var target = new THREE.Vector3();
  19542. // Catmull-Rom spline
  19543. var interpolateCatmullRom = function ( points, scale ) {
  19544. var c = [], v3 = [],
  19545. point, intPoint, weight, w2, w3,
  19546. pa, pb, pc, pd;
  19547. point = ( points.length - 1 ) * scale;
  19548. intPoint = Math.floor( point );
  19549. weight = point - intPoint;
  19550. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  19551. c[ 1 ] = intPoint;
  19552. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  19553. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  19554. pa = points[ c[ 0 ] ];
  19555. pb = points[ c[ 1 ] ];
  19556. pc = points[ c[ 2 ] ];
  19557. pd = points[ c[ 3 ] ];
  19558. w2 = weight * weight;
  19559. w3 = weight * w2;
  19560. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  19561. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  19562. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  19563. return v3;
  19564. };
  19565. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  19566. var v0 = ( p2 - p0 ) * 0.5,
  19567. v1 = ( p3 - p1 ) * 0.5;
  19568. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19569. };
  19570. return function ( delta ) {
  19571. if ( this.isPlaying === false ) return;
  19572. this.currentTime += delta * this.timeScale;
  19573. //
  19574. var vector;
  19575. var types = [ "pos", "rot", "scl" ];
  19576. var duration = this.data.length;
  19577. if ( this.loop === true && this.currentTime > duration ) {
  19578. this.currentTime %= duration;
  19579. this.reset();
  19580. } else if ( this.loop === false && this.currentTime > duration ) {
  19581. this.stop();
  19582. return;
  19583. }
  19584. this.currentTime = Math.min( this.currentTime, duration );
  19585. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19586. var object = this.hierarchy[ h ];
  19587. var animationCache = object.animationCache;
  19588. // loop through pos/rot/scl
  19589. for ( var t = 0; t < 3; t ++ ) {
  19590. // get keys
  19591. var type = types[ t ];
  19592. var prevKey = animationCache.prevKey[ type ];
  19593. var nextKey = animationCache.nextKey[ type ];
  19594. if ( nextKey.time <= this.currentTime ) {
  19595. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  19596. nextKey = this.getNextKeyWith( type, h, 1 );
  19597. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19598. prevKey = nextKey;
  19599. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  19600. }
  19601. animationCache.prevKey[ type ] = prevKey;
  19602. animationCache.nextKey[ type ] = nextKey;
  19603. }
  19604. object.matrixAutoUpdate = true;
  19605. object.matrixWorldNeedsUpdate = true;
  19606. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  19607. var prevXYZ = prevKey[ type ];
  19608. var nextXYZ = nextKey[ type ];
  19609. if ( scale < 0 ) scale = 0;
  19610. if ( scale > 1 ) scale = 1;
  19611. // interpolate
  19612. if ( type === "pos" ) {
  19613. vector = object.position;
  19614. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  19615. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19616. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19617. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19618. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19619. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19620. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  19621. points[ 1 ] = prevXYZ;
  19622. points[ 2 ] = nextXYZ;
  19623. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  19624. scale = scale * 0.33 + 0.33;
  19625. var currentPoint = interpolateCatmullRom( points, scale );
  19626. vector.x = currentPoint[ 0 ];
  19627. vector.y = currentPoint[ 1 ];
  19628. vector.z = currentPoint[ 2 ];
  19629. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19630. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  19631. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  19632. target.sub( vector );
  19633. target.y = 0;
  19634. target.normalize();
  19635. var angle = Math.atan2( target.x, target.z );
  19636. object.rotation.set( 0, angle, 0 );
  19637. }
  19638. }
  19639. } else if ( type === "rot" ) {
  19640. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  19641. } else if ( type === "scl" ) {
  19642. vector = object.scale;
  19643. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19644. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19645. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19646. }
  19647. }
  19648. }
  19649. };
  19650. })();
  19651. // Get next key with
  19652. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  19653. var keys = this.data.hierarchy[ h ].keys;
  19654. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19655. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19656. key = key < keys.length - 1 ? key : keys.length - 1;
  19657. } else {
  19658. key = key % keys.length;
  19659. }
  19660. for ( ; key < keys.length; key++ ) {
  19661. if ( keys[ key ][ type ] !== undefined ) {
  19662. return keys[ key ];
  19663. }
  19664. }
  19665. return this.data.hierarchy[ h ].keys[ 0 ];
  19666. };
  19667. // Get previous key with
  19668. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  19669. var keys = this.data.hierarchy[ h ].keys;
  19670. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19671. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19672. key = key > 0 ? key : 0;
  19673. } else {
  19674. key = key >= 0 ? key : key + keys.length;
  19675. }
  19676. for ( ; key >= 0; key -- ) {
  19677. if ( keys[ key ][ type ] !== undefined ) {
  19678. return keys[ key ];
  19679. }
  19680. }
  19681. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  19682. };
  19683. /**
  19684. * @author mikael emtinger / http://gomo.se/
  19685. * @author mrdoob / http://mrdoob.com/
  19686. * @author alteredq / http://alteredqualia.com/
  19687. * @author khang duong
  19688. * @author erik kitson
  19689. */
  19690. THREE.KeyFrameAnimation = function ( root, data ) {
  19691. this.root = root;
  19692. this.data = THREE.AnimationHandler.get( data );
  19693. this.hierarchy = THREE.AnimationHandler.parse( root );
  19694. this.currentTime = 0;
  19695. this.timeScale = 0.001;
  19696. this.isPlaying = false;
  19697. this.isPaused = true;
  19698. this.loop = true;
  19699. // initialize to first keyframes
  19700. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19701. var keys = this.data.hierarchy[h].keys,
  19702. sids = this.data.hierarchy[h].sids,
  19703. obj = this.hierarchy[h];
  19704. if ( keys.length && sids ) {
  19705. for ( var s = 0; s < sids.length; s++ ) {
  19706. var sid = sids[ s ],
  19707. next = this.getNextKeyWith( sid, h, 0 );
  19708. if ( next ) {
  19709. next.apply( sid );
  19710. }
  19711. }
  19712. obj.matrixAutoUpdate = false;
  19713. this.data.hierarchy[h].node.updateMatrix();
  19714. obj.matrixWorldNeedsUpdate = true;
  19715. }
  19716. }
  19717. };
  19718. // Play
  19719. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  19720. this.currentTime = startTime !== undefined ? startTime : 0;
  19721. if ( this.isPlaying === false ) {
  19722. this.isPlaying = true;
  19723. // reset key cache
  19724. var h, hl = this.hierarchy.length,
  19725. object,
  19726. node;
  19727. for ( h = 0; h < hl; h++ ) {
  19728. object = this.hierarchy[ h ];
  19729. node = this.data.hierarchy[ h ];
  19730. if ( node.animationCache === undefined ) {
  19731. node.animationCache = {};
  19732. node.animationCache.prevKey = null;
  19733. node.animationCache.nextKey = null;
  19734. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  19735. }
  19736. var keys = this.data.hierarchy[h].keys;
  19737. if (keys.length) {
  19738. node.animationCache.prevKey = keys[ 0 ];
  19739. node.animationCache.nextKey = keys[ 1 ];
  19740. this.startTime = Math.min( keys[0].time, this.startTime );
  19741. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  19742. }
  19743. }
  19744. this.update( 0 );
  19745. }
  19746. this.isPaused = false;
  19747. THREE.AnimationHandler.addToUpdate( this );
  19748. };
  19749. // Pause
  19750. THREE.KeyFrameAnimation.prototype.pause = function() {
  19751. if( this.isPaused ) {
  19752. THREE.AnimationHandler.addToUpdate( this );
  19753. } else {
  19754. THREE.AnimationHandler.removeFromUpdate( this );
  19755. }
  19756. this.isPaused = !this.isPaused;
  19757. };
  19758. // Stop
  19759. THREE.KeyFrameAnimation.prototype.stop = function() {
  19760. this.isPlaying = false;
  19761. this.isPaused = false;
  19762. THREE.AnimationHandler.removeFromUpdate( this );
  19763. // reset JIT matrix and remove cache
  19764. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  19765. var obj = this.hierarchy[ h ];
  19766. var node = this.data.hierarchy[ h ];
  19767. if ( node.animationCache !== undefined ) {
  19768. var original = node.animationCache.originalMatrix;
  19769. if( obj instanceof THREE.Bone ) {
  19770. original.copy( obj.skinMatrix );
  19771. obj.skinMatrix = original;
  19772. } else {
  19773. original.copy( obj.matrix );
  19774. obj.matrix = original;
  19775. }
  19776. delete node.animationCache;
  19777. }
  19778. }
  19779. };
  19780. // Update
  19781. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  19782. if ( this.isPlaying === false ) return;
  19783. this.currentTime += delta * this.timeScale;
  19784. //
  19785. var duration = this.data.length;
  19786. if ( this.loop === true && this.currentTime > duration ) {
  19787. this.currentTime %= duration;
  19788. }
  19789. this.currentTime = Math.min( this.currentTime, duration );
  19790. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  19791. var object = this.hierarchy[ h ];
  19792. var node = this.data.hierarchy[ h ];
  19793. var keys = node.keys,
  19794. animationCache = node.animationCache;
  19795. if ( keys.length ) {
  19796. var prevKey = animationCache.prevKey;
  19797. var nextKey = animationCache.nextKey;
  19798. if ( nextKey.time <= this.currentTime ) {
  19799. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19800. prevKey = nextKey;
  19801. nextKey = keys[ prevKey.index + 1 ];
  19802. }
  19803. animationCache.prevKey = prevKey;
  19804. animationCache.nextKey = nextKey;
  19805. }
  19806. if ( nextKey.time >= this.currentTime ) {
  19807. prevKey.interpolate( nextKey, this.currentTime );
  19808. } else {
  19809. prevKey.interpolate( nextKey, nextKey.time );
  19810. }
  19811. this.data.hierarchy[ h ].node.updateMatrix();
  19812. object.matrixWorldNeedsUpdate = true;
  19813. }
  19814. }
  19815. };
  19816. // Get next key with
  19817. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  19818. var keys = this.data.hierarchy[ h ].keys;
  19819. key = key % keys.length;
  19820. for ( ; key < keys.length; key++ ) {
  19821. if ( keys[ key ].hasTarget( sid ) ) {
  19822. return keys[ key ];
  19823. }
  19824. }
  19825. return keys[ 0 ];
  19826. };
  19827. // Get previous key with
  19828. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  19829. var keys = this.data.hierarchy[ h ].keys;
  19830. key = key >= 0 ? key : key + keys.length;
  19831. for ( ; key >= 0; key-- ) {
  19832. if ( keys[ key ].hasTarget( sid ) ) {
  19833. return keys[ key ];
  19834. }
  19835. }
  19836. return keys[ keys.length - 1 ];
  19837. };
  19838. /**
  19839. * @author mrdoob / http://mrdoob.com
  19840. */
  19841. THREE.MorphAnimation = function ( mesh ) {
  19842. this.mesh = mesh;
  19843. this.frames = mesh.morphTargetInfluences.length;
  19844. this.currentTime = 0;
  19845. this.duration = 1000;
  19846. this.loop = true;
  19847. this.isPlaying = false;
  19848. };
  19849. THREE.MorphAnimation.prototype = {
  19850. play: function () {
  19851. this.isPlaying = true;
  19852. },
  19853. pause: function () {
  19854. this.isPlaying = false;
  19855. },
  19856. update: ( function () {
  19857. var lastFrame = 0;
  19858. var currentFrame = 0;
  19859. return function ( delta ) {
  19860. if ( this.isPlaying === false ) return;
  19861. this.currentTime += delta;
  19862. if ( this.loop === true && this.currentTime > this.duration ) {
  19863. this.currentTime %= this.duration;
  19864. }
  19865. this.currentTime = Math.min( this.currentTime, this.duration );
  19866. var interpolation = this.duration / this.frames;
  19867. var frame = Math.floor( this.currentTime / interpolation );
  19868. if ( frame != currentFrame ) {
  19869. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  19870. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  19871. this.mesh.morphTargetInfluences[ frame ] = 0;
  19872. lastFrame = currentFrame;
  19873. currentFrame = frame;
  19874. }
  19875. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  19876. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  19877. }
  19878. } )()
  19879. };
  19880. /**
  19881. * Camera for rendering cube maps
  19882. * - renders scene into axis-aligned cube
  19883. *
  19884. * @author alteredq / http://alteredqualia.com/
  19885. */
  19886. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19887. THREE.Object3D.call( this );
  19888. var fov = 90, aspect = 1;
  19889. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19890. cameraPX.up.set( 0, -1, 0 );
  19891. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19892. this.add( cameraPX );
  19893. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19894. cameraNX.up.set( 0, -1, 0 );
  19895. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19896. this.add( cameraNX );
  19897. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19898. cameraPY.up.set( 0, 0, 1 );
  19899. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19900. this.add( cameraPY );
  19901. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19902. cameraNY.up.set( 0, 0, -1 );
  19903. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19904. this.add( cameraNY );
  19905. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19906. cameraPZ.up.set( 0, -1, 0 );
  19907. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19908. this.add( cameraPZ );
  19909. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19910. cameraNZ.up.set( 0, -1, 0 );
  19911. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19912. this.add( cameraNZ );
  19913. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19914. this.updateCubeMap = function ( renderer, scene ) {
  19915. var renderTarget = this.renderTarget;
  19916. var generateMipmaps = renderTarget.generateMipmaps;
  19917. renderTarget.generateMipmaps = false;
  19918. renderTarget.activeCubeFace = 0;
  19919. renderer.render( scene, cameraPX, renderTarget );
  19920. renderTarget.activeCubeFace = 1;
  19921. renderer.render( scene, cameraNX, renderTarget );
  19922. renderTarget.activeCubeFace = 2;
  19923. renderer.render( scene, cameraPY, renderTarget );
  19924. renderTarget.activeCubeFace = 3;
  19925. renderer.render( scene, cameraNY, renderTarget );
  19926. renderTarget.activeCubeFace = 4;
  19927. renderer.render( scene, cameraPZ, renderTarget );
  19928. renderTarget.generateMipmaps = generateMipmaps;
  19929. renderTarget.activeCubeFace = 5;
  19930. renderer.render( scene, cameraNZ, renderTarget );
  19931. };
  19932. };
  19933. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19934. /**
  19935. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19936. *
  19937. * A general perpose camera, for setting FOV, Lens Focal Length,
  19938. * and switching between perspective and orthographic views easily.
  19939. * Use this only if you do not wish to manage
  19940. * both a Orthographic and Perspective Camera
  19941. *
  19942. */
  19943. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19944. THREE.Camera.call( this );
  19945. this.fov = fov;
  19946. this.left = -width / 2;
  19947. this.right = width / 2
  19948. this.top = height / 2;
  19949. this.bottom = -height / 2;
  19950. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19951. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19952. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19953. this.zoom = 1;
  19954. this.toPerspective();
  19955. var aspect = width/height;
  19956. };
  19957. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19958. THREE.CombinedCamera.prototype.toPerspective = function () {
  19959. // Switches to the Perspective Camera
  19960. this.near = this.cameraP.near;
  19961. this.far = this.cameraP.far;
  19962. this.cameraP.fov = this.fov / this.zoom ;
  19963. this.cameraP.updateProjectionMatrix();
  19964. this.projectionMatrix = this.cameraP.projectionMatrix;
  19965. this.inPerspectiveMode = true;
  19966. this.inOrthographicMode = false;
  19967. };
  19968. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19969. // Switches to the Orthographic camera estimating viewport from Perspective
  19970. var fov = this.fov;
  19971. var aspect = this.cameraP.aspect;
  19972. var near = this.cameraP.near;
  19973. var far = this.cameraP.far;
  19974. // The size that we set is the mid plane of the viewing frustum
  19975. var hyperfocus = ( near + far ) / 2;
  19976. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19977. var planeHeight = 2 * halfHeight;
  19978. var planeWidth = planeHeight * aspect;
  19979. var halfWidth = planeWidth / 2;
  19980. halfHeight /= this.zoom;
  19981. halfWidth /= this.zoom;
  19982. this.cameraO.left = -halfWidth;
  19983. this.cameraO.right = halfWidth;
  19984. this.cameraO.top = halfHeight;
  19985. this.cameraO.bottom = -halfHeight;
  19986. // this.cameraO.left = -farHalfWidth;
  19987. // this.cameraO.right = farHalfWidth;
  19988. // this.cameraO.top = farHalfHeight;
  19989. // this.cameraO.bottom = -farHalfHeight;
  19990. // this.cameraO.left = this.left / this.zoom;
  19991. // this.cameraO.right = this.right / this.zoom;
  19992. // this.cameraO.top = this.top / this.zoom;
  19993. // this.cameraO.bottom = this.bottom / this.zoom;
  19994. this.cameraO.updateProjectionMatrix();
  19995. this.near = this.cameraO.near;
  19996. this.far = this.cameraO.far;
  19997. this.projectionMatrix = this.cameraO.projectionMatrix;
  19998. this.inPerspectiveMode = false;
  19999. this.inOrthographicMode = true;
  20000. };
  20001. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  20002. this.cameraP.aspect = width / height;
  20003. this.left = -width / 2;
  20004. this.right = width / 2
  20005. this.top = height / 2;
  20006. this.bottom = -height / 2;
  20007. };
  20008. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  20009. this.fov = fov;
  20010. if ( this.inPerspectiveMode ) {
  20011. this.toPerspective();
  20012. } else {
  20013. this.toOrthographic();
  20014. }
  20015. };
  20016. // For mantaining similar API with PerspectiveCamera
  20017. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  20018. if ( this.inPerspectiveMode ) {
  20019. this.toPerspective();
  20020. } else {
  20021. this.toPerspective();
  20022. this.toOrthographic();
  20023. }
  20024. };
  20025. /*
  20026. * Uses Focal Length (in mm) to estimate and set FOV
  20027. * 35mm (fullframe) camera is used if frame size is not specified;
  20028. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  20029. */
  20030. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  20031. if ( frameHeight === undefined ) frameHeight = 24;
  20032. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  20033. this.setFov( fov );
  20034. return fov;
  20035. };
  20036. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  20037. this.zoom = zoom;
  20038. if ( this.inPerspectiveMode ) {
  20039. this.toPerspective();
  20040. } else {
  20041. this.toOrthographic();
  20042. }
  20043. };
  20044. THREE.CombinedCamera.prototype.toFrontView = function() {
  20045. this.rotation.x = 0;
  20046. this.rotation.y = 0;
  20047. this.rotation.z = 0;
  20048. // should we be modifing the matrix instead?
  20049. this.rotationAutoUpdate = false;
  20050. };
  20051. THREE.CombinedCamera.prototype.toBackView = function() {
  20052. this.rotation.x = 0;
  20053. this.rotation.y = Math.PI;
  20054. this.rotation.z = 0;
  20055. this.rotationAutoUpdate = false;
  20056. };
  20057. THREE.CombinedCamera.prototype.toLeftView = function() {
  20058. this.rotation.x = 0;
  20059. this.rotation.y = - Math.PI / 2;
  20060. this.rotation.z = 0;
  20061. this.rotationAutoUpdate = false;
  20062. };
  20063. THREE.CombinedCamera.prototype.toRightView = function() {
  20064. this.rotation.x = 0;
  20065. this.rotation.y = Math.PI / 2;
  20066. this.rotation.z = 0;
  20067. this.rotationAutoUpdate = false;
  20068. };
  20069. THREE.CombinedCamera.prototype.toTopView = function() {
  20070. this.rotation.x = - Math.PI / 2;
  20071. this.rotation.y = 0;
  20072. this.rotation.z = 0;
  20073. this.rotationAutoUpdate = false;
  20074. };
  20075. THREE.CombinedCamera.prototype.toBottomView = function() {
  20076. this.rotation.x = Math.PI / 2;
  20077. this.rotation.y = 0;
  20078. this.rotation.z = 0;
  20079. this.rotationAutoUpdate = false;
  20080. };
  20081. /**
  20082. * @author mrdoob / http://mrdoob.com/
  20083. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  20084. */
  20085. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  20086. THREE.Geometry.call( this );
  20087. this.parameters = {
  20088. width: width,
  20089. height: height,
  20090. depth: depth,
  20091. widthSegments: widthSegments,
  20092. heightSegments: heightSegments,
  20093. depthSegments: depthSegments
  20094. };
  20095. this.widthSegments = widthSegments || 1;
  20096. this.heightSegments = heightSegments || 1;
  20097. this.depthSegments = depthSegments || 1;
  20098. var scope = this;
  20099. var width_half = width / 2;
  20100. var height_half = height / 2;
  20101. var depth_half = depth / 2;
  20102. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  20103. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  20104. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  20105. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  20106. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  20107. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  20108. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  20109. var w, ix, iy,
  20110. gridX = scope.widthSegments,
  20111. gridY = scope.heightSegments,
  20112. width_half = width / 2,
  20113. height_half = height / 2,
  20114. offset = scope.vertices.length;
  20115. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  20116. w = 'z';
  20117. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  20118. w = 'y';
  20119. gridY = scope.depthSegments;
  20120. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  20121. w = 'x';
  20122. gridX = scope.depthSegments;
  20123. }
  20124. var gridX1 = gridX + 1,
  20125. gridY1 = gridY + 1,
  20126. segment_width = width / gridX,
  20127. segment_height = height / gridY,
  20128. normal = new THREE.Vector3();
  20129. normal[ w ] = depth > 0 ? 1 : - 1;
  20130. for ( iy = 0; iy < gridY1; iy ++ ) {
  20131. for ( ix = 0; ix < gridX1; ix ++ ) {
  20132. var vector = new THREE.Vector3();
  20133. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  20134. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  20135. vector[ w ] = depth;
  20136. scope.vertices.push( vector );
  20137. }
  20138. }
  20139. for ( iy = 0; iy < gridY; iy++ ) {
  20140. for ( ix = 0; ix < gridX; ix++ ) {
  20141. var a = ix + gridX1 * iy;
  20142. var b = ix + gridX1 * ( iy + 1 );
  20143. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20144. var d = ( ix + 1 ) + gridX1 * iy;
  20145. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  20146. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  20147. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  20148. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  20149. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  20150. face.normal.copy( normal );
  20151. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20152. face.materialIndex = materialIndex;
  20153. scope.faces.push( face );
  20154. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20155. face = new THREE.Face3( b + offset, c + offset, d + offset );
  20156. face.normal.copy( normal );
  20157. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20158. face.materialIndex = materialIndex;
  20159. scope.faces.push( face );
  20160. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20161. }
  20162. }
  20163. }
  20164. this.mergeVertices();
  20165. };
  20166. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20167. /**
  20168. * @author hughes
  20169. * @author mrdoob / http://mrdoob.com/
  20170. */
  20171. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  20172. this.parameters = {
  20173. radius: radius,
  20174. segments: segments,
  20175. thetaStart: thetaStart,
  20176. thetaLength: thetaLength
  20177. };
  20178. radius = radius || 50;
  20179. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  20180. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20181. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20182. //
  20183. var elements = segments + 2;
  20184. var indices = new Uint16Array( segments * 3 );
  20185. var vertices = new Float32Array( elements * 3 );
  20186. var normals = new Float32Array( elements * 3 );
  20187. var uvs = new Float32Array( elements * 2 );
  20188. // center
  20189. normals[ 2 ] = 1;
  20190. uvs[ 0 ] = 0.5;
  20191. uvs[ 1 ] = 0.5;
  20192. var offset = 0, offset2 = 2, offset3 = 3;
  20193. for ( var i = 0; i <= segments; i ++ ) {
  20194. var segment = thetaStart + i / segments * thetaLength;
  20195. var x = radius * Math.cos( segment );
  20196. var y = radius * Math.sin( segment );
  20197. vertices[ offset3 ] = x;
  20198. vertices[ offset3 + 1 ] = y;
  20199. normals[ offset3 + 2 ] = 1;
  20200. uvs[ offset2 ] = ( x / radius + 1 ) / 2;
  20201. uvs[ offset2 + 1 ] = ( y / radius + 1 ) / 2;
  20202. offset2 += 2;
  20203. offset3 += 3;
  20204. //
  20205. indices[ offset ] = 0;
  20206. indices[ offset + 1 ] = i + 1;
  20207. indices[ offset + 2 ] = i + 2;
  20208. offset += 3;
  20209. }
  20210. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  20211. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20212. };
  20213. THREE.CircleGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  20214. // DEPRECATED
  20215. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  20216. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  20217. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  20218. };
  20219. /**
  20220. * @author mrdoob / http://mrdoob.com/
  20221. */
  20222. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  20223. THREE.Geometry.call( this );
  20224. this.parameters = {
  20225. radiusTop: radiusTop,
  20226. radiusBottom: radiusBottom,
  20227. height: height,
  20228. radialSegments: radialSegments,
  20229. heightSegments: heightSegments,
  20230. openEnded: openEnded
  20231. };
  20232. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  20233. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  20234. height = height !== undefined ? height : 100;
  20235. radialSegments = radialSegments || 8;
  20236. heightSegments = heightSegments || 1;
  20237. openEnded = openEnded !== undefined ? openEnded : false;
  20238. var heightHalf = height / 2;
  20239. var x, y, vertices = [], uvs = [];
  20240. for ( y = 0; y <= heightSegments; y ++ ) {
  20241. var verticesRow = [];
  20242. var uvsRow = [];
  20243. var v = y / heightSegments;
  20244. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20245. for ( x = 0; x <= radialSegments; x ++ ) {
  20246. var u = x / radialSegments;
  20247. var vertex = new THREE.Vector3();
  20248. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  20249. vertex.y = - v * height + heightHalf;
  20250. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  20251. this.vertices.push( vertex );
  20252. verticesRow.push( this.vertices.length - 1 );
  20253. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20254. }
  20255. vertices.push( verticesRow );
  20256. uvs.push( uvsRow );
  20257. }
  20258. var tanTheta = ( radiusBottom - radiusTop ) / height;
  20259. var na, nb;
  20260. for ( x = 0; x < radialSegments; x ++ ) {
  20261. if ( radiusTop !== 0 ) {
  20262. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  20263. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  20264. } else {
  20265. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  20266. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  20267. }
  20268. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  20269. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  20270. for ( y = 0; y < heightSegments; y ++ ) {
  20271. var v1 = vertices[ y ][ x ];
  20272. var v2 = vertices[ y + 1 ][ x ];
  20273. var v3 = vertices[ y + 1 ][ x + 1 ];
  20274. var v4 = vertices[ y ][ x + 1 ];
  20275. var n1 = na.clone();
  20276. var n2 = na.clone();
  20277. var n3 = nb.clone();
  20278. var n4 = nb.clone();
  20279. var uv1 = uvs[ y ][ x ].clone();
  20280. var uv2 = uvs[ y + 1 ][ x ].clone();
  20281. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  20282. var uv4 = uvs[ y ][ x + 1 ].clone();
  20283. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20284. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20285. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20286. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20287. }
  20288. }
  20289. // top cap
  20290. if ( openEnded === false && radiusTop > 0 ) {
  20291. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  20292. for ( x = 0; x < radialSegments; x ++ ) {
  20293. var v1 = vertices[ 0 ][ x ];
  20294. var v2 = vertices[ 0 ][ x + 1 ];
  20295. var v3 = this.vertices.length - 1;
  20296. var n1 = new THREE.Vector3( 0, 1, 0 );
  20297. var n2 = new THREE.Vector3( 0, 1, 0 );
  20298. var n3 = new THREE.Vector3( 0, 1, 0 );
  20299. var uv1 = uvs[ 0 ][ x ].clone();
  20300. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  20301. var uv3 = new THREE.Vector2( uv2.x, 0 );
  20302. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20303. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20304. }
  20305. }
  20306. // bottom cap
  20307. if ( openEnded === false && radiusBottom > 0 ) {
  20308. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  20309. for ( x = 0; x < radialSegments; x ++ ) {
  20310. var v1 = vertices[ y ][ x + 1 ];
  20311. var v2 = vertices[ y ][ x ];
  20312. var v3 = this.vertices.length - 1;
  20313. var n1 = new THREE.Vector3( 0, - 1, 0 );
  20314. var n2 = new THREE.Vector3( 0, - 1, 0 );
  20315. var n3 = new THREE.Vector3( 0, - 1, 0 );
  20316. var uv1 = uvs[ y ][ x + 1 ].clone();
  20317. var uv2 = uvs[ y ][ x ].clone();
  20318. var uv3 = new THREE.Vector2( uv2.x, 1 );
  20319. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20320. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20321. }
  20322. }
  20323. this.computeFaceNormals();
  20324. }
  20325. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20326. /**
  20327. * @author zz85 / http://www.lab4games.net/zz85/blog
  20328. *
  20329. * Creates extruded geometry from a path shape.
  20330. *
  20331. * parameters = {
  20332. *
  20333. * curveSegments: <int>, // number of points on the curves
  20334. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  20335. * amount: <int>, // Depth to extrude the shape
  20336. *
  20337. * bevelEnabled: <bool>, // turn on bevel
  20338. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20339. * bevelSize: <float>, // how far from shape outline is bevel
  20340. * bevelSegments: <int>, // number of bevel layers
  20341. *
  20342. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  20343. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  20344. *
  20345. * material: <int> // material index for front and back faces
  20346. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  20347. * uvGenerator: <Object> // object that provides UV generator functions
  20348. *
  20349. * }
  20350. **/
  20351. THREE.ExtrudeGeometry = function ( shapes, options ) {
  20352. if ( typeof( shapes ) === "undefined" ) {
  20353. shapes = [];
  20354. return;
  20355. }
  20356. THREE.Geometry.call( this );
  20357. shapes = shapes instanceof Array ? shapes : [ shapes ];
  20358. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  20359. this.addShapeList( shapes, options );
  20360. this.computeFaceNormals();
  20361. // can't really use automatic vertex normals
  20362. // as then front and back sides get smoothed too
  20363. // should do separate smoothing just for sides
  20364. //this.computeVertexNormals();
  20365. //console.log( "took", ( Date.now() - startTime ) );
  20366. };
  20367. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20368. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  20369. var sl = shapes.length;
  20370. for ( var s = 0; s < sl; s ++ ) {
  20371. var shape = shapes[ s ];
  20372. this.addShape( shape, options );
  20373. }
  20374. };
  20375. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  20376. var amount = options.amount !== undefined ? options.amount : 100;
  20377. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  20378. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  20379. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20380. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  20381. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20382. var steps = options.steps !== undefined ? options.steps : 1;
  20383. var extrudePath = options.extrudePath;
  20384. var extrudePts, extrudeByPath = false;
  20385. var material = options.material;
  20386. var extrudeMaterial = options.extrudeMaterial;
  20387. // Use default WorldUVGenerator if no UV generators are specified.
  20388. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  20389. var shapebb = this.shapebb;
  20390. //shapebb = shape.getBoundingBox();
  20391. var splineTube, binormal, normal, position2;
  20392. if ( extrudePath ) {
  20393. extrudePts = extrudePath.getSpacedPoints( steps );
  20394. extrudeByPath = true;
  20395. bevelEnabled = false; // bevels not supported for path extrusion
  20396. // SETUP TNB variables
  20397. // Reuse TNB from TubeGeomtry for now.
  20398. // TODO1 - have a .isClosed in spline?
  20399. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  20400. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20401. binormal = new THREE.Vector3();
  20402. normal = new THREE.Vector3();
  20403. position2 = new THREE.Vector3();
  20404. }
  20405. // Safeguards if bevels are not enabled
  20406. if ( ! bevelEnabled ) {
  20407. bevelSegments = 0;
  20408. bevelThickness = 0;
  20409. bevelSize = 0;
  20410. }
  20411. // Variables initalization
  20412. var ahole, h, hl; // looping of holes
  20413. var scope = this;
  20414. var bevelPoints = [];
  20415. var shapesOffset = this.vertices.length;
  20416. var shapePoints = shape.extractPoints( curveSegments );
  20417. var vertices = shapePoints.shape;
  20418. var holes = shapePoints.holes;
  20419. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  20420. if ( reverse ) {
  20421. vertices = vertices.reverse();
  20422. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20423. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20424. ahole = holes[ h ];
  20425. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  20426. holes[ h ] = ahole.reverse();
  20427. }
  20428. }
  20429. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  20430. }
  20431. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  20432. /* Vertices */
  20433. var contour = vertices; // vertices has all points but contour has only points of circumference
  20434. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20435. ahole = holes[ h ];
  20436. vertices = vertices.concat( ahole );
  20437. }
  20438. function scalePt2 ( pt, vec, size ) {
  20439. if ( !vec ) console.log( "die" );
  20440. return vec.clone().multiplyScalar( size ).add( pt );
  20441. }
  20442. var b, bs, t, z,
  20443. vert, vlen = vertices.length,
  20444. face, flen = faces.length,
  20445. cont, clen = contour.length;
  20446. // Find directions for point movement
  20447. var RAD_TO_DEGREES = 180 / Math.PI;
  20448. function getBevelVec( inPt, inPrev, inNext ) {
  20449. var EPSILON = 0.0000000001;
  20450. var sign = THREE.Math.sign;
  20451. // computes for inPt the corresponding point inPt' on a new contour
  20452. // shiftet by 1 unit (length of normalized vector) to the left
  20453. // if we walk along contour clockwise, this new contour is outside the old one
  20454. //
  20455. // inPt' is the intersection of the two lines parallel to the two
  20456. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20457. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  20458. // good reading for geometry algorithms (here: line-line intersection)
  20459. // http://geomalgorithms.com/a05-_intersect-1.html
  20460. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  20461. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  20462. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20463. // check for colinear edges
  20464. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20465. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  20466. // length of vectors for normalizing
  20467. var v_prev_len = Math.sqrt( v_prev_lensq );
  20468. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20469. // shift adjacent points by unit vectors to the left
  20470. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20471. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20472. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20473. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20474. // scaling factor for v_prev to intersection point
  20475. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20476. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20477. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20478. // vector from inPt to intersection point
  20479. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20480. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20481. // Don't normalize!, otherwise sharp corners become ugly
  20482. // but prevent crazy spikes
  20483. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  20484. if ( v_trans_lensq <= 2 ) {
  20485. return new THREE.Vector2( v_trans_x, v_trans_y );
  20486. } else {
  20487. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20488. }
  20489. } else { // handle special case of colinear edges
  20490. var direction_eq = false; // assumes: opposite
  20491. if ( v_prev_x > EPSILON ) {
  20492. if ( v_next_x > EPSILON ) { direction_eq = true; }
  20493. } else {
  20494. if ( v_prev_x < -EPSILON ) {
  20495. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  20496. } else {
  20497. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  20498. }
  20499. }
  20500. if ( direction_eq ) {
  20501. // console.log("Warning: lines are a straight sequence");
  20502. v_trans_x = -v_prev_y;
  20503. v_trans_y = v_prev_x;
  20504. shrink_by = Math.sqrt( v_prev_lensq );
  20505. } else {
  20506. // console.log("Warning: lines are a straight spike");
  20507. v_trans_x = v_prev_x;
  20508. v_trans_y = v_prev_y;
  20509. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20510. }
  20511. }
  20512. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20513. }
  20514. var contourMovements = [];
  20515. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20516. if ( j === il ) j = 0;
  20517. if ( k === il ) k = 0;
  20518. // (j)---(i)---(k)
  20519. // console.log('i,j,k', i, j , k)
  20520. var pt_i = contour[ i ];
  20521. var pt_j = contour[ j ];
  20522. var pt_k = contour[ k ];
  20523. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20524. }
  20525. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  20526. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20527. ahole = holes[ h ];
  20528. oneHoleMovements = [];
  20529. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20530. if ( j === il ) j = 0;
  20531. if ( k === il ) k = 0;
  20532. // (j)---(i)---(k)
  20533. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20534. }
  20535. holesMovements.push( oneHoleMovements );
  20536. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20537. }
  20538. // Loop bevelSegments, 1 for the front, 1 for the back
  20539. for ( b = 0; b < bevelSegments; b ++ ) {
  20540. //for ( b = bevelSegments; b > 0; b -- ) {
  20541. t = b / bevelSegments;
  20542. z = bevelThickness * ( 1 - t );
  20543. //z = bevelThickness * t;
  20544. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  20545. //bs = bevelSize * t ; // linear
  20546. // contract shape
  20547. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20548. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20549. v( vert.x, vert.y, - z );
  20550. }
  20551. // expand holes
  20552. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  20553. ahole = holes[ h ];
  20554. oneHoleMovements = holesMovements[ h ];
  20555. for ( i = 0, il = ahole.length; i < il; i++ ) {
  20556. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20557. v( vert.x, vert.y, -z );
  20558. }
  20559. }
  20560. }
  20561. bs = bevelSize;
  20562. // Back facing vertices
  20563. for ( i = 0; i < vlen; i ++ ) {
  20564. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20565. if ( !extrudeByPath ) {
  20566. v( vert.x, vert.y, 0 );
  20567. } else {
  20568. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20569. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  20570. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  20571. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  20572. v( position2.x, position2.y, position2.z );
  20573. }
  20574. }
  20575. // Add stepped vertices...
  20576. // Including front facing vertices
  20577. var s;
  20578. for ( s = 1; s <= steps; s ++ ) {
  20579. for ( i = 0; i < vlen; i ++ ) {
  20580. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20581. if ( !extrudeByPath ) {
  20582. v( vert.x, vert.y, amount / steps * s );
  20583. } else {
  20584. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20585. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  20586. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  20587. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  20588. v( position2.x, position2.y, position2.z );
  20589. }
  20590. }
  20591. }
  20592. // Add bevel segments planes
  20593. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20594. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20595. t = b / bevelSegments;
  20596. z = bevelThickness * ( 1 - t );
  20597. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  20598. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  20599. // contract shape
  20600. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20601. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20602. v( vert.x, vert.y, amount + z );
  20603. }
  20604. // expand holes
  20605. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20606. ahole = holes[ h ];
  20607. oneHoleMovements = holesMovements[ h ];
  20608. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20609. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20610. if ( !extrudeByPath ) {
  20611. v( vert.x, vert.y, amount + z );
  20612. } else {
  20613. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20614. }
  20615. }
  20616. }
  20617. }
  20618. /* Faces */
  20619. // Top and bottom faces
  20620. buildLidFaces();
  20621. // Sides faces
  20622. buildSideFaces();
  20623. ///// Internal functions
  20624. function buildLidFaces() {
  20625. if ( bevelEnabled ) {
  20626. var layer = 0 ; // steps + 1
  20627. var offset = vlen * layer;
  20628. // Bottom faces
  20629. for ( i = 0; i < flen; i ++ ) {
  20630. face = faces[ i ];
  20631. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  20632. }
  20633. layer = steps + bevelSegments * 2;
  20634. offset = vlen * layer;
  20635. // Top faces
  20636. for ( i = 0; i < flen; i ++ ) {
  20637. face = faces[ i ];
  20638. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  20639. }
  20640. } else {
  20641. // Bottom faces
  20642. for ( i = 0; i < flen; i++ ) {
  20643. face = faces[ i ];
  20644. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  20645. }
  20646. // Top faces
  20647. for ( i = 0; i < flen; i ++ ) {
  20648. face = faces[ i ];
  20649. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  20650. }
  20651. }
  20652. }
  20653. // Create faces for the z-sides of the shape
  20654. function buildSideFaces() {
  20655. var layeroffset = 0;
  20656. sidewalls( contour, layeroffset );
  20657. layeroffset += contour.length;
  20658. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20659. ahole = holes[ h ];
  20660. sidewalls( ahole, layeroffset );
  20661. //, true
  20662. layeroffset += ahole.length;
  20663. }
  20664. }
  20665. function sidewalls( contour, layeroffset ) {
  20666. var j, k;
  20667. i = contour.length;
  20668. while ( --i >= 0 ) {
  20669. j = i;
  20670. k = i - 1;
  20671. if ( k < 0 ) k = contour.length - 1;
  20672. //console.log('b', i,j, i-1, k,vertices.length);
  20673. var s = 0, sl = steps + bevelSegments * 2;
  20674. for ( s = 0; s < sl; s ++ ) {
  20675. var slen1 = vlen * s;
  20676. var slen2 = vlen * ( s + 1 );
  20677. var a = layeroffset + j + slen1,
  20678. b = layeroffset + k + slen1,
  20679. c = layeroffset + k + slen2,
  20680. d = layeroffset + j + slen2;
  20681. f4( a, b, c, d, contour, s, sl, j, k );
  20682. }
  20683. }
  20684. }
  20685. function v( x, y, z ) {
  20686. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  20687. }
  20688. function f3( a, b, c, isBottom ) {
  20689. a += shapesOffset;
  20690. b += shapesOffset;
  20691. c += shapesOffset;
  20692. // normal, color, material
  20693. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20694. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  20695. scope.faceVertexUvs[ 0 ].push( uvs );
  20696. }
  20697. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20698. a += shapesOffset;
  20699. b += shapesOffset;
  20700. c += shapesOffset;
  20701. d += shapesOffset;
  20702. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  20703. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  20704. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  20705. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  20706. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20707. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20708. }
  20709. };
  20710. THREE.ExtrudeGeometry.WorldUVGenerator = {
  20711. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20712. var ax = geometry.vertices[ indexA ].x,
  20713. ay = geometry.vertices[ indexA ].y,
  20714. bx = geometry.vertices[ indexB ].x,
  20715. by = geometry.vertices[ indexB ].y,
  20716. cx = geometry.vertices[ indexC ].x,
  20717. cy = geometry.vertices[ indexC ].y;
  20718. return [
  20719. new THREE.Vector2( ax, ay ),
  20720. new THREE.Vector2( bx, by ),
  20721. new THREE.Vector2( cx, cy )
  20722. ];
  20723. },
  20724. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20725. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  20726. },
  20727. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  20728. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  20729. contourIndex1, contourIndex2 ) {
  20730. var ax = geometry.vertices[ indexA ].x,
  20731. ay = geometry.vertices[ indexA ].y,
  20732. az = geometry.vertices[ indexA ].z,
  20733. bx = geometry.vertices[ indexB ].x,
  20734. by = geometry.vertices[ indexB ].y,
  20735. bz = geometry.vertices[ indexB ].z,
  20736. cx = geometry.vertices[ indexC ].x,
  20737. cy = geometry.vertices[ indexC ].y,
  20738. cz = geometry.vertices[ indexC ].z,
  20739. dx = geometry.vertices[ indexD ].x,
  20740. dy = geometry.vertices[ indexD ].y,
  20741. dz = geometry.vertices[ indexD ].z;
  20742. if ( Math.abs( ay - by ) < 0.01 ) {
  20743. return [
  20744. new THREE.Vector2( ax, 1 - az ),
  20745. new THREE.Vector2( bx, 1 - bz ),
  20746. new THREE.Vector2( cx, 1 - cz ),
  20747. new THREE.Vector2( dx, 1 - dz )
  20748. ];
  20749. } else {
  20750. return [
  20751. new THREE.Vector2( ay, 1 - az ),
  20752. new THREE.Vector2( by, 1 - bz ),
  20753. new THREE.Vector2( cy, 1 - cz ),
  20754. new THREE.Vector2( dy, 1 - dz )
  20755. ];
  20756. }
  20757. }
  20758. };
  20759. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  20760. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  20761. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  20762. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  20763. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  20764. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  20765. /**
  20766. * @author jonobr1 / http://jonobr1.com
  20767. *
  20768. * Creates a one-sided polygonal geometry from a path shape. Similar to
  20769. * ExtrudeGeometry.
  20770. *
  20771. * parameters = {
  20772. *
  20773. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  20774. *
  20775. * material: <int> // material index for front and back faces
  20776. * uvGenerator: <Object> // object that provides UV generator functions
  20777. *
  20778. * }
  20779. **/
  20780. THREE.ShapeGeometry = function ( shapes, options ) {
  20781. THREE.Geometry.call( this );
  20782. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  20783. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  20784. this.addShapeList( shapes, options );
  20785. this.computeFaceNormals();
  20786. };
  20787. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20788. /**
  20789. * Add an array of shapes to THREE.ShapeGeometry.
  20790. */
  20791. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  20792. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  20793. this.addShape( shapes[ i ], options );
  20794. }
  20795. return this;
  20796. };
  20797. /**
  20798. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  20799. */
  20800. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  20801. if ( options === undefined ) options = {};
  20802. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20803. var material = options.material;
  20804. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  20805. var shapebb = this.shapebb;
  20806. //
  20807. var i, l, hole, s;
  20808. var shapesOffset = this.vertices.length;
  20809. var shapePoints = shape.extractPoints( curveSegments );
  20810. var vertices = shapePoints.shape;
  20811. var holes = shapePoints.holes;
  20812. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  20813. if ( reverse ) {
  20814. vertices = vertices.reverse();
  20815. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  20816. for ( i = 0, l = holes.length; i < l; i++ ) {
  20817. hole = holes[ i ];
  20818. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  20819. holes[ i ] = hole.reverse();
  20820. }
  20821. }
  20822. reverse = false;
  20823. }
  20824. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  20825. // Vertices
  20826. var contour = vertices;
  20827. for ( i = 0, l = holes.length; i < l; i++ ) {
  20828. hole = holes[ i ];
  20829. vertices = vertices.concat( hole );
  20830. }
  20831. //
  20832. var vert, vlen = vertices.length;
  20833. var face, flen = faces.length;
  20834. var cont, clen = contour.length;
  20835. for ( i = 0; i < vlen; i++ ) {
  20836. vert = vertices[ i ];
  20837. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  20838. }
  20839. for ( i = 0; i < flen; i++ ) {
  20840. face = faces[ i ];
  20841. var a = face[ 0 ] + shapesOffset;
  20842. var b = face[ 1 ] + shapesOffset;
  20843. var c = face[ 2 ] + shapesOffset;
  20844. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20845. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  20846. }
  20847. };
  20848. /**
  20849. * @author astrodud / http://astrodud.isgreat.org/
  20850. * @author zz85 / https://github.com/zz85
  20851. * @author bhouston / http://exocortex.com
  20852. */
  20853. // points - to create a closed torus, one must use a set of points
  20854. // like so: [ a, b, c, d, a ], see first is the same as last.
  20855. // segments - the number of circumference segments to create
  20856. // phiStart - the starting radian
  20857. // phiLength - the radian (0 to 2*PI) range of the lathed section
  20858. // 2*pi is a closed lathe, less than 2PI is a portion.
  20859. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  20860. THREE.Geometry.call( this );
  20861. segments = segments || 12;
  20862. phiStart = phiStart || 0;
  20863. phiLength = phiLength || 2 * Math.PI;
  20864. var inversePointLength = 1.0 / ( points.length - 1 );
  20865. var inverseSegments = 1.0 / segments;
  20866. for ( var i = 0, il = segments; i <= il; i ++ ) {
  20867. var phi = phiStart + i * inverseSegments * phiLength;
  20868. var c = Math.cos( phi ),
  20869. s = Math.sin( phi );
  20870. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  20871. var pt = points[ j ];
  20872. var vertex = new THREE.Vector3();
  20873. vertex.x = c * pt.x - s * pt.y;
  20874. vertex.y = s * pt.x + c * pt.y;
  20875. vertex.z = pt.z;
  20876. this.vertices.push( vertex );
  20877. }
  20878. }
  20879. var np = points.length;
  20880. for ( var i = 0, il = segments; i < il; i ++ ) {
  20881. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  20882. var base = j + np * i;
  20883. var a = base;
  20884. var b = base + np;
  20885. var c = base + 1 + np;
  20886. var d = base + 1;
  20887. var u0 = i * inverseSegments;
  20888. var v0 = j * inversePointLength;
  20889. var u1 = u0 + inverseSegments;
  20890. var v1 = v0 + inversePointLength;
  20891. this.faces.push( new THREE.Face3( a, b, d ) );
  20892. this.faceVertexUvs[ 0 ].push( [
  20893. new THREE.Vector2( u0, v0 ),
  20894. new THREE.Vector2( u1, v0 ),
  20895. new THREE.Vector2( u0, v1 )
  20896. ] );
  20897. this.faces.push( new THREE.Face3( b, c, d ) );
  20898. this.faceVertexUvs[ 0 ].push( [
  20899. new THREE.Vector2( u1, v0 ),
  20900. new THREE.Vector2( u1, v1 ),
  20901. new THREE.Vector2( u0, v1 )
  20902. ] );
  20903. }
  20904. }
  20905. this.mergeVertices();
  20906. this.computeFaceNormals();
  20907. this.computeVertexNormals();
  20908. };
  20909. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20910. /**
  20911. * @author mrdoob / http://mrdoob.com/
  20912. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20913. */
  20914. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20915. this.parameters = {
  20916. width: width,
  20917. height: height,
  20918. widthSegments: widthSegments,
  20919. heightSegments: heightSegments
  20920. };
  20921. var width_half = width / 2;
  20922. var height_half = height / 2;
  20923. var gridX = widthSegments || 1;
  20924. var gridY = heightSegments || 1;
  20925. var gridX1 = gridX + 1;
  20926. var gridY1 = gridY + 1;
  20927. var segment_width = width / gridX;
  20928. var segment_height = height / gridY;
  20929. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  20930. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  20931. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  20932. var offset = 0;
  20933. var offset2 = 0;
  20934. for ( var iy = 0; iy < gridY1; iy ++ ) {
  20935. var y = iy * segment_height - height_half;
  20936. for ( var ix = 0; ix < gridX1; ix ++ ) {
  20937. var x = ix * segment_width - width_half;
  20938. vertices[ offset ] = x;
  20939. vertices[ offset + 1 ] = - y;
  20940. normals[ offset + 2 ] = 1;
  20941. uvs[ offset2 ] = ix / gridX;
  20942. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  20943. offset += 3;
  20944. offset2 += 2;
  20945. }
  20946. }
  20947. offset = 0;
  20948. var indices = new ( vertices.length > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  20949. for ( var iy = 0; iy < gridY; iy ++ ) {
  20950. for ( var ix = 0; ix < gridX; ix ++ ) {
  20951. var a = ix + gridX1 * iy;
  20952. var b = ix + gridX1 * ( iy + 1 );
  20953. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20954. var d = ( ix + 1 ) + gridX1 * iy;
  20955. indices[ offset ] = a;
  20956. indices[ offset + 1 ] = b;
  20957. indices[ offset + 2 ] = d;
  20958. indices[ offset + 3 ] = b;
  20959. indices[ offset + 4 ] = c;
  20960. indices[ offset + 5 ] = d;
  20961. offset += 6;
  20962. }
  20963. }
  20964. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  20965. };
  20966. THREE.PlaneGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  20967. /**
  20968. * @author Kaleb Murphy
  20969. */
  20970. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20971. THREE.Geometry.call( this );
  20972. innerRadius = innerRadius || 0;
  20973. outerRadius = outerRadius || 50;
  20974. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20975. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20976. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20977. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20978. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20979. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20980. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20981. var vertex = new THREE.Vector3();
  20982. var segment = thetaStart + o / thetaSegments * thetaLength;
  20983. vertex.x = radius * Math.cos( segment );
  20984. vertex.y = radius * Math.sin( segment );
  20985. this.vertices.push( vertex );
  20986. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  20987. }
  20988. radius += radiusStep;
  20989. }
  20990. var n = new THREE.Vector3( 0, 0, 1 );
  20991. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20992. var thetaSegment = i * thetaSegments;
  20993. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20994. var segment = o + thetaSegment;
  20995. var v1 = segment + i;
  20996. var v2 = segment + thetaSegments + i;
  20997. var v3 = segment + thetaSegments + 1 + i;
  20998. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20999. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  21000. v1 = segment + i;
  21001. v2 = segment + thetaSegments + 1 + i;
  21002. v3 = segment + 1 + i;
  21003. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  21004. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  21005. }
  21006. }
  21007. this.computeFaceNormals();
  21008. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21009. };
  21010. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21011. /**
  21012. * @author mrdoob / http://mrdoob.com/
  21013. */
  21014. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21015. THREE.Geometry.call( this );
  21016. this.parameters = {
  21017. radius: radius,
  21018. widthSegments: widthSegments,
  21019. heightSegments: heightSegments,
  21020. phiStart: phiStart,
  21021. phiLength: phiLength,
  21022. thetaStart: thetaStart,
  21023. thetaLength: thetaLength
  21024. };
  21025. radius = radius || 50;
  21026. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21027. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21028. phiStart = phiStart !== undefined ? phiStart : 0;
  21029. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21030. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21031. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21032. var x, y, vertices = [], uvs = [];
  21033. for ( y = 0; y <= heightSegments; y ++ ) {
  21034. var verticesRow = [];
  21035. var uvsRow = [];
  21036. for ( x = 0; x <= widthSegments; x ++ ) {
  21037. var u = x / widthSegments;
  21038. var v = y / heightSegments;
  21039. var vertex = new THREE.Vector3();
  21040. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21041. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21042. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21043. this.vertices.push( vertex );
  21044. verticesRow.push( this.vertices.length - 1 );
  21045. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  21046. }
  21047. vertices.push( verticesRow );
  21048. uvs.push( uvsRow );
  21049. }
  21050. for ( y = 0; y < heightSegments; y ++ ) {
  21051. for ( x = 0; x < widthSegments; x ++ ) {
  21052. var v1 = vertices[ y ][ x + 1 ];
  21053. var v2 = vertices[ y ][ x ];
  21054. var v3 = vertices[ y + 1 ][ x ];
  21055. var v4 = vertices[ y + 1 ][ x + 1 ];
  21056. var n1 = this.vertices[ v1 ].clone().normalize();
  21057. var n2 = this.vertices[ v2 ].clone().normalize();
  21058. var n3 = this.vertices[ v3 ].clone().normalize();
  21059. var n4 = this.vertices[ v4 ].clone().normalize();
  21060. var uv1 = uvs[ y ][ x + 1 ].clone();
  21061. var uv2 = uvs[ y ][ x ].clone();
  21062. var uv3 = uvs[ y + 1 ][ x ].clone();
  21063. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  21064. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  21065. uv1.x = ( uv1.x + uv2.x ) / 2;
  21066. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  21067. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  21068. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  21069. uv3.x = ( uv3.x + uv4.x ) / 2;
  21070. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  21071. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21072. } else {
  21073. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  21074. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  21075. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  21076. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  21077. }
  21078. }
  21079. }
  21080. this.computeFaceNormals();
  21081. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21082. };
  21083. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21084. /**
  21085. * @author zz85 / http://www.lab4games.net/zz85/blog
  21086. * @author alteredq / http://alteredqualia.com/
  21087. *
  21088. * For creating 3D text geometry in three.js
  21089. *
  21090. * Text = 3D Text
  21091. *
  21092. * parameters = {
  21093. * size: <float>, // size of the text
  21094. * height: <float>, // thickness to extrude text
  21095. * curveSegments: <int>, // number of points on the curves
  21096. *
  21097. * font: <string>, // font name
  21098. * weight: <string>, // font weight (normal, bold)
  21099. * style: <string>, // font style (normal, italics)
  21100. *
  21101. * bevelEnabled: <bool>, // turn on bevel
  21102. * bevelThickness: <float>, // how deep into text bevel goes
  21103. * bevelSize: <float>, // how far from text outline is bevel
  21104. * }
  21105. *
  21106. */
  21107. /* Usage Examples
  21108. // TextGeometry wrapper
  21109. var text3d = new TextGeometry( text, options );
  21110. // Complete manner
  21111. var textShapes = THREE.FontUtils.generateShapes( text, options );
  21112. var text3d = new ExtrudeGeometry( textShapes, options );
  21113. */
  21114. THREE.TextGeometry = function ( text, parameters ) {
  21115. parameters = parameters || {};
  21116. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  21117. // translate parameters to ExtrudeGeometry API
  21118. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  21119. // defaults
  21120. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21121. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21122. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21123. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  21124. };
  21125. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  21126. /**
  21127. * @author oosmoxiecode
  21128. * @author mrdoob / http://mrdoob.com/
  21129. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  21130. */
  21131. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  21132. THREE.Geometry.call( this );
  21133. this.parameters = {
  21134. radius: radius,
  21135. tube: tube,
  21136. radialSegments: radialSegments,
  21137. tubularSegments: tubularSegments,
  21138. arc: arc
  21139. };
  21140. radius = radius || 100;
  21141. tube = tube || 40;
  21142. radialSegments = radialSegments || 8;
  21143. tubularSegments = tubularSegments || 6;
  21144. arc = arc || Math.PI * 2;
  21145. var center = new THREE.Vector3(), uvs = [], normals = [];
  21146. for ( var j = 0; j <= radialSegments; j ++ ) {
  21147. for ( var i = 0; i <= tubularSegments; i ++ ) {
  21148. var u = i / tubularSegments * arc;
  21149. var v = j / radialSegments * Math.PI * 2;
  21150. center.x = radius * Math.cos( u );
  21151. center.y = radius * Math.sin( u );
  21152. var vertex = new THREE.Vector3();
  21153. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21154. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21155. vertex.z = tube * Math.sin( v );
  21156. this.vertices.push( vertex );
  21157. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  21158. normals.push( vertex.clone().sub( center ).normalize() );
  21159. }
  21160. }
  21161. for ( var j = 1; j <= radialSegments; j ++ ) {
  21162. for ( var i = 1; i <= tubularSegments; i ++ ) {
  21163. var a = ( tubularSegments + 1 ) * j + i - 1;
  21164. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21165. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21166. var d = ( tubularSegments + 1 ) * j + i;
  21167. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  21168. this.faces.push( face );
  21169. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  21170. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  21171. this.faces.push( face );
  21172. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  21173. }
  21174. }
  21175. this.computeFaceNormals();
  21176. };
  21177. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21178. /**
  21179. * @author oosmoxiecode
  21180. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21181. */
  21182. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  21183. THREE.Geometry.call( this );
  21184. this.parameters = {
  21185. radius: radius,
  21186. tube: tube,
  21187. radialSegments: radialSegments,
  21188. tubularSegments: tubularSegments,
  21189. p: p,
  21190. q: q,
  21191. heightScale: heightScale
  21192. };
  21193. radius = radius || 100;
  21194. tube = tube || 40;
  21195. radialSegments = radialSegments || 64;
  21196. tubularSegments = tubularSegments || 8;
  21197. p = p || 2;
  21198. q = q || 3;
  21199. heightScale = heightScale || 1;
  21200. var grid = new Array( radialSegments );
  21201. var tang = new THREE.Vector3();
  21202. var n = new THREE.Vector3();
  21203. var bitan = new THREE.Vector3();
  21204. for ( var i = 0; i < radialSegments; ++ i ) {
  21205. grid[ i ] = new Array( tubularSegments );
  21206. var u = i / radialSegments * 2 * p * Math.PI;
  21207. var p1 = getPos( u, q, p, radius, heightScale );
  21208. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  21209. tang.subVectors( p2, p1 );
  21210. n.addVectors( p2, p1 );
  21211. bitan.crossVectors( tang, n );
  21212. n.crossVectors( bitan, tang );
  21213. bitan.normalize();
  21214. n.normalize();
  21215. for ( var j = 0; j < tubularSegments; ++ j ) {
  21216. var v = j / tubularSegments * 2 * Math.PI;
  21217. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  21218. var cy = tube * Math.sin( v );
  21219. var pos = new THREE.Vector3();
  21220. pos.x = p1.x + cx * n.x + cy * bitan.x;
  21221. pos.y = p1.y + cx * n.y + cy * bitan.y;
  21222. pos.z = p1.z + cx * n.z + cy * bitan.z;
  21223. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  21224. }
  21225. }
  21226. for ( var i = 0; i < radialSegments; ++ i ) {
  21227. for ( var j = 0; j < tubularSegments; ++ j ) {
  21228. var ip = ( i + 1 ) % radialSegments;
  21229. var jp = ( j + 1 ) % tubularSegments;
  21230. var a = grid[ i ][ j ];
  21231. var b = grid[ ip ][ j ];
  21232. var c = grid[ ip ][ jp ];
  21233. var d = grid[ i ][ jp ];
  21234. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  21235. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  21236. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  21237. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  21238. this.faces.push( new THREE.Face3( a, b, d ) );
  21239. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  21240. this.faces.push( new THREE.Face3( b, c, d ) );
  21241. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  21242. }
  21243. }
  21244. this.computeFaceNormals();
  21245. this.computeVertexNormals();
  21246. function getPos( u, in_q, in_p, radius, heightScale ) {
  21247. var cu = Math.cos( u );
  21248. var su = Math.sin( u );
  21249. var quOverP = in_q / in_p * u;
  21250. var cs = Math.cos( quOverP );
  21251. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  21252. var ty = radius * ( 2 + cs ) * su * 0.5;
  21253. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  21254. return new THREE.Vector3( tx, ty, tz );
  21255. }
  21256. };
  21257. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21258. /**
  21259. * @author WestLangley / https://github.com/WestLangley
  21260. * @author zz85 / https://github.com/zz85
  21261. * @author miningold / https://github.com/miningold
  21262. *
  21263. * Modified from the TorusKnotGeometry by @oosmoxiecode
  21264. *
  21265. * Creates a tube which extrudes along a 3d spline
  21266. *
  21267. * Uses parallel transport frames as described in
  21268. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21269. */
  21270. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  21271. THREE.Geometry.call( this );
  21272. this.parameters = {
  21273. path: path,
  21274. segments: segments,
  21275. radius: radius,
  21276. radialSegments: radialSegments,
  21277. closed: closed
  21278. };
  21279. segments = segments || 64;
  21280. radius = radius || 1;
  21281. radialSegments = radialSegments || 8;
  21282. closed = closed || false;
  21283. var grid = [];
  21284. var scope = this,
  21285. tangent,
  21286. normal,
  21287. binormal,
  21288. numpoints = segments + 1,
  21289. x, y, z,
  21290. tx, ty, tz,
  21291. u, v,
  21292. cx, cy,
  21293. pos, pos2 = new THREE.Vector3(),
  21294. i, j,
  21295. ip, jp,
  21296. a, b, c, d,
  21297. uva, uvb, uvc, uvd;
  21298. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  21299. tangents = frames.tangents,
  21300. normals = frames.normals,
  21301. binormals = frames.binormals;
  21302. // proxy internals
  21303. this.tangents = tangents;
  21304. this.normals = normals;
  21305. this.binormals = binormals;
  21306. function vert( x, y, z ) {
  21307. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  21308. }
  21309. // consruct the grid
  21310. for ( i = 0; i < numpoints; i++ ) {
  21311. grid[ i ] = [];
  21312. u = i / ( numpoints - 1 );
  21313. pos = path.getPointAt( u );
  21314. tangent = tangents[ i ];
  21315. normal = normals[ i ];
  21316. binormal = binormals[ i ];
  21317. for ( j = 0; j < radialSegments; j++ ) {
  21318. v = j / radialSegments * 2 * Math.PI;
  21319. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  21320. cy = radius * Math.sin( v );
  21321. pos2.copy( pos );
  21322. pos2.x += cx * normal.x + cy * binormal.x;
  21323. pos2.y += cx * normal.y + cy * binormal.y;
  21324. pos2.z += cx * normal.z + cy * binormal.z;
  21325. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  21326. }
  21327. }
  21328. // construct the mesh
  21329. for ( i = 0; i < segments; i++ ) {
  21330. for ( j = 0; j < radialSegments; j++ ) {
  21331. ip = ( closed ) ? (i + 1) % segments : i + 1;
  21332. jp = (j + 1) % radialSegments;
  21333. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  21334. b = grid[ ip ][ j ];
  21335. c = grid[ ip ][ jp ];
  21336. d = grid[ i ][ jp ];
  21337. uva = new THREE.Vector2( i / segments, j / radialSegments );
  21338. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  21339. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  21340. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  21341. this.faces.push( new THREE.Face3( a, b, d ) );
  21342. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  21343. this.faces.push( new THREE.Face3( b, c, d ) );
  21344. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  21345. }
  21346. }
  21347. this.computeFaceNormals();
  21348. this.computeVertexNormals();
  21349. };
  21350. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21351. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  21352. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  21353. var tangent = new THREE.Vector3(),
  21354. normal = new THREE.Vector3(),
  21355. binormal = new THREE.Vector3(),
  21356. tangents = [],
  21357. normals = [],
  21358. binormals = [],
  21359. vec = new THREE.Vector3(),
  21360. mat = new THREE.Matrix4(),
  21361. numpoints = segments + 1,
  21362. theta,
  21363. epsilon = 0.0001,
  21364. smallest,
  21365. tx, ty, tz,
  21366. i, u, v;
  21367. // expose internals
  21368. this.tangents = tangents;
  21369. this.normals = normals;
  21370. this.binormals = binormals;
  21371. // compute the tangent vectors for each segment on the path
  21372. for ( i = 0; i < numpoints; i++ ) {
  21373. u = i / ( numpoints - 1 );
  21374. tangents[ i ] = path.getTangentAt( u );
  21375. tangents[ i ].normalize();
  21376. }
  21377. initialNormal3();
  21378. function initialNormal1(lastBinormal) {
  21379. // fixed start binormal. Has dangers of 0 vectors
  21380. normals[ 0 ] = new THREE.Vector3();
  21381. binormals[ 0 ] = new THREE.Vector3();
  21382. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  21383. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  21384. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  21385. }
  21386. function initialNormal2() {
  21387. // This uses the Frenet-Serret formula for deriving binormal
  21388. var t2 = path.getTangentAt( epsilon );
  21389. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  21390. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  21391. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  21392. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  21393. }
  21394. function initialNormal3() {
  21395. // select an initial normal vector perpenicular to the first tangent vector,
  21396. // and in the direction of the smallest tangent xyz component
  21397. normals[ 0 ] = new THREE.Vector3();
  21398. binormals[ 0 ] = new THREE.Vector3();
  21399. smallest = Number.MAX_VALUE;
  21400. tx = Math.abs( tangents[ 0 ].x );
  21401. ty = Math.abs( tangents[ 0 ].y );
  21402. tz = Math.abs( tangents[ 0 ].z );
  21403. if ( tx <= smallest ) {
  21404. smallest = tx;
  21405. normal.set( 1, 0, 0 );
  21406. }
  21407. if ( ty <= smallest ) {
  21408. smallest = ty;
  21409. normal.set( 0, 1, 0 );
  21410. }
  21411. if ( tz <= smallest ) {
  21412. normal.set( 0, 0, 1 );
  21413. }
  21414. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21415. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21416. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21417. }
  21418. // compute the slowly-varying normal and binormal vectors for each segment on the path
  21419. for ( i = 1; i < numpoints; i++ ) {
  21420. normals[ i ] = normals[ i-1 ].clone();
  21421. binormals[ i ] = binormals[ i-1 ].clone();
  21422. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  21423. if ( vec.length() > epsilon ) {
  21424. vec.normalize();
  21425. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  21426. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21427. }
  21428. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21429. }
  21430. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21431. if ( closed ) {
  21432. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  21433. theta /= ( numpoints - 1 );
  21434. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  21435. theta = -theta;
  21436. }
  21437. for ( i = 1; i < numpoints; i++ ) {
  21438. // twist a little...
  21439. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21440. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21441. }
  21442. }
  21443. };
  21444. /**
  21445. * @author clockworkgeek / https://github.com/clockworkgeek
  21446. * @author timothypratley / https://github.com/timothypratley
  21447. * @author WestLangley / http://github.com/WestLangley
  21448. */
  21449. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  21450. THREE.Geometry.call( this );
  21451. radius = radius || 1;
  21452. detail = detail || 0;
  21453. var that = this;
  21454. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  21455. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  21456. }
  21457. var midpoints = [], p = this.vertices;
  21458. var faces = [];
  21459. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  21460. var v1 = p[ indices[ i ] ];
  21461. var v2 = p[ indices[ i + 1 ] ];
  21462. var v3 = p[ indices[ i + 2 ] ];
  21463. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  21464. }
  21465. var centroid = new THREE.Vector3();
  21466. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21467. subdivide( faces[ i ], detail );
  21468. }
  21469. // Handle case when face straddles the seam
  21470. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  21471. var uvs = this.faceVertexUvs[ 0 ][ i ];
  21472. var x0 = uvs[ 0 ].x;
  21473. var x1 = uvs[ 1 ].x;
  21474. var x2 = uvs[ 2 ].x;
  21475. var max = Math.max( x0, Math.max( x1, x2 ) );
  21476. var min = Math.min( x0, Math.min( x1, x2 ) );
  21477. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  21478. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  21479. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  21480. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  21481. }
  21482. }
  21483. // Apply radius
  21484. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  21485. this.vertices[ i ].multiplyScalar( radius );
  21486. }
  21487. // Merge vertices
  21488. this.mergeVertices();
  21489. this.computeFaceNormals();
  21490. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21491. // Project vector onto sphere's surface
  21492. function prepare( vector ) {
  21493. var vertex = vector.normalize().clone();
  21494. vertex.index = that.vertices.push( vertex ) - 1;
  21495. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  21496. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  21497. var v = inclination( vector ) / Math.PI + 0.5;
  21498. vertex.uv = new THREE.Vector2( u, 1 - v );
  21499. return vertex;
  21500. }
  21501. // Approximate a curved face with recursively sub-divided triangles.
  21502. function make( v1, v2, v3 ) {
  21503. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  21504. that.faces.push( face );
  21505. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  21506. var azi = azimuth( centroid );
  21507. that.faceVertexUvs[ 0 ].push( [
  21508. correctUV( v1.uv, v1, azi ),
  21509. correctUV( v2.uv, v2, azi ),
  21510. correctUV( v3.uv, v3, azi )
  21511. ] );
  21512. }
  21513. // Analytically subdivide a face to the required detail level.
  21514. function subdivide( face, detail ) {
  21515. var cols = Math.pow(2, detail);
  21516. var cells = Math.pow(4, detail);
  21517. var a = prepare( that.vertices[ face.a ] );
  21518. var b = prepare( that.vertices[ face.b ] );
  21519. var c = prepare( that.vertices[ face.c ] );
  21520. var v = [];
  21521. // Construct all of the vertices for this subdivision.
  21522. for ( var i = 0 ; i <= cols; i ++ ) {
  21523. v[ i ] = [];
  21524. var aj = prepare( a.clone().lerp( c, i / cols ) );
  21525. var bj = prepare( b.clone().lerp( c, i / cols ) );
  21526. var rows = cols - i;
  21527. for ( var j = 0; j <= rows; j ++) {
  21528. if ( j == 0 && i == cols ) {
  21529. v[ i ][ j ] = aj;
  21530. } else {
  21531. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  21532. }
  21533. }
  21534. }
  21535. // Construct all of the faces.
  21536. for ( var i = 0; i < cols ; i ++ ) {
  21537. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  21538. var k = Math.floor( j / 2 );
  21539. if ( j % 2 == 0 ) {
  21540. make(
  21541. v[ i ][ k + 1],
  21542. v[ i + 1 ][ k ],
  21543. v[ i ][ k ]
  21544. );
  21545. } else {
  21546. make(
  21547. v[ i ][ k + 1 ],
  21548. v[ i + 1][ k + 1],
  21549. v[ i + 1 ][ k ]
  21550. );
  21551. }
  21552. }
  21553. }
  21554. }
  21555. // Angle around the Y axis, counter-clockwise when looking from above.
  21556. function azimuth( vector ) {
  21557. return Math.atan2( vector.z, -vector.x );
  21558. }
  21559. // Angle above the XZ plane.
  21560. function inclination( vector ) {
  21561. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21562. }
  21563. // Texture fixing helper. Spheres have some odd behaviours.
  21564. function correctUV( uv, vector, azimuth ) {
  21565. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  21566. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  21567. return uv.clone();
  21568. }
  21569. };
  21570. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21571. /**
  21572. * @author timothypratley / https://github.com/timothypratley
  21573. */
  21574. THREE.IcosahedronGeometry = function ( radius, detail ) {
  21575. this.parameters = {
  21576. radius: radius,
  21577. detail: detail
  21578. };
  21579. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21580. var vertices = [
  21581. -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  21582. 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
  21583. t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
  21584. ];
  21585. var indices = [
  21586. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21587. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21588. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21589. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21590. ];
  21591. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21592. };
  21593. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21594. /**
  21595. * @author timothypratley / https://github.com/timothypratley
  21596. */
  21597. THREE.OctahedronGeometry = function ( radius, detail ) {
  21598. this.parameters = {
  21599. radius: radius,
  21600. detail: detail
  21601. };
  21602. var vertices = [
  21603. 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1
  21604. ];
  21605. var indices = [
  21606. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  21607. ];
  21608. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21609. };
  21610. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21611. /**
  21612. * @author timothypratley / https://github.com/timothypratley
  21613. */
  21614. THREE.TetrahedronGeometry = function ( radius, detail ) {
  21615. var vertices = [
  21616. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  21617. ];
  21618. var indices = [
  21619. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21620. ];
  21621. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21622. };
  21623. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21624. /**
  21625. * @author zz85 / https://github.com/zz85
  21626. * Parametric Surfaces Geometry
  21627. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  21628. *
  21629. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  21630. *
  21631. */
  21632. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  21633. THREE.Geometry.call( this );
  21634. var verts = this.vertices;
  21635. var faces = this.faces;
  21636. var uvs = this.faceVertexUvs[ 0 ];
  21637. var i, il, j, p;
  21638. var u, v;
  21639. var stackCount = stacks + 1;
  21640. var sliceCount = slices + 1;
  21641. for ( i = 0; i <= stacks; i ++ ) {
  21642. v = i / stacks;
  21643. for ( j = 0; j <= slices; j ++ ) {
  21644. u = j / slices;
  21645. p = func( u, v );
  21646. verts.push( p );
  21647. }
  21648. }
  21649. var a, b, c, d;
  21650. var uva, uvb, uvc, uvd;
  21651. for ( i = 0; i < stacks; i ++ ) {
  21652. for ( j = 0; j < slices; j ++ ) {
  21653. a = i * sliceCount + j;
  21654. b = i * sliceCount + j + 1;
  21655. c = (i + 1) * sliceCount + j + 1;
  21656. d = (i + 1) * sliceCount + j;
  21657. uva = new THREE.Vector2( j / slices, i / stacks );
  21658. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  21659. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  21660. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  21661. faces.push( new THREE.Face3( a, b, d ) );
  21662. uvs.push( [ uva, uvb, uvd ] );
  21663. faces.push( new THREE.Face3( b, c, d ) );
  21664. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  21665. }
  21666. }
  21667. // console.log(this);
  21668. // magic bullet
  21669. // var diff = this.mergeVertices();
  21670. // console.log('removed ', diff, ' vertices by merging');
  21671. this.computeFaceNormals();
  21672. this.computeVertexNormals();
  21673. };
  21674. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21675. /**
  21676. * @author sroucheray / http://sroucheray.org/
  21677. * @author mrdoob / http://mrdoob.com/
  21678. */
  21679. THREE.AxisHelper = function ( size ) {
  21680. size = size || 1;
  21681. var geometry = new THREE.Geometry();
  21682. geometry.vertices.push(
  21683. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  21684. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  21685. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  21686. );
  21687. geometry.colors.push(
  21688. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  21689. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  21690. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  21691. );
  21692. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21693. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21694. };
  21695. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  21696. /**
  21697. * @author WestLangley / http://github.com/WestLangley
  21698. * @author zz85 / http://github.com/zz85
  21699. * @author bhouston / http://exocortex.com
  21700. *
  21701. * Creates an arrow for visualizing directions
  21702. *
  21703. * Parameters:
  21704. * dir - Vector3
  21705. * origin - Vector3
  21706. * length - Number
  21707. * hex - color in hex value
  21708. * headLength - Number
  21709. * headWidth - Number
  21710. */
  21711. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  21712. // dir is assumed to be normalized
  21713. THREE.Object3D.call( this );
  21714. if ( hex === undefined ) hex = 0xffff00;
  21715. if ( length === undefined ) length = 1;
  21716. if ( headLength === undefined ) headLength = 0.2 * length;
  21717. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21718. this.position = origin;
  21719. var lineGeometry = new THREE.Geometry();
  21720. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  21721. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  21722. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  21723. this.line.matrixAutoUpdate = false;
  21724. this.add( this.line );
  21725. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21726. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  21727. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  21728. this.cone.matrixAutoUpdate = false;
  21729. this.add( this.cone );
  21730. this.setDirection( dir );
  21731. this.setLength( length, headLength, headWidth );
  21732. };
  21733. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  21734. THREE.ArrowHelper.prototype.setDirection = function () {
  21735. var axis = new THREE.Vector3();
  21736. var radians;
  21737. return function ( dir ) {
  21738. // dir is assumed to be normalized
  21739. if ( dir.y > 0.99999 ) {
  21740. this.quaternion.set( 0, 0, 0, 1 );
  21741. } else if ( dir.y < - 0.99999 ) {
  21742. this.quaternion.set( 1, 0, 0, 0 );
  21743. } else {
  21744. axis.set( dir.z, 0, - dir.x ).normalize();
  21745. radians = Math.acos( dir.y );
  21746. this.quaternion.setFromAxisAngle( axis, radians );
  21747. }
  21748. };
  21749. }();
  21750. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  21751. if ( headLength === undefined ) headLength = 0.2 * length;
  21752. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21753. this.line.scale.set( 1, length, 1 );
  21754. this.line.updateMatrix();
  21755. this.cone.scale.set( headWidth, headLength, headWidth );
  21756. this.cone.position.y = length;
  21757. this.cone.updateMatrix();
  21758. };
  21759. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  21760. this.line.material.color.setHex( hex );
  21761. this.cone.material.color.setHex( hex );
  21762. };
  21763. /**
  21764. * @author mrdoob / http://mrdoob.com/
  21765. */
  21766. THREE.BoxHelper = function ( object ) {
  21767. // 5____4
  21768. // 1/___0/|
  21769. // | 6__|_7
  21770. // 2/___3/
  21771. var vertices = [
  21772. new THREE.Vector3( 1, 1, 1 ),
  21773. new THREE.Vector3( - 1, 1, 1 ),
  21774. new THREE.Vector3( - 1, - 1, 1 ),
  21775. new THREE.Vector3( 1, - 1, 1 ),
  21776. new THREE.Vector3( 1, 1, - 1 ),
  21777. new THREE.Vector3( - 1, 1, - 1 ),
  21778. new THREE.Vector3( - 1, - 1, - 1 ),
  21779. new THREE.Vector3( 1, - 1, - 1 )
  21780. ];
  21781. this.vertices = vertices;
  21782. // TODO: Wouldn't be nice if Line had .segments?
  21783. var geometry = new THREE.Geometry();
  21784. geometry.vertices.push(
  21785. vertices[ 0 ], vertices[ 1 ],
  21786. vertices[ 1 ], vertices[ 2 ],
  21787. vertices[ 2 ], vertices[ 3 ],
  21788. vertices[ 3 ], vertices[ 0 ],
  21789. vertices[ 4 ], vertices[ 5 ],
  21790. vertices[ 5 ], vertices[ 6 ],
  21791. vertices[ 6 ], vertices[ 7 ],
  21792. vertices[ 7 ], vertices[ 4 ],
  21793. vertices[ 0 ], vertices[ 4 ],
  21794. vertices[ 1 ], vertices[ 5 ],
  21795. vertices[ 2 ], vertices[ 6 ],
  21796. vertices[ 3 ], vertices[ 7 ]
  21797. );
  21798. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  21799. if ( object !== undefined ) {
  21800. this.update( object );
  21801. }
  21802. };
  21803. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  21804. THREE.BoxHelper.prototype.update = function ( object ) {
  21805. var geometry = object.geometry;
  21806. if ( geometry.boundingBox === null ) {
  21807. geometry.computeBoundingBox();
  21808. }
  21809. var min = geometry.boundingBox.min;
  21810. var max = geometry.boundingBox.max;
  21811. var vertices = this.vertices;
  21812. vertices[ 0 ].set( max.x, max.y, max.z );
  21813. vertices[ 1 ].set( min.x, max.y, max.z );
  21814. vertices[ 2 ].set( min.x, min.y, max.z );
  21815. vertices[ 3 ].set( max.x, min.y, max.z );
  21816. vertices[ 4 ].set( max.x, max.y, min.z );
  21817. vertices[ 5 ].set( min.x, max.y, min.z );
  21818. vertices[ 6 ].set( min.x, min.y, min.z );
  21819. vertices[ 7 ].set( max.x, min.y, min.z );
  21820. this.geometry.computeBoundingSphere();
  21821. this.geometry.verticesNeedUpdate = true;
  21822. this.matrixAutoUpdate = false;
  21823. this.matrixWorld = object.matrixWorld;
  21824. };
  21825. /**
  21826. * @author WestLangley / http://github.com/WestLangley
  21827. */
  21828. // a helper to show the world-axis-aligned bounding box for an object
  21829. THREE.BoundingBoxHelper = function ( object, hex ) {
  21830. var color = ( hex !== undefined ) ? hex : 0x888888;
  21831. this.object = object;
  21832. this.box = new THREE.Box3();
  21833. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  21834. };
  21835. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  21836. THREE.BoundingBoxHelper.prototype.update = function () {
  21837. this.box.setFromObject( this.object );
  21838. this.box.size( this.scale );
  21839. this.box.center( this.position );
  21840. };
  21841. /**
  21842. * @author alteredq / http://alteredqualia.com/
  21843. *
  21844. * - shows frustum, line of sight and up of the camera
  21845. * - suitable for fast updates
  21846. * - based on frustum visualization in lightgl.js shadowmap example
  21847. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  21848. */
  21849. THREE.CameraHelper = function ( camera ) {
  21850. var geometry = new THREE.Geometry();
  21851. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  21852. var pointMap = {};
  21853. // colors
  21854. var hexFrustum = 0xffaa00;
  21855. var hexCone = 0xff0000;
  21856. var hexUp = 0x00aaff;
  21857. var hexTarget = 0xffffff;
  21858. var hexCross = 0x333333;
  21859. // near
  21860. addLine( "n1", "n2", hexFrustum );
  21861. addLine( "n2", "n4", hexFrustum );
  21862. addLine( "n4", "n3", hexFrustum );
  21863. addLine( "n3", "n1", hexFrustum );
  21864. // far
  21865. addLine( "f1", "f2", hexFrustum );
  21866. addLine( "f2", "f4", hexFrustum );
  21867. addLine( "f4", "f3", hexFrustum );
  21868. addLine( "f3", "f1", hexFrustum );
  21869. // sides
  21870. addLine( "n1", "f1", hexFrustum );
  21871. addLine( "n2", "f2", hexFrustum );
  21872. addLine( "n3", "f3", hexFrustum );
  21873. addLine( "n4", "f4", hexFrustum );
  21874. // cone
  21875. addLine( "p", "n1", hexCone );
  21876. addLine( "p", "n2", hexCone );
  21877. addLine( "p", "n3", hexCone );
  21878. addLine( "p", "n4", hexCone );
  21879. // up
  21880. addLine( "u1", "u2", hexUp );
  21881. addLine( "u2", "u3", hexUp );
  21882. addLine( "u3", "u1", hexUp );
  21883. // target
  21884. addLine( "c", "t", hexTarget );
  21885. addLine( "p", "c", hexCross );
  21886. // cross
  21887. addLine( "cn1", "cn2", hexCross );
  21888. addLine( "cn3", "cn4", hexCross );
  21889. addLine( "cf1", "cf2", hexCross );
  21890. addLine( "cf3", "cf4", hexCross );
  21891. function addLine( a, b, hex ) {
  21892. addPoint( a, hex );
  21893. addPoint( b, hex );
  21894. }
  21895. function addPoint( id, hex ) {
  21896. geometry.vertices.push( new THREE.Vector3() );
  21897. geometry.colors.push( new THREE.Color( hex ) );
  21898. if ( pointMap[ id ] === undefined ) {
  21899. pointMap[ id ] = [];
  21900. }
  21901. pointMap[ id ].push( geometry.vertices.length - 1 );
  21902. }
  21903. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21904. this.camera = camera;
  21905. this.matrixWorld = camera.matrixWorld;
  21906. this.matrixAutoUpdate = false;
  21907. this.pointMap = pointMap;
  21908. this.update();
  21909. };
  21910. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  21911. THREE.CameraHelper.prototype.update = function () {
  21912. var vector = new THREE.Vector3();
  21913. var camera = new THREE.Camera();
  21914. var projector = new THREE.Projector();
  21915. return function () {
  21916. var scope = this;
  21917. var w = 1, h = 1;
  21918. // we need just camera projection matrix
  21919. // world matrix must be identity
  21920. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  21921. // center / target
  21922. setPoint( "c", 0, 0, -1 );
  21923. setPoint( "t", 0, 0, 1 );
  21924. // near
  21925. setPoint( "n1", -w, -h, -1 );
  21926. setPoint( "n2", w, -h, -1 );
  21927. setPoint( "n3", -w, h, -1 );
  21928. setPoint( "n4", w, h, -1 );
  21929. // far
  21930. setPoint( "f1", -w, -h, 1 );
  21931. setPoint( "f2", w, -h, 1 );
  21932. setPoint( "f3", -w, h, 1 );
  21933. setPoint( "f4", w, h, 1 );
  21934. // up
  21935. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  21936. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  21937. setPoint( "u3", 0, h * 2, -1 );
  21938. // cross
  21939. setPoint( "cf1", -w, 0, 1 );
  21940. setPoint( "cf2", w, 0, 1 );
  21941. setPoint( "cf3", 0, -h, 1 );
  21942. setPoint( "cf4", 0, h, 1 );
  21943. setPoint( "cn1", -w, 0, -1 );
  21944. setPoint( "cn2", w, 0, -1 );
  21945. setPoint( "cn3", 0, -h, -1 );
  21946. setPoint( "cn4", 0, h, -1 );
  21947. function setPoint( point, x, y, z ) {
  21948. vector.set( x, y, z );
  21949. projector.unprojectVector( vector, camera );
  21950. var points = scope.pointMap[ point ];
  21951. if ( points !== undefined ) {
  21952. for ( var i = 0, il = points.length; i < il; i ++ ) {
  21953. scope.geometry.vertices[ points[ i ] ].copy( vector );
  21954. }
  21955. }
  21956. }
  21957. this.geometry.verticesNeedUpdate = true;
  21958. };
  21959. }();
  21960. /**
  21961. * @author alteredq / http://alteredqualia.com/
  21962. * @author mrdoob / http://mrdoob.com/
  21963. * @author WestLangley / http://github.com/WestLangley
  21964. */
  21965. THREE.DirectionalLightHelper = function ( light, size ) {
  21966. THREE.Object3D.call( this );
  21967. this.light = light;
  21968. this.light.updateMatrixWorld();
  21969. this.matrixWorld = light.matrixWorld;
  21970. this.matrixAutoUpdate = false;
  21971. size = size || 1;
  21972. var geometry = new THREE.Geometry();
  21973. geometry.vertices.push(
  21974. new THREE.Vector3( - size, size, 0 ),
  21975. new THREE.Vector3( size, size, 0 ),
  21976. new THREE.Vector3( size, - size, 0 ),
  21977. new THREE.Vector3( - size, - size, 0 ),
  21978. new THREE.Vector3( - size, size, 0 )
  21979. );
  21980. var material = new THREE.LineBasicMaterial( { fog: false } );
  21981. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21982. this.lightPlane = new THREE.Line( geometry, material );
  21983. this.add( this.lightPlane );
  21984. geometry = new THREE.Geometry();
  21985. geometry.vertices.push(
  21986. new THREE.Vector3(),
  21987. new THREE.Vector3()
  21988. );
  21989. material = new THREE.LineBasicMaterial( { fog: false } );
  21990. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21991. this.targetLine = new THREE.Line( geometry, material );
  21992. this.add( this.targetLine );
  21993. this.update();
  21994. };
  21995. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21996. THREE.DirectionalLightHelper.prototype.dispose = function () {
  21997. this.lightPlane.geometry.dispose();
  21998. this.lightPlane.material.dispose();
  21999. this.targetLine.geometry.dispose();
  22000. this.targetLine.material.dispose();
  22001. };
  22002. THREE.DirectionalLightHelper.prototype.update = function () {
  22003. var v1 = new THREE.Vector3();
  22004. var v2 = new THREE.Vector3();
  22005. var v3 = new THREE.Vector3();
  22006. return function () {
  22007. v1.setFromMatrixPosition( this.light.matrixWorld );
  22008. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22009. v3.subVectors( v2, v1 );
  22010. this.lightPlane.lookAt( v3 );
  22011. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22012. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  22013. this.targetLine.geometry.verticesNeedUpdate = true;
  22014. this.targetLine.material.color.copy( this.lightPlane.material.color );
  22015. }
  22016. }();
  22017. /**
  22018. * @author WestLangley / http://github.com/WestLangley
  22019. */
  22020. THREE.EdgesHelper = function ( object, hex ) {
  22021. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22022. var edge = [ 0, 0 ], hash = {};
  22023. var sortFunction = function ( a, b ) { return a - b };
  22024. var keys = [ 'a', 'b', 'c' ];
  22025. var geometry = new THREE.BufferGeometry();
  22026. var geometry2 = object.geometry.clone();
  22027. geometry2.mergeVertices();
  22028. geometry2.computeFaceNormals();
  22029. var vertices = geometry2.vertices;
  22030. var faces = geometry2.faces;
  22031. var numEdges = 0;
  22032. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22033. var face = faces[ i ];
  22034. for ( var j = 0; j < 3; j ++ ) {
  22035. edge[ 0 ] = face[ keys[ j ] ];
  22036. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22037. edge.sort( sortFunction );
  22038. var key = edge.toString();
  22039. if ( hash[ key ] === undefined ) {
  22040. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  22041. numEdges ++;
  22042. } else {
  22043. hash[ key ].face2 = i;
  22044. }
  22045. }
  22046. }
  22047. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  22048. var coords = geometry.attributes.position.array;
  22049. var index = 0;
  22050. for ( var key in hash ) {
  22051. var h = hash[ key ];
  22052. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  22053. var vertex = vertices[ h.vert1 ];
  22054. coords[ index ++ ] = vertex.x;
  22055. coords[ index ++ ] = vertex.y;
  22056. coords[ index ++ ] = vertex.z;
  22057. vertex = vertices[ h.vert2 ];
  22058. coords[ index ++ ] = vertex.x;
  22059. coords[ index ++ ] = vertex.y;
  22060. coords[ index ++ ] = vertex.z;
  22061. }
  22062. }
  22063. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  22064. this.matrixAutoUpdate = false;
  22065. this.matrixWorld = object.matrixWorld;
  22066. };
  22067. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  22068. /**
  22069. * @author mrdoob / http://mrdoob.com/
  22070. * @author WestLangley / http://github.com/WestLangley
  22071. */
  22072. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  22073. this.object = object;
  22074. this.size = ( size !== undefined ) ? size : 1;
  22075. var color = ( hex !== undefined ) ? hex : 0xffff00;
  22076. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22077. var geometry = new THREE.Geometry();
  22078. var faces = this.object.geometry.faces;
  22079. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22080. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  22081. }
  22082. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  22083. this.matrixAutoUpdate = false;
  22084. this.normalMatrix = new THREE.Matrix3();
  22085. this.update();
  22086. };
  22087. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  22088. THREE.FaceNormalsHelper.prototype.update = function () {
  22089. var vertices = this.geometry.vertices;
  22090. var object = this.object;
  22091. var objectVertices = object.geometry.vertices;
  22092. var objectFaces = object.geometry.faces;
  22093. var objectWorldMatrix = object.matrixWorld;
  22094. object.updateMatrixWorld( true );
  22095. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  22096. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  22097. var face = objectFaces[ i ];
  22098. vertices[ i2 ].copy( objectVertices[ face.a ] )
  22099. .add( objectVertices[ face.b ] )
  22100. .add( objectVertices[ face.c ] )
  22101. .divideScalar( 3 )
  22102. .applyMatrix4( objectWorldMatrix );
  22103. vertices[ i2 + 1 ].copy( face.normal )
  22104. .applyMatrix3( this.normalMatrix )
  22105. .normalize()
  22106. .multiplyScalar( this.size )
  22107. .add( vertices[ i2 ] );
  22108. }
  22109. this.geometry.verticesNeedUpdate = true;
  22110. return this;
  22111. };
  22112. /**
  22113. * @author mrdoob / http://mrdoob.com/
  22114. */
  22115. THREE.GridHelper = function ( size, step ) {
  22116. var geometry = new THREE.Geometry();
  22117. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  22118. this.color1 = new THREE.Color( 0x444444 );
  22119. this.color2 = new THREE.Color( 0x888888 );
  22120. for ( var i = - size; i <= size; i += step ) {
  22121. geometry.vertices.push(
  22122. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  22123. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  22124. );
  22125. var color = i === 0 ? this.color1 : this.color2;
  22126. geometry.colors.push( color, color, color, color );
  22127. }
  22128. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  22129. };
  22130. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  22131. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  22132. this.color1.set( colorCenterLine );
  22133. this.color2.set( colorGrid );
  22134. this.geometry.colorsNeedUpdate = true;
  22135. }
  22136. /**
  22137. * @author alteredq / http://alteredqualia.com/
  22138. * @author mrdoob / http://mrdoob.com/
  22139. */
  22140. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  22141. THREE.Object3D.call( this );
  22142. this.light = light;
  22143. this.light.updateMatrixWorld();
  22144. this.matrixWorld = light.matrixWorld;
  22145. this.matrixAutoUpdate = false;
  22146. this.colors = [ new THREE.Color(), new THREE.Color() ];
  22147. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  22148. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  22149. for ( var i = 0, il = 8; i < il; i ++ ) {
  22150. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  22151. }
  22152. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  22153. this.lightSphere = new THREE.Mesh( geometry, material );
  22154. this.add( this.lightSphere );
  22155. this.update();
  22156. };
  22157. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  22158. THREE.HemisphereLightHelper.prototype.dispose = function () {
  22159. this.lightSphere.geometry.dispose();
  22160. this.lightSphere.material.dispose();
  22161. };
  22162. THREE.HemisphereLightHelper.prototype.update = function () {
  22163. var vector = new THREE.Vector3();
  22164. return function () {
  22165. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  22166. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  22167. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22168. this.lightSphere.geometry.colorsNeedUpdate = true;
  22169. }
  22170. }();
  22171. /**
  22172. * @author alteredq / http://alteredqualia.com/
  22173. * @author mrdoob / http://mrdoob.com/
  22174. */
  22175. THREE.PointLightHelper = function ( light, sphereSize ) {
  22176. this.light = light;
  22177. this.light.updateMatrixWorld();
  22178. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  22179. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  22180. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22181. THREE.Mesh.call( this, geometry, material );
  22182. this.matrixWorld = this.light.matrixWorld;
  22183. this.matrixAutoUpdate = false;
  22184. /*
  22185. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22186. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22187. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22188. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22189. var d = light.distance;
  22190. if ( d === 0.0 ) {
  22191. this.lightDistance.visible = false;
  22192. } else {
  22193. this.lightDistance.scale.set( d, d, d );
  22194. }
  22195. this.add( this.lightDistance );
  22196. */
  22197. };
  22198. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  22199. THREE.PointLightHelper.prototype.dispose = function () {
  22200. this.geometry.dispose();
  22201. this.material.dispose();
  22202. };
  22203. THREE.PointLightHelper.prototype.update = function () {
  22204. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22205. /*
  22206. var d = this.light.distance;
  22207. if ( d === 0.0 ) {
  22208. this.lightDistance.visible = false;
  22209. } else {
  22210. this.lightDistance.visible = true;
  22211. this.lightDistance.scale.set( d, d, d );
  22212. }
  22213. */
  22214. };
  22215. /**
  22216. * @author alteredq / http://alteredqualia.com/
  22217. * @author mrdoob / http://mrdoob.com/
  22218. * @author WestLangley / http://github.com/WestLangley
  22219. */
  22220. THREE.SpotLightHelper = function ( light ) {
  22221. THREE.Object3D.call( this );
  22222. this.light = light;
  22223. this.light.updateMatrixWorld();
  22224. this.matrixWorld = light.matrixWorld;
  22225. this.matrixAutoUpdate = false;
  22226. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  22227. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  22228. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  22229. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  22230. this.cone = new THREE.Mesh( geometry, material );
  22231. this.add( this.cone );
  22232. this.update();
  22233. };
  22234. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  22235. THREE.SpotLightHelper.prototype.dispose = function () {
  22236. this.cone.geometry.dispose();
  22237. this.cone.material.dispose();
  22238. };
  22239. THREE.SpotLightHelper.prototype.update = function () {
  22240. var vector = new THREE.Vector3();
  22241. var vector2 = new THREE.Vector3();
  22242. return function () {
  22243. var coneLength = this.light.distance ? this.light.distance : 10000;
  22244. var coneWidth = coneLength * Math.tan( this.light.angle );
  22245. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22246. vector.setFromMatrixPosition( this.light.matrixWorld );
  22247. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  22248. this.cone.lookAt( vector2.sub( vector ) );
  22249. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22250. };
  22251. }();
  22252. /**
  22253. * @author mrdoob / http://mrdoob.com/
  22254. * @author WestLangley / http://github.com/WestLangley
  22255. */
  22256. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  22257. this.object = object;
  22258. this.size = ( size !== undefined ) ? size : 1;
  22259. var color = ( hex !== undefined ) ? hex : 0xff0000;
  22260. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22261. var geometry = new THREE.Geometry();
  22262. var vertices = object.geometry.vertices;
  22263. var faces = object.geometry.faces;
  22264. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22265. var face = faces[ i ];
  22266. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  22267. geometry.vertices.push( new THREE.Vector3() );
  22268. geometry.vertices.push( new THREE.Vector3() );
  22269. }
  22270. }
  22271. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  22272. this.matrixAutoUpdate = false;
  22273. this.normalMatrix = new THREE.Matrix3();
  22274. this.update();
  22275. };
  22276. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  22277. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  22278. var v1 = new THREE.Vector3();
  22279. return function( object ) {
  22280. var keys = [ 'a', 'b', 'c', 'd' ];
  22281. this.object.updateMatrixWorld( true );
  22282. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22283. var vertices = this.geometry.vertices;
  22284. var verts = this.object.geometry.vertices;
  22285. var faces = this.object.geometry.faces;
  22286. var worldMatrix = this.object.matrixWorld;
  22287. var idx = 0;
  22288. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22289. var face = faces[ i ];
  22290. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  22291. var vertexId = face[ keys[ j ] ];
  22292. var vertex = verts[ vertexId ];
  22293. var normal = face.vertexNormals[ j ];
  22294. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  22295. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  22296. v1.add( vertices[ idx ] );
  22297. idx = idx + 1;
  22298. vertices[ idx ].copy( v1 );
  22299. idx = idx + 1;
  22300. }
  22301. }
  22302. this.geometry.verticesNeedUpdate = true;
  22303. return this;
  22304. }
  22305. }());
  22306. /**
  22307. * @author mrdoob / http://mrdoob.com/
  22308. * @author WestLangley / http://github.com/WestLangley
  22309. */
  22310. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  22311. this.object = object;
  22312. this.size = ( size !== undefined ) ? size : 1;
  22313. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  22314. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22315. var geometry = new THREE.Geometry();
  22316. var vertices = object.geometry.vertices;
  22317. var faces = object.geometry.faces;
  22318. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22319. var face = faces[ i ];
  22320. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  22321. geometry.vertices.push( new THREE.Vector3() );
  22322. geometry.vertices.push( new THREE.Vector3() );
  22323. }
  22324. }
  22325. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  22326. this.matrixAutoUpdate = false;
  22327. this.update();
  22328. };
  22329. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  22330. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  22331. var v1 = new THREE.Vector3();
  22332. return function( object ) {
  22333. var keys = [ 'a', 'b', 'c', 'd' ];
  22334. this.object.updateMatrixWorld( true );
  22335. var vertices = this.geometry.vertices;
  22336. var verts = this.object.geometry.vertices;
  22337. var faces = this.object.geometry.faces;
  22338. var worldMatrix = this.object.matrixWorld;
  22339. var idx = 0;
  22340. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22341. var face = faces[ i ];
  22342. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  22343. var vertexId = face[ keys[ j ] ];
  22344. var vertex = verts[ vertexId ];
  22345. var tangent = face.vertexTangents[ j ];
  22346. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  22347. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  22348. v1.add( vertices[ idx ] );
  22349. idx = idx + 1;
  22350. vertices[ idx ].copy( v1 );
  22351. idx = idx + 1;
  22352. }
  22353. }
  22354. this.geometry.verticesNeedUpdate = true;
  22355. return this;
  22356. }
  22357. }());
  22358. /**
  22359. * @author mrdoob / http://mrdoob.com/
  22360. */
  22361. THREE.WireframeHelper = function ( object, hex ) {
  22362. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22363. var edge = [ 0, 0 ], hash = {};
  22364. var sortFunction = function ( a, b ) { return a - b };
  22365. var keys = [ 'a', 'b', 'c' ];
  22366. var geometry = new THREE.BufferGeometry();
  22367. if ( object.geometry instanceof THREE.Geometry ) {
  22368. var vertices = object.geometry.vertices;
  22369. var faces = object.geometry.faces;
  22370. var numEdges = 0;
  22371. // allocate maximal size
  22372. var edges = new Uint32Array( 6 * faces.length );
  22373. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22374. var face = faces[ i ];
  22375. for ( var j = 0; j < 3; j ++ ) {
  22376. edge[ 0 ] = face[ keys[ j ] ];
  22377. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22378. edge.sort( sortFunction );
  22379. var key = edge.toString();
  22380. if ( hash[ key ] === undefined ) {
  22381. edges[ 2 * numEdges ] = edge[ 0 ];
  22382. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22383. hash[ key ] = true;
  22384. numEdges ++;
  22385. }
  22386. }
  22387. }
  22388. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  22389. var coords = geometry.attributes.position.array;
  22390. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22391. for ( var j = 0; j < 2; j ++ ) {
  22392. var vertex = vertices[ edges [ 2 * i + j] ];
  22393. var index = 6 * i + 3 * j;
  22394. coords[ index + 0 ] = vertex.x;
  22395. coords[ index + 1 ] = vertex.y;
  22396. coords[ index + 2 ] = vertex.z;
  22397. }
  22398. }
  22399. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  22400. var vertices = object.geometry.attributes.position.array;
  22401. var indices = object.geometry.attributes.index.array;
  22402. var offsets = object.geometry.offsets;
  22403. var numEdges = 0;
  22404. // allocate maximal size
  22405. var edges = new Uint32Array( 2 * indices.length );
  22406. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  22407. var start = offsets[ o ].start;
  22408. var count = offsets[ o ].count;
  22409. var index = offsets[ o ].index;
  22410. for ( var i = start, il = start + count; i < il; i += 3 ) {
  22411. for ( var j = 0; j < 3; j ++ ) {
  22412. edge[ 0 ] = index + indices[ i + j ];
  22413. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  22414. edge.sort( sortFunction );
  22415. var key = edge.toString();
  22416. if ( hash[ key ] === undefined ) {
  22417. edges[ 2 * numEdges ] = edge[ 0 ];
  22418. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22419. hash[ key ] = true;
  22420. numEdges ++;
  22421. }
  22422. }
  22423. }
  22424. }
  22425. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  22426. var coords = geometry.attributes.position.array;
  22427. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22428. for ( var j = 0; j < 2; j ++ ) {
  22429. var index = 6 * i + 3 * j;
  22430. var index2 = 3 * edges[ 2 * i + j];
  22431. coords[ index + 0 ] = vertices[ index2 ];
  22432. coords[ index + 1 ] = vertices[ index2 + 1 ];
  22433. coords[ index + 2 ] = vertices[ index2 + 2 ];
  22434. }
  22435. }
  22436. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  22437. var vertices = object.geometry.attributes.position.array;
  22438. var numEdges = vertices.length / 3;
  22439. var numTris = numEdges / 3;
  22440. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  22441. var coords = geometry.attributes.position.array;
  22442. for ( var i = 0, l = numTris; i < l; i ++ ) {
  22443. for ( var j = 0; j < 3; j ++ ) {
  22444. var index = 18 * i + 6 * j;
  22445. var index1 = 9 * i + 3 * j;
  22446. coords[ index + 0 ] = vertices[ index1 ];
  22447. coords[ index + 1 ] = vertices[ index1 + 1 ];
  22448. coords[ index + 2 ] = vertices[ index1 + 2 ];
  22449. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  22450. coords[ index + 3 ] = vertices[ index2 ];
  22451. coords[ index + 4 ] = vertices[ index2 + 1 ];
  22452. coords[ index + 5 ] = vertices[ index2 + 2 ];
  22453. }
  22454. }
  22455. }
  22456. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  22457. this.matrixAutoUpdate = false;
  22458. this.matrixWorld = object.matrixWorld;
  22459. };
  22460. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  22461. /**
  22462. * @author alteredq / http://alteredqualia.com/
  22463. */
  22464. THREE.ImmediateRenderObject = function () {
  22465. THREE.Object3D.call( this );
  22466. this.render = function ( renderCallback ) { };
  22467. };
  22468. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  22469. /**
  22470. * @author mikael emtinger / http://gomo.se/
  22471. * @author alteredq / http://alteredqualia.com/
  22472. */
  22473. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  22474. THREE.Object3D.call( this );
  22475. this.lensFlares = [];
  22476. this.positionScreen = new THREE.Vector3();
  22477. this.customUpdateCallback = undefined;
  22478. if( texture !== undefined ) {
  22479. this.add( texture, size, distance, blending, color );
  22480. }
  22481. };
  22482. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  22483. /*
  22484. * Add: adds another flare
  22485. */
  22486. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  22487. if( size === undefined ) size = -1;
  22488. if( distance === undefined ) distance = 0;
  22489. if( opacity === undefined ) opacity = 1;
  22490. if( color === undefined ) color = new THREE.Color( 0xffffff );
  22491. if( blending === undefined ) blending = THREE.NormalBlending;
  22492. distance = Math.min( distance, Math.max( 0, distance ) );
  22493. this.lensFlares.push( { texture: texture, // THREE.Texture
  22494. size: size, // size in pixels (-1 = use texture.width)
  22495. distance: distance, // distance (0-1) from light source (0=at light source)
  22496. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  22497. scale: 1, // scale
  22498. rotation: 1, // rotation
  22499. opacity: opacity, // opacity
  22500. color: color, // color
  22501. blending: blending } ); // blending
  22502. };
  22503. /*
  22504. * Update lens flares update positions on all flares based on the screen position
  22505. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  22506. */
  22507. THREE.LensFlare.prototype.updateLensFlares = function () {
  22508. var f, fl = this.lensFlares.length;
  22509. var flare;
  22510. var vecX = -this.positionScreen.x * 2;
  22511. var vecY = -this.positionScreen.y * 2;
  22512. for( f = 0; f < fl; f ++ ) {
  22513. flare = this.lensFlares[ f ];
  22514. flare.x = this.positionScreen.x + vecX * flare.distance;
  22515. flare.y = this.positionScreen.y + vecY * flare.distance;
  22516. flare.wantedRotation = flare.x * Math.PI * 0.25;
  22517. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  22518. }
  22519. };
  22520. /**
  22521. * @author alteredq / http://alteredqualia.com/
  22522. */
  22523. THREE.MorphBlendMesh = function( geometry, material ) {
  22524. THREE.Mesh.call( this, geometry, material );
  22525. this.animationsMap = {};
  22526. this.animationsList = [];
  22527. // prepare default animation
  22528. // (all frames played together in 1 second)
  22529. var numFrames = this.geometry.morphTargets.length;
  22530. var name = "__default";
  22531. var startFrame = 0;
  22532. var endFrame = numFrames - 1;
  22533. var fps = numFrames / 1;
  22534. this.createAnimation( name, startFrame, endFrame, fps );
  22535. this.setAnimationWeight( name, 1 );
  22536. };
  22537. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  22538. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  22539. var animation = {
  22540. startFrame: start,
  22541. endFrame: end,
  22542. length: end - start + 1,
  22543. fps: fps,
  22544. duration: ( end - start ) / fps,
  22545. lastFrame: 0,
  22546. currentFrame: 0,
  22547. active: false,
  22548. time: 0,
  22549. direction: 1,
  22550. weight: 1,
  22551. directionBackwards: false,
  22552. mirroredLoop: false
  22553. };
  22554. this.animationsMap[ name ] = animation;
  22555. this.animationsList.push( animation );
  22556. };
  22557. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  22558. var pattern = /([a-z]+)(\d+)/;
  22559. var firstAnimation, frameRanges = {};
  22560. var geometry = this.geometry;
  22561. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  22562. var morph = geometry.morphTargets[ i ];
  22563. var chunks = morph.name.match( pattern );
  22564. if ( chunks && chunks.length > 1 ) {
  22565. var name = chunks[ 1 ];
  22566. var num = chunks[ 2 ];
  22567. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  22568. var range = frameRanges[ name ];
  22569. if ( i < range.start ) range.start = i;
  22570. if ( i > range.end ) range.end = i;
  22571. if ( ! firstAnimation ) firstAnimation = name;
  22572. }
  22573. }
  22574. for ( var name in frameRanges ) {
  22575. var range = frameRanges[ name ];
  22576. this.createAnimation( name, range.start, range.end, fps );
  22577. }
  22578. this.firstAnimation = firstAnimation;
  22579. };
  22580. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  22581. var animation = this.animationsMap[ name ];
  22582. if ( animation ) {
  22583. animation.direction = 1;
  22584. animation.directionBackwards = false;
  22585. }
  22586. };
  22587. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  22588. var animation = this.animationsMap[ name ];
  22589. if ( animation ) {
  22590. animation.direction = -1;
  22591. animation.directionBackwards = true;
  22592. }
  22593. };
  22594. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  22595. var animation = this.animationsMap[ name ];
  22596. if ( animation ) {
  22597. animation.fps = fps;
  22598. animation.duration = ( animation.end - animation.start ) / animation.fps;
  22599. }
  22600. };
  22601. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  22602. var animation = this.animationsMap[ name ];
  22603. if ( animation ) {
  22604. animation.duration = duration;
  22605. animation.fps = ( animation.end - animation.start ) / animation.duration;
  22606. }
  22607. };
  22608. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  22609. var animation = this.animationsMap[ name ];
  22610. if ( animation ) {
  22611. animation.weight = weight;
  22612. }
  22613. };
  22614. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  22615. var animation = this.animationsMap[ name ];
  22616. if ( animation ) {
  22617. animation.time = time;
  22618. }
  22619. };
  22620. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  22621. var time = 0;
  22622. var animation = this.animationsMap[ name ];
  22623. if ( animation ) {
  22624. time = animation.time;
  22625. }
  22626. return time;
  22627. };
  22628. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  22629. var duration = -1;
  22630. var animation = this.animationsMap[ name ];
  22631. if ( animation ) {
  22632. duration = animation.duration;
  22633. }
  22634. return duration;
  22635. };
  22636. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  22637. var animation = this.animationsMap[ name ];
  22638. if ( animation ) {
  22639. animation.time = 0;
  22640. animation.active = true;
  22641. } else {
  22642. console.warn( "animation[" + name + "] undefined" );
  22643. }
  22644. };
  22645. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  22646. var animation = this.animationsMap[ name ];
  22647. if ( animation ) {
  22648. animation.active = false;
  22649. }
  22650. };
  22651. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  22652. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  22653. var animation = this.animationsList[ i ];
  22654. if ( ! animation.active ) continue;
  22655. var frameTime = animation.duration / animation.length;
  22656. animation.time += animation.direction * delta;
  22657. if ( animation.mirroredLoop ) {
  22658. if ( animation.time > animation.duration || animation.time < 0 ) {
  22659. animation.direction *= -1;
  22660. if ( animation.time > animation.duration ) {
  22661. animation.time = animation.duration;
  22662. animation.directionBackwards = true;
  22663. }
  22664. if ( animation.time < 0 ) {
  22665. animation.time = 0;
  22666. animation.directionBackwards = false;
  22667. }
  22668. }
  22669. } else {
  22670. animation.time = animation.time % animation.duration;
  22671. if ( animation.time < 0 ) animation.time += animation.duration;
  22672. }
  22673. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  22674. var weight = animation.weight;
  22675. if ( keyframe !== animation.currentFrame ) {
  22676. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  22677. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  22678. this.morphTargetInfluences[ keyframe ] = 0;
  22679. animation.lastFrame = animation.currentFrame;
  22680. animation.currentFrame = keyframe;
  22681. }
  22682. var mix = ( animation.time % frameTime ) / frameTime;
  22683. if ( animation.directionBackwards ) mix = 1 - mix;
  22684. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  22685. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  22686. }
  22687. };
  22688. /**
  22689. * @author mikael emtinger / http://gomo.se/
  22690. * @author alteredq / http://alteredqualia.com/
  22691. */
  22692. THREE.LensFlarePlugin = function () {
  22693. var _gl, _renderer, _precision, _lensFlare = {};
  22694. this.init = function ( renderer ) {
  22695. _gl = renderer.context;
  22696. _renderer = renderer;
  22697. _precision = renderer.getPrecision();
  22698. _lensFlare.vertices = new Float32Array( 8 + 8 );
  22699. _lensFlare.faces = new Uint16Array( 6 );
  22700. var i = 0;
  22701. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  22702. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  22703. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  22704. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  22705. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22706. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22707. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  22708. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  22709. i = 0;
  22710. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  22711. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  22712. // buffers
  22713. _lensFlare.vertexBuffer = _gl.createBuffer();
  22714. _lensFlare.elementBuffer = _gl.createBuffer();
  22715. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22716. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  22717. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22718. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  22719. // textures
  22720. _lensFlare.tempTexture = _gl.createTexture();
  22721. _lensFlare.occlusionTexture = _gl.createTexture();
  22722. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22723. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  22724. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22725. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22726. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22727. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22728. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22729. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  22730. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22731. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22732. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22733. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22734. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  22735. _lensFlare.hasVertexTexture = false;
  22736. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  22737. } else {
  22738. _lensFlare.hasVertexTexture = true;
  22739. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  22740. }
  22741. _lensFlare.attributes = {};
  22742. _lensFlare.uniforms = {};
  22743. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  22744. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  22745. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  22746. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  22747. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  22748. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  22749. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  22750. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  22751. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  22752. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  22753. };
  22754. /*
  22755. * Render lens flares
  22756. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  22757. * reads these back and calculates occlusion.
  22758. * Then _lensFlare.update_lensFlares() is called to re-position and
  22759. * update transparency of flares. Then they are rendered.
  22760. *
  22761. */
  22762. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22763. var flares = scene.__webglFlares,
  22764. nFlares = flares.length;
  22765. if ( ! nFlares ) return;
  22766. var tempPosition = new THREE.Vector3();
  22767. var invAspect = viewportHeight / viewportWidth,
  22768. halfViewportWidth = viewportWidth * 0.5,
  22769. halfViewportHeight = viewportHeight * 0.5;
  22770. var size = 16 / viewportHeight,
  22771. scale = new THREE.Vector2( size * invAspect, size );
  22772. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  22773. screenPositionPixels = new THREE.Vector2( 1, 1 );
  22774. var uniforms = _lensFlare.uniforms,
  22775. attributes = _lensFlare.attributes;
  22776. // set _lensFlare program and reset blending
  22777. _gl.useProgram( _lensFlare.program );
  22778. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  22779. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  22780. // loop through all lens flares to update their occlusion and positions
  22781. // setup gl and common used attribs/unforms
  22782. _gl.uniform1i( uniforms.occlusionMap, 0 );
  22783. _gl.uniform1i( uniforms.map, 1 );
  22784. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22785. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22786. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22787. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22788. _gl.disable( _gl.CULL_FACE );
  22789. _gl.depthMask( false );
  22790. var i, j, jl, flare, sprite;
  22791. for ( i = 0; i < nFlares; i ++ ) {
  22792. size = 16 / viewportHeight;
  22793. scale.set( size * invAspect, size );
  22794. // calc object screen position
  22795. flare = flares[ i ];
  22796. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  22797. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  22798. tempPosition.applyProjection( camera.projectionMatrix );
  22799. // setup arrays for gl programs
  22800. screenPosition.copy( tempPosition )
  22801. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  22802. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  22803. // screen cull
  22804. if ( _lensFlare.hasVertexTexture || (
  22805. screenPositionPixels.x > 0 &&
  22806. screenPositionPixels.x < viewportWidth &&
  22807. screenPositionPixels.y > 0 &&
  22808. screenPositionPixels.y < viewportHeight ) ) {
  22809. // save current RGB to temp texture
  22810. _gl.activeTexture( _gl.TEXTURE1 );
  22811. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22812. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22813. // render pink quad
  22814. _gl.uniform1i( uniforms.renderType, 0 );
  22815. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22816. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22817. _gl.disable( _gl.BLEND );
  22818. _gl.enable( _gl.DEPTH_TEST );
  22819. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22820. // copy result to occlusionMap
  22821. _gl.activeTexture( _gl.TEXTURE0 );
  22822. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22823. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22824. // restore graphics
  22825. _gl.uniform1i( uniforms.renderType, 1 );
  22826. _gl.disable( _gl.DEPTH_TEST );
  22827. _gl.activeTexture( _gl.TEXTURE1 );
  22828. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22829. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22830. // update object positions
  22831. flare.positionScreen.copy( screenPosition )
  22832. if ( flare.customUpdateCallback ) {
  22833. flare.customUpdateCallback( flare );
  22834. } else {
  22835. flare.updateLensFlares();
  22836. }
  22837. // render flares
  22838. _gl.uniform1i( uniforms.renderType, 2 );
  22839. _gl.enable( _gl.BLEND );
  22840. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  22841. sprite = flare.lensFlares[ j ];
  22842. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  22843. screenPosition.x = sprite.x;
  22844. screenPosition.y = sprite.y;
  22845. screenPosition.z = sprite.z;
  22846. size = sprite.size * sprite.scale / viewportHeight;
  22847. scale.x = size * invAspect;
  22848. scale.y = size;
  22849. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22850. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22851. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22852. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  22853. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  22854. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  22855. _renderer.setTexture( sprite.texture, 1 );
  22856. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22857. }
  22858. }
  22859. }
  22860. }
  22861. // restore gl
  22862. _gl.enable( _gl.CULL_FACE );
  22863. _gl.enable( _gl.DEPTH_TEST );
  22864. _gl.depthMask( true );
  22865. };
  22866. function createProgram ( shader, precision ) {
  22867. var program = _gl.createProgram();
  22868. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22869. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22870. var prefix = "precision " + precision + " float;\n";
  22871. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22872. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22873. _gl.compileShader( fragmentShader );
  22874. _gl.compileShader( vertexShader );
  22875. _gl.attachShader( program, fragmentShader );
  22876. _gl.attachShader( program, vertexShader );
  22877. _gl.linkProgram( program );
  22878. return program;
  22879. };
  22880. };
  22881. /**
  22882. * @author alteredq / http://alteredqualia.com/
  22883. */
  22884. THREE.ShadowMapPlugin = function () {
  22885. var _gl,
  22886. _renderer,
  22887. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22888. _frustum = new THREE.Frustum(),
  22889. _projScreenMatrix = new THREE.Matrix4(),
  22890. _min = new THREE.Vector3(),
  22891. _max = new THREE.Vector3(),
  22892. _matrixPosition = new THREE.Vector3();
  22893. this.init = function ( renderer ) {
  22894. _gl = renderer.context;
  22895. _renderer = renderer;
  22896. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22897. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22898. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22899. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22900. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22901. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22902. _depthMaterial._shadowPass = true;
  22903. _depthMaterialMorph._shadowPass = true;
  22904. _depthMaterialSkin._shadowPass = true;
  22905. _depthMaterialMorphSkin._shadowPass = true;
  22906. };
  22907. this.render = function ( scene, camera ) {
  22908. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  22909. this.update( scene, camera );
  22910. };
  22911. this.update = function ( scene, camera ) {
  22912. var i, il, j, jl, n,
  22913. shadowMap, shadowMatrix, shadowCamera,
  22914. program, buffer, material,
  22915. webglObject, object, light,
  22916. renderList,
  22917. lights = [],
  22918. k = 0,
  22919. fog = null;
  22920. // set GL state for depth map
  22921. _gl.clearColor( 1, 1, 1, 1 );
  22922. _gl.disable( _gl.BLEND );
  22923. _gl.enable( _gl.CULL_FACE );
  22924. _gl.frontFace( _gl.CCW );
  22925. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22926. _gl.cullFace( _gl.FRONT );
  22927. } else {
  22928. _gl.cullFace( _gl.BACK );
  22929. }
  22930. _renderer.setDepthTest( true );
  22931. // preprocess lights
  22932. // - skip lights that are not casting shadows
  22933. // - create virtual lights for cascaded shadow maps
  22934. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  22935. light = scene.__lights[ i ];
  22936. if ( ! light.castShadow ) continue;
  22937. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  22938. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  22939. var virtualLight;
  22940. if ( ! light.shadowCascadeArray[ n ] ) {
  22941. virtualLight = createVirtualLight( light, n );
  22942. virtualLight.originalCamera = camera;
  22943. var gyro = new THREE.Gyroscope();
  22944. gyro.position.copy( light.shadowCascadeOffset );
  22945. gyro.add( virtualLight );
  22946. gyro.add( virtualLight.target );
  22947. camera.add( gyro );
  22948. light.shadowCascadeArray[ n ] = virtualLight;
  22949. console.log( "Created virtualLight", virtualLight );
  22950. } else {
  22951. virtualLight = light.shadowCascadeArray[ n ];
  22952. }
  22953. updateVirtualLight( light, n );
  22954. lights[ k ] = virtualLight;
  22955. k ++;
  22956. }
  22957. } else {
  22958. lights[ k ] = light;
  22959. k ++;
  22960. }
  22961. }
  22962. // render depth map
  22963. for ( i = 0, il = lights.length; i < il; i ++ ) {
  22964. light = lights[ i ];
  22965. if ( ! light.shadowMap ) {
  22966. var shadowFilter = THREE.LinearFilter;
  22967. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  22968. shadowFilter = THREE.NearestFilter;
  22969. }
  22970. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  22971. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  22972. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  22973. light.shadowMatrix = new THREE.Matrix4();
  22974. }
  22975. if ( ! light.shadowCamera ) {
  22976. if ( light instanceof THREE.SpotLight ) {
  22977. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  22978. } else if ( light instanceof THREE.DirectionalLight ) {
  22979. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  22980. } else {
  22981. console.error( "Unsupported light type for shadow" );
  22982. continue;
  22983. }
  22984. scene.add( light.shadowCamera );
  22985. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22986. }
  22987. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  22988. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  22989. light.shadowCamera.add( light.cameraHelper );
  22990. }
  22991. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  22992. updateShadowCamera( camera, light );
  22993. }
  22994. shadowMap = light.shadowMap;
  22995. shadowMatrix = light.shadowMatrix;
  22996. shadowCamera = light.shadowCamera;
  22997. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  22998. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  22999. shadowCamera.lookAt( _matrixPosition );
  23000. shadowCamera.updateMatrixWorld();
  23001. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  23002. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  23003. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  23004. // compute shadow matrix
  23005. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  23006. 0.0, 0.5, 0.0, 0.5,
  23007. 0.0, 0.0, 0.5, 0.5,
  23008. 0.0, 0.0, 0.0, 1.0 );
  23009. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23010. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23011. // update camera matrices and frustum
  23012. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23013. _frustum.setFromMatrix( _projScreenMatrix );
  23014. // render shadow map
  23015. _renderer.setRenderTarget( shadowMap );
  23016. _renderer.clear();
  23017. // set object matrices & frustum culling
  23018. renderList = scene.__webglObjects;
  23019. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23020. webglObject = renderList[ j ];
  23021. object = webglObject.object;
  23022. webglObject.render = false;
  23023. if ( object.visible && object.castShadow ) {
  23024. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  23025. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  23026. webglObject.render = true;
  23027. }
  23028. }
  23029. }
  23030. // render regular objects
  23031. var objectMaterial, useMorphing, useSkinning;
  23032. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23033. webglObject = renderList[ j ];
  23034. if ( webglObject.render ) {
  23035. object = webglObject.object;
  23036. buffer = webglObject.buffer;
  23037. // culling is overriden globally for all objects
  23038. // while rendering depth map
  23039. // need to deal with MeshFaceMaterial somehow
  23040. // in that case just use the first of material.materials for now
  23041. // (proper solution would require to break objects by materials
  23042. // similarly to regular rendering and then set corresponding
  23043. // depth materials per each chunk instead of just once per object)
  23044. objectMaterial = getObjectMaterial( object );
  23045. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  23046. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  23047. if ( object.customDepthMaterial ) {
  23048. material = object.customDepthMaterial;
  23049. } else if ( useSkinning ) {
  23050. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  23051. } else if ( useMorphing ) {
  23052. material = _depthMaterialMorph;
  23053. } else {
  23054. material = _depthMaterial;
  23055. }
  23056. if ( buffer instanceof THREE.BufferGeometry ) {
  23057. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  23058. } else {
  23059. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  23060. }
  23061. }
  23062. }
  23063. // set matrices and render immediate objects
  23064. renderList = scene.__webglObjectsImmediate;
  23065. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23066. webglObject = renderList[ j ];
  23067. object = webglObject.object;
  23068. if ( object.visible && object.castShadow ) {
  23069. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  23070. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  23071. }
  23072. }
  23073. }
  23074. // restore GL state
  23075. var clearColor = _renderer.getClearColor(),
  23076. clearAlpha = _renderer.getClearAlpha();
  23077. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  23078. _gl.enable( _gl.BLEND );
  23079. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  23080. _gl.cullFace( _gl.BACK );
  23081. }
  23082. };
  23083. function createVirtualLight( light, cascade ) {
  23084. var virtualLight = new THREE.DirectionalLight();
  23085. virtualLight.isVirtual = true;
  23086. virtualLight.onlyShadow = true;
  23087. virtualLight.castShadow = true;
  23088. virtualLight.shadowCameraNear = light.shadowCameraNear;
  23089. virtualLight.shadowCameraFar = light.shadowCameraFar;
  23090. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  23091. virtualLight.shadowCameraRight = light.shadowCameraRight;
  23092. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  23093. virtualLight.shadowCameraTop = light.shadowCameraTop;
  23094. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  23095. virtualLight.shadowDarkness = light.shadowDarkness;
  23096. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  23097. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  23098. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  23099. virtualLight.pointsWorld = [];
  23100. virtualLight.pointsFrustum = [];
  23101. var pointsWorld = virtualLight.pointsWorld,
  23102. pointsFrustum = virtualLight.pointsFrustum;
  23103. for ( var i = 0; i < 8; i ++ ) {
  23104. pointsWorld[ i ] = new THREE.Vector3();
  23105. pointsFrustum[ i ] = new THREE.Vector3();
  23106. }
  23107. var nearZ = light.shadowCascadeNearZ[ cascade ];
  23108. var farZ = light.shadowCascadeFarZ[ cascade ];
  23109. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  23110. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  23111. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  23112. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  23113. pointsFrustum[ 4 ].set( -1, -1, farZ );
  23114. pointsFrustum[ 5 ].set( 1, -1, farZ );
  23115. pointsFrustum[ 6 ].set( -1, 1, farZ );
  23116. pointsFrustum[ 7 ].set( 1, 1, farZ );
  23117. return virtualLight;
  23118. }
  23119. // Synchronize virtual light with the original light
  23120. function updateVirtualLight( light, cascade ) {
  23121. var virtualLight = light.shadowCascadeArray[ cascade ];
  23122. virtualLight.position.copy( light.position );
  23123. virtualLight.target.position.copy( light.target.position );
  23124. virtualLight.lookAt( virtualLight.target );
  23125. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  23126. virtualLight.shadowDarkness = light.shadowDarkness;
  23127. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  23128. var nearZ = light.shadowCascadeNearZ[ cascade ];
  23129. var farZ = light.shadowCascadeFarZ[ cascade ];
  23130. var pointsFrustum = virtualLight.pointsFrustum;
  23131. pointsFrustum[ 0 ].z = nearZ;
  23132. pointsFrustum[ 1 ].z = nearZ;
  23133. pointsFrustum[ 2 ].z = nearZ;
  23134. pointsFrustum[ 3 ].z = nearZ;
  23135. pointsFrustum[ 4 ].z = farZ;
  23136. pointsFrustum[ 5 ].z = farZ;
  23137. pointsFrustum[ 6 ].z = farZ;
  23138. pointsFrustum[ 7 ].z = farZ;
  23139. }
  23140. // Fit shadow camera's ortho frustum to camera frustum
  23141. function updateShadowCamera( camera, light ) {
  23142. var shadowCamera = light.shadowCamera,
  23143. pointsFrustum = light.pointsFrustum,
  23144. pointsWorld = light.pointsWorld;
  23145. _min.set( Infinity, Infinity, Infinity );
  23146. _max.set( -Infinity, -Infinity, -Infinity );
  23147. for ( var i = 0; i < 8; i ++ ) {
  23148. var p = pointsWorld[ i ];
  23149. p.copy( pointsFrustum[ i ] );
  23150. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  23151. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  23152. if ( p.x < _min.x ) _min.x = p.x;
  23153. if ( p.x > _max.x ) _max.x = p.x;
  23154. if ( p.y < _min.y ) _min.y = p.y;
  23155. if ( p.y > _max.y ) _max.y = p.y;
  23156. if ( p.z < _min.z ) _min.z = p.z;
  23157. if ( p.z > _max.z ) _max.z = p.z;
  23158. }
  23159. shadowCamera.left = _min.x;
  23160. shadowCamera.right = _max.x;
  23161. shadowCamera.top = _max.y;
  23162. shadowCamera.bottom = _min.y;
  23163. // can't really fit near/far
  23164. //shadowCamera.near = _min.z;
  23165. //shadowCamera.far = _max.z;
  23166. shadowCamera.updateProjectionMatrix();
  23167. }
  23168. // For the moment just ignore objects that have multiple materials with different animation methods
  23169. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  23170. function getObjectMaterial( object ) {
  23171. return object.material instanceof THREE.MeshFaceMaterial
  23172. ? object.material.materials[ 0 ]
  23173. : object.material;
  23174. };
  23175. };
  23176. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  23177. /**
  23178. * @author mikael emtinger / http://gomo.se/
  23179. * @author alteredq / http://alteredqualia.com/
  23180. */
  23181. THREE.SpritePlugin = function () {
  23182. var _gl, _renderer, _texture;
  23183. var vertices, faces, vertexBuffer, elementBuffer;
  23184. var program, attributes, uniforms;
  23185. this.init = function ( renderer ) {
  23186. _gl = renderer.context;
  23187. _renderer = renderer;
  23188. vertices = new Float32Array( [
  23189. - 0.5, - 0.5, 0, 0,
  23190. 0.5, - 0.5, 1, 0,
  23191. 0.5, 0.5, 1, 1,
  23192. - 0.5, 0.5, 0, 1
  23193. ] );
  23194. faces = new Uint16Array( [
  23195. 0, 1, 2,
  23196. 0, 2, 3
  23197. ] );
  23198. vertexBuffer = _gl.createBuffer();
  23199. elementBuffer = _gl.createBuffer();
  23200. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  23201. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  23202. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  23203. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  23204. program = createProgram();
  23205. attributes = {
  23206. position: _gl.getAttribLocation ( program, 'position' ),
  23207. uv: _gl.getAttribLocation ( program, 'uv' )
  23208. };
  23209. uniforms = {
  23210. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  23211. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  23212. rotation: _gl.getUniformLocation( program, 'rotation' ),
  23213. scale: _gl.getUniformLocation( program, 'scale' ),
  23214. color: _gl.getUniformLocation( program, 'color' ),
  23215. map: _gl.getUniformLocation( program, 'map' ),
  23216. opacity: _gl.getUniformLocation( program, 'opacity' ),
  23217. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  23218. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  23219. fogType: _gl.getUniformLocation( program, 'fogType' ),
  23220. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  23221. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  23222. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  23223. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  23224. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  23225. };
  23226. var canvas = document.createElement( 'canvas' );
  23227. canvas.width = 8;
  23228. canvas.height = 8;
  23229. var context = canvas.getContext( '2d' );
  23230. context.fillStyle = '#ffffff';
  23231. context.fillRect( 0, 0, canvas.width, canvas.height );
  23232. _texture = new THREE.Texture( canvas );
  23233. _texture.needsUpdate = true;
  23234. };
  23235. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  23236. var sprites = scene.__webglSprites,
  23237. nSprites = sprites.length;
  23238. if ( ! nSprites ) return;
  23239. // setup gl
  23240. _gl.useProgram( program );
  23241. _gl.enableVertexAttribArray( attributes.position );
  23242. _gl.enableVertexAttribArray( attributes.uv );
  23243. _gl.disable( _gl.CULL_FACE );
  23244. _gl.enable( _gl.BLEND );
  23245. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  23246. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  23247. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  23248. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  23249. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  23250. _gl.activeTexture( _gl.TEXTURE0 );
  23251. _gl.uniform1i( uniforms.map, 0 );
  23252. var oldFogType = 0;
  23253. var sceneFogType = 0;
  23254. var fog = scene.fog;
  23255. if ( fog ) {
  23256. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  23257. if ( fog instanceof THREE.Fog ) {
  23258. _gl.uniform1f( uniforms.fogNear, fog.near );
  23259. _gl.uniform1f( uniforms.fogFar, fog.far );
  23260. _gl.uniform1i( uniforms.fogType, 1 );
  23261. oldFogType = 1;
  23262. sceneFogType = 1;
  23263. } else if ( fog instanceof THREE.FogExp2 ) {
  23264. _gl.uniform1f( uniforms.fogDensity, fog.density );
  23265. _gl.uniform1i( uniforms.fogType, 2 );
  23266. oldFogType = 2;
  23267. sceneFogType = 2;
  23268. }
  23269. } else {
  23270. _gl.uniform1i( uniforms.fogType, 0 );
  23271. oldFogType = 0;
  23272. sceneFogType = 0;
  23273. }
  23274. // update positions and sort
  23275. var i, sprite, material, fogType, scale = [];
  23276. for( i = 0; i < nSprites; i ++ ) {
  23277. sprite = sprites[ i ];
  23278. material = sprite.material;
  23279. if ( sprite.visible === false ) continue;
  23280. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  23281. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  23282. }
  23283. sprites.sort( painterSortStable );
  23284. // render all sprites
  23285. for( i = 0; i < nSprites; i ++ ) {
  23286. sprite = sprites[ i ];
  23287. if ( sprite.visible === false ) continue;
  23288. material = sprite.material;
  23289. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  23290. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  23291. scale[ 0 ] = sprite.scale.x;
  23292. scale[ 1 ] = sprite.scale.y;
  23293. if ( scene.fog && material.fog ) {
  23294. fogType = sceneFogType;
  23295. } else {
  23296. fogType = 0;
  23297. }
  23298. if ( oldFogType !== fogType ) {
  23299. _gl.uniform1i( uniforms.fogType, fogType );
  23300. oldFogType = fogType;
  23301. }
  23302. if ( material.map !== null ) {
  23303. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  23304. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  23305. } else {
  23306. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  23307. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  23308. }
  23309. _gl.uniform1f( uniforms.opacity, material.opacity );
  23310. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  23311. _gl.uniform1f( uniforms.rotation, material.rotation );
  23312. _gl.uniform2fv( uniforms.scale, scale );
  23313. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  23314. _renderer.setDepthTest( material.depthTest );
  23315. _renderer.setDepthWrite( material.depthWrite );
  23316. if ( material.map && material.map.image && material.map.image.width ) {
  23317. _renderer.setTexture( material.map, 0 );
  23318. } else {
  23319. _renderer.setTexture( _texture, 0 );
  23320. }
  23321. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  23322. }
  23323. // restore gl
  23324. _gl.enable( _gl.CULL_FACE );
  23325. };
  23326. function createProgram () {
  23327. var program = _gl.createProgram();
  23328. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  23329. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  23330. _gl.shaderSource( vertexShader, [
  23331. 'precision ' + _renderer.getPrecision() + ' float;',
  23332. 'uniform mat4 modelViewMatrix;',
  23333. 'uniform mat4 projectionMatrix;',
  23334. 'uniform float rotation;',
  23335. 'uniform vec2 scale;',
  23336. 'uniform vec2 uvOffset;',
  23337. 'uniform vec2 uvScale;',
  23338. 'attribute vec2 position;',
  23339. 'attribute vec2 uv;',
  23340. 'varying vec2 vUV;',
  23341. 'void main() {',
  23342. 'vUV = uvOffset + uv * uvScale;',
  23343. 'vec2 alignedPosition = position * scale;',
  23344. 'vec2 rotatedPosition;',
  23345. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  23346. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  23347. 'vec4 finalPosition;',
  23348. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  23349. 'finalPosition.xy += rotatedPosition;',
  23350. 'finalPosition = projectionMatrix * finalPosition;',
  23351. 'gl_Position = finalPosition;',
  23352. '}'
  23353. ].join( '\n' ) );
  23354. _gl.shaderSource( fragmentShader, [
  23355. 'precision ' + _renderer.getPrecision() + ' float;',
  23356. 'uniform vec3 color;',
  23357. 'uniform sampler2D map;',
  23358. 'uniform float opacity;',
  23359. 'uniform int fogType;',
  23360. 'uniform vec3 fogColor;',
  23361. 'uniform float fogDensity;',
  23362. 'uniform float fogNear;',
  23363. 'uniform float fogFar;',
  23364. 'uniform float alphaTest;',
  23365. 'varying vec2 vUV;',
  23366. 'void main() {',
  23367. 'vec4 texture = texture2D( map, vUV );',
  23368. 'if ( texture.a < alphaTest ) discard;',
  23369. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  23370. 'if ( fogType > 0 ) {',
  23371. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  23372. 'float fogFactor = 0.0;',
  23373. 'if ( fogType == 1 ) {',
  23374. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  23375. '} else {',
  23376. 'const float LOG2 = 1.442695;',
  23377. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  23378. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  23379. '}',
  23380. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  23381. '}',
  23382. '}'
  23383. ].join( '\n' ) );
  23384. _gl.compileShader( vertexShader );
  23385. _gl.compileShader( fragmentShader );
  23386. _gl.attachShader( program, vertexShader );
  23387. _gl.attachShader( program, fragmentShader );
  23388. _gl.linkProgram( program );
  23389. return program;
  23390. };
  23391. function painterSortStable ( a, b ) {
  23392. if ( a.z !== b.z ) {
  23393. return b.z - a.z;
  23394. } else {
  23395. return b.id - a.id;
  23396. }
  23397. };
  23398. };
  23399. /**
  23400. * @author alteredq / http://alteredqualia.com/
  23401. */
  23402. THREE.DepthPassPlugin = function () {
  23403. this.enabled = false;
  23404. this.renderTarget = null;
  23405. var _gl,
  23406. _renderer,
  23407. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  23408. _frustum = new THREE.Frustum(),
  23409. _projScreenMatrix = new THREE.Matrix4();
  23410. this.init = function ( renderer ) {
  23411. _gl = renderer.context;
  23412. _renderer = renderer;
  23413. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  23414. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  23415. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  23416. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  23417. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  23418. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  23419. _depthMaterial._shadowPass = true;
  23420. _depthMaterialMorph._shadowPass = true;
  23421. _depthMaterialSkin._shadowPass = true;
  23422. _depthMaterialMorphSkin._shadowPass = true;
  23423. };
  23424. this.render = function ( scene, camera ) {
  23425. if ( ! this.enabled ) return;
  23426. this.update( scene, camera );
  23427. };
  23428. this.update = function ( scene, camera ) {
  23429. var i, il, j, jl, n,
  23430. program, buffer, material,
  23431. webglObject, object, light,
  23432. renderList,
  23433. fog = null;
  23434. // set GL state for depth map
  23435. _gl.clearColor( 1, 1, 1, 1 );
  23436. _gl.disable( _gl.BLEND );
  23437. _renderer.setDepthTest( true );
  23438. // update scene
  23439. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  23440. // update camera matrices and frustum
  23441. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  23442. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23443. _frustum.setFromMatrix( _projScreenMatrix );
  23444. // render depth map
  23445. _renderer.setRenderTarget( this.renderTarget );
  23446. _renderer.clear();
  23447. // set object matrices & frustum culling
  23448. renderList = scene.__webglObjects;
  23449. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23450. webglObject = renderList[ j ];
  23451. object = webglObject.object;
  23452. webglObject.render = false;
  23453. if ( object.visible ) {
  23454. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  23455. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  23456. webglObject.render = true;
  23457. }
  23458. }
  23459. }
  23460. // render regular objects
  23461. var objectMaterial, useMorphing, useSkinning;
  23462. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23463. webglObject = renderList[ j ];
  23464. if ( webglObject.render ) {
  23465. object = webglObject.object;
  23466. buffer = webglObject.buffer;
  23467. // todo: create proper depth material for particles
  23468. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  23469. objectMaterial = getObjectMaterial( object );
  23470. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  23471. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  23472. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  23473. if ( object.customDepthMaterial ) {
  23474. material = object.customDepthMaterial;
  23475. } else if ( useSkinning ) {
  23476. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  23477. } else if ( useMorphing ) {
  23478. material = _depthMaterialMorph;
  23479. } else {
  23480. material = _depthMaterial;
  23481. }
  23482. if ( buffer instanceof THREE.BufferGeometry ) {
  23483. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  23484. } else {
  23485. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  23486. }
  23487. }
  23488. }
  23489. // set matrices and render immediate objects
  23490. renderList = scene.__webglObjectsImmediate;
  23491. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  23492. webglObject = renderList[ j ];
  23493. object = webglObject.object;
  23494. if ( object.visible ) {
  23495. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  23496. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  23497. }
  23498. }
  23499. // restore GL state
  23500. var clearColor = _renderer.getClearColor(),
  23501. clearAlpha = _renderer.getClearAlpha();
  23502. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  23503. _gl.enable( _gl.BLEND );
  23504. };
  23505. // For the moment just ignore objects that have multiple materials with different animation methods
  23506. // Only the first material will be taken into account for deciding which depth material to use
  23507. function getObjectMaterial( object ) {
  23508. return object.material instanceof THREE.MeshFaceMaterial
  23509. ? object.material.materials[ 0 ]
  23510. : object.material;
  23511. };
  23512. };
  23513. /**
  23514. * @author mikael emtinger / http://gomo.se/
  23515. */
  23516. THREE.ShaderFlares = {
  23517. 'lensFlareVertexTexture': {
  23518. vertexShader: [
  23519. "uniform lowp int renderType;",
  23520. "uniform vec3 screenPosition;",
  23521. "uniform vec2 scale;",
  23522. "uniform float rotation;",
  23523. "uniform sampler2D occlusionMap;",
  23524. "attribute vec2 position;",
  23525. "attribute vec2 uv;",
  23526. "varying vec2 vUV;",
  23527. "varying float vVisibility;",
  23528. "void main() {",
  23529. "vUV = uv;",
  23530. "vec2 pos = position;",
  23531. "if( renderType == 2 ) {",
  23532. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  23533. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  23534. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  23535. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  23536. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  23537. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  23538. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  23539. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  23540. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  23541. "vVisibility = visibility.r / 9.0;",
  23542. "vVisibility *= 1.0 - visibility.g / 9.0;",
  23543. "vVisibility *= visibility.b / 9.0;",
  23544. "vVisibility *= 1.0 - visibility.a / 9.0;",
  23545. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  23546. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  23547. "}",
  23548. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  23549. "}"
  23550. ].join( "\n" ),
  23551. fragmentShader: [
  23552. "uniform lowp int renderType;",
  23553. "uniform sampler2D map;",
  23554. "uniform float opacity;",
  23555. "uniform vec3 color;",
  23556. "varying vec2 vUV;",
  23557. "varying float vVisibility;",
  23558. "void main() {",
  23559. // pink square
  23560. "if( renderType == 0 ) {",
  23561. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  23562. // restore
  23563. "} else if( renderType == 1 ) {",
  23564. "gl_FragColor = texture2D( map, vUV );",
  23565. // flare
  23566. "} else {",
  23567. "vec4 texture = texture2D( map, vUV );",
  23568. "texture.a *= opacity * vVisibility;",
  23569. "gl_FragColor = texture;",
  23570. "gl_FragColor.rgb *= color;",
  23571. "}",
  23572. "}"
  23573. ].join( "\n" )
  23574. },
  23575. 'lensFlare': {
  23576. vertexShader: [
  23577. "uniform lowp int renderType;",
  23578. "uniform vec3 screenPosition;",
  23579. "uniform vec2 scale;",
  23580. "uniform float rotation;",
  23581. "attribute vec2 position;",
  23582. "attribute vec2 uv;",
  23583. "varying vec2 vUV;",
  23584. "void main() {",
  23585. "vUV = uv;",
  23586. "vec2 pos = position;",
  23587. "if( renderType == 2 ) {",
  23588. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  23589. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  23590. "}",
  23591. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  23592. "}"
  23593. ].join( "\n" ),
  23594. fragmentShader: [
  23595. "precision mediump float;",
  23596. "uniform lowp int renderType;",
  23597. "uniform sampler2D map;",
  23598. "uniform sampler2D occlusionMap;",
  23599. "uniform float opacity;",
  23600. "uniform vec3 color;",
  23601. "varying vec2 vUV;",
  23602. "void main() {",
  23603. // pink square
  23604. "if( renderType == 0 ) {",
  23605. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  23606. // restore
  23607. "} else if( renderType == 1 ) {",
  23608. "gl_FragColor = texture2D( map, vUV );",
  23609. // flare
  23610. "} else {",
  23611. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  23612. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  23613. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  23614. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  23615. "visibility = ( 1.0 - visibility / 4.0 );",
  23616. "vec4 texture = texture2D( map, vUV );",
  23617. "texture.a *= opacity * visibility;",
  23618. "gl_FragColor = texture;",
  23619. "gl_FragColor.rgb *= color;",
  23620. "}",
  23621. "}"
  23622. ].join( "\n" )
  23623. }
  23624. };